#discord-bots
1 messages Β· Page 1093 of 1
oh how can i search it then? i need to search the 'text': "text here"
iterate through the list, and grab the text keys
this is getting kinda off-topic for this channel, consider using a more appropriate channel maybe?
ok can you point me toward the docs for iterating?
do you know how to make a for loop?
i think so
then you know how to iterate through a list 
ok lol thanks
me = client.get_user(id)
This returned a NoneType object instead of a member object
also the Id I used was my user id
the method is a cache lookup which can return None
!d discord.ext.commands.Bot.get_user
get_user(id, /)```
Returns a user with the given ID.
Changed in version 2.0: `id` parameter is now positional-only.
How can I exactly fix that so it can return my user id?
you can make an api request, but i recommend you check first in cache and then make the call
Alright, ty
!d discord.ext.commands.Bot.fetch_user
await fetch_user(user_id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User") based on their ID. You do not have to share any guilds with the user to get this information, however many operations do require that you do.
Note
This method is an API call. If you have [`discord.Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members "discord.Intents.members") and member cache enabled, consider [`get_user()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.get_user "discord.ext.commands.Bot.get_user") instead.
Changed in version 2.0: `user_id` parameter is now positional-only.
is the method that calls the api
im making a calculator command (usage: .calc 1k+9.5m) but i need help replacing stuff like 1k to 1000 and 9.5m to 9500000
do i need regex for this and still cant find any lib for safe calculating (some people said to use eval() but i doubt thats safe)
what lang is fastest for discord bots
there is a lib for that lemme see
or u could just create a custom function for that
last sentence
That would probably be pretty easy
Youβd just have to find every number with a letter next to it and have a dictionary with the values of the letter and multiply the number with of the letterβs corresponding value
none, that depends on what language is faster and your code quality
its not like discord will respond faster to javascript and slower to rust
Dudes at what time do y'all even wake up π
6
yall, what libraries are you using?
i switched to https://api.imgbb.com/
Free image hosting and sharing service, upload pictures, photo host. Offers integration solutions for uploading images to forums.
I'm trying disnake currently and it seems relatively intuitive
people here use dpy2.0/hikari/disnake/few use pycord and nextcord
something: Option(choice=[1, 2, 3], description="something") isnt this how you give choices, choices arent showing up though
I'm still trying to figure out how cogs work
selection row?
ye
I've got them working for slash commands but I don't know how to use them for other sorts of interactions
imagine sleeping
hikari 
nobody uses py-cord really
!d discord.SelectOption
class discord.SelectOption(*, label, value=..., description=None, emoji=None, default=False)```
Represents a select menuβs option.
These can be created by users.
New in version 2.0.
so, uh, we have to create multiple of these instead of passing a list ?
no u pass these in the list
Im trying to use cogs for the first time, and my file structure looks like this
hmm, what if i wanted to give the user a list of guild channels to choose from
or members.
ModuleNotFoundError: path attribute not found on 'cogs.events.CommandEvents' while trying to find 'cogs.events.CommandEvents.py'
I get this error
why
Can I not do that?
show code
don't have .py
^
'cogs.events.CommandEvents'
so should I use [:-3] to remove .py
ya
CommandEvents.py.py imagine
literally where you have bot.load_extension("cogs.events.CommandEvents.py") in your code replace it with bot.load_extension("cogs.events.CommandEvents")
imagine manual loading
im not manual loading
I don't have a clue what I'm doing lmao
I just haven't used cogs
π
thats my code
im getting this now
discord.ext.commands.errors.ExtensionNotFound: Extension 'cogs.events.__pycach' could not be loaded.
How to find author through thread? MongoDB -> I have a branch and I need to search MongoDB to find the author of this branch
!d discord.Guild.text_channels
property text_channels```
A list of text channels that belongs to this guild.
This is sorted by the position and are in UI order from top to bottom.
do a check to see if its a .py file like if file.endswith('.py') then load
or just use pathlib
Guild channels
if were going by that its Guild.channels
~~```py
for file in pathlib.Path(path-to-cogs-dir).glob('**/*.py'):
bot.load_extension(file[:-3])
and how do you access a property ?
you can just use os.listdir
recursive dir
bro ryuga thats sus
π³ os.listdir bad
discord.ext.commands.errors.NoEntryPointError: Extension 'cogs.events.__pycache__' has no 'setup' function.
.... π¦
check if the file starts with an underscore
import pathlib
for cog in pathlib.Path('cogs').glob('*.py'):
bot.load_extension(f'cogs.{cog.stem}')
oops, didn't mean for that to be a reply but oh well
that does the trick
How to find author through thread? MongoDB -> I have a branch and I need to search MongoDB to find the author of this branch
shouldve used the import dunderπ
thats what the folder looks like. im pulling CommandEvents
what now?
how do you access a property.
you can use __import__("module_name")
which returns a module object
no clue what that means lmao
!e
print(__import__("random").randint(1, 10))
@slate swan :white_check_mark: Your eval job has completed with return code 0.
5
i forget that isnt like range smh
for cog in __import__("pathlib").Path('cogs').glob('*.py'):
bot.load_extension(f'cogs.{cog.stem}')
but why
would deny on that
i have tried it before, but couldnt figure out how to access a property.
gave up on using cogs like 6 months ago but I finally got it
π
are cogs all that beneficial?
wdym access it?
ya they are great for organizing
yes
Oh please could you introduce me
π³ u ping = u talk
alright bro thank you bro
what can you put in a cog?
for example, can I put on_ready stuff in a cog?
if so, how?
and good for mutating the source code of your bot without disconnecting from the gateway
ya, u would use Cog.listener
yes you can with a listener but it can still be used with the decorator thats bound to the Bot class
listener* π
π .
do yall care to elaborate or should I just try to figure it out?
!d discord.ext.commands.Cog.listener
classmethod listener(name=...)```
A decorator that marks a function as a listener.
This is the cog equivalent of [`Bot.listen()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.listen "discord.ext.commands.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...
how do i make a button view time out after a certain amount of time
timeout=None makes it never timeout but subbing in a number makes it time out instantly
!d discord.ui.View.timeout
property timeout```
The timeout in seconds from last interaction with the UI before no longer accepting input. If `None` then there is no timeout.
cool well I still don't know what I'm doing but it's not erroring in VSC so that's a good start
.
i thought this was the kwarg smh
#progression
when do u want it to timeout
bro
couple seconds
rip
okay well it doesn't work
just do timeout=couple seconds π³
it doesnt work
it times out instantly
wdym doesn't work? show code
class Fight3(discord.ui.View):
def __init__(self, context: commands.Context):
super().__init__(timeout=4)```
it's hideous
Β―_(γ)_/Β―
4 seconds lol
ok
want to share a working example?
so this will timeout after 4 seconds.... what is the problem
what do you expect ofc it will timeoutπ
it times out instantly
is the problem (no matter what time)
u sure ur using Fight3 view?
yes
do you have a working example of this?
are you sure its a timeout and not interaction fails?
@commands.Cog.listener("on_ready")
async def random_function_name(self) -> None:
print("my cache has been populated")
because wait for the view and the else statement triggers instantly and the button doesnt work
ur subclassing view and using wait_for? why π
why is await view3.wait() bad
care to tell me everything that's wrong with it?
from disnake.ext import commands
from bot import SERVERID
class OnReady(commands.Cog):
def __init__(self, bot: commands.Bot.listen):
self.bot = bot
@commands.Cog.listener()
async def on_ready(self):
print(f'{self.bot.user.name} has connected to Discord!')
print("The bot is ready!")
guild = self.bot.get_guild(int(SERVERID))
members = '\n - '.join([member.name for member in guild.members])
print(
f'{self.bot.user.name} is connected to the following guild:\n'
f'{guild.name} (id: {guild.id})\n'
f'Guild Members:\n - {members}'
)
def setup(bot: commands.Bot.listen):
bot.add_cog(OnReady(bot))
just do
class Fight3(discord.ui.View):
def __init__(self, context: commands.Context):
super().__init__(timeout=4)
@discord.ui.button(...)
async def callback_for_this_button(...):
...
just do this, why do u need wait_for ?
im confused
did you loaded the cog and your annotations are not correct
wdym by any of that
no u just do ctx.send(..., view=Fight3(ctx))
yes i do that
what do u want to do when someone clicks the button?
bot: commands.Bot.listen
here in the argument you pass your Bot object to, you annotated it as a decorator
and if it doesnt fire did you loaded the cog?
oh uh yeah I have no clue what I'm doing there
well i need it in my main command
but it does work
does it get called?
import pathlib
for cog in pathlib.Path('cogs').rglob('*.py'):
bot.load_extension(f'cogs.{cog.stem}')
Hey okimii π
pretty sure that calls it?
hi sparky!
that loads the cog, i ment the on_ready method
I don't have a clue but this is the output when I run it:
PS C:\Users\carso\Documents\Discord Bots\Bot 2> & C:/Users/carso/AppData/Local/Programs/Python/Python310/python.exe "c:/Users/carso/Documents/Discord Bots/Bot 2/bot.py"
Magic DisBot has connected to Discord!
The bot is ready!
Magic DisBot is connected to the following guild:
Simplex (id: 983259662411501578)
Guild Members:
- Carson
- CC
- Magic DisBot
need what?
thats perfect
so it seems to be working as intended, probably/maybe/I hope
whats wrong there?
oh it was all horribly wrong but like I said, it seems to be working'
after I've fixed some stuff
seems correct but your first sentence isnt correct lol
oh? how so
nvm.
the first bit is the 'being run' part and the rest is the output, if that's what you mean
on_ready gets fired on cache population and not connecting to the gateway
!d discord.on_connect
discord.on_connect()```
Called when the client has successfully connected to Discord. This is not the same as the client being fully prepared, see [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready "discord.on_ready") for that.
The warnings on [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready "discord.on_ready") also apply.
oh, I see
ah, I see
yeah, that makes sense
so then this should be good?
from disnake.ext import commands
from bot import SERVERID
class OnConnect(commands.Cog):
def __init__(self, bot: commands.Bot.listen):
self.bot = bot
@commands.Cog.listener()
async def on_connect(self):
print(f'{self.bot.user.name} has connected to Discord!')
print("The bot is ready!")
guild = self.bot.get_guild(int(SERVERID))
members = '\n - '.join([member.name for member in guild.members])
print(
f'{self.bot.user.name} is connected to the following guild:\n'
f'{guild.name} (id: {guild.id})\n'
f'Guild Members:\n - {members}'
)
def setup(bot):
bot.add_cog(OnConnect(bot))
yes but now your second sentence isnt correct lmao
the bot wont be ready and it wont ever print the guild members
your clients cache hasnt been set up yet so you would need to use Bot.wait_until_ready
it does print the guild members
What's the issue
i mean it can but i think its not always the same result
it all appears to be working, I just want to make sure I'm following best practices
so what should I do to fix it then?
!d discord.ext.commands.Bot.wait_until_ready
await wait_until_ready()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits until the clientβs internal cache is all ready.
Warning
Calling this inside [`setup_hook()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.setup_hook "discord.ext.commands.Bot.setup_hook") can lead to a deadlock.
can be used
ποΈ
yeah, it's not working now lol
so is there a solution, or do I just use on_connect and forget about it?
do whatever you like lol
fair enough
oh, I do have one more question
I know that with Client it's possible to respond to messages without a prefix
is the same possible with Bot?
with on_message? yeah
the Bot class is the subclass of Client so everything the Client has the Bot has aswell
!d discord.ext.commands.Bot
class discord.ext.commands.Bot(command_prefix, *, help_command=<default-help-command>, tree_cls=<class 'discord.app_commands.tree.CommandTree'>, description=None, intents, **options)```
Represents a discord bot.
This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") you can do with this bot.
This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.
Unlike [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client"), This class does not require manually setting a [`CommandTree`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree "discord.app_commands.CommandTree") and is automatically set upon instantiating the class.
oh
yeah so I just had it give an inconsistent result
I just don't know what I could do to get around the issue
just use on_ready
alright lol
okay... yikes
I'm definitely not ready to be messing around with modals lol
I've already got the disnake tutorial one working
both the high-level and low-level implementation
as cogs no less
Awesome! π
I just should probably try to understand the basics before I move on to more complicated things lol
although tbf that's really not my style
can anyone give me an example how to use
create_sticker()
with message.attachments
!d discord.Guild.create_sticker ( checking docs )
i have seen not sure what to add in file
hmm... I don't know that I can add message-id to the modal's id in the high-level implementation
here's what the code looks like:
import disnake
from disnake.ext import commands
from disnake import TextInputStyle
class MyModal(disnake.ui.Modal):
def __init__(self):
# The details of the modal, and its components
components = [
disnake.ui.TextInput(
label="Name",
placeholder="Foo Tag",
custom_id="name",
style=TextInputStyle.short,
max_length=50,
),
disnake.ui.TextInput(
label="Description",
placeholder="Lorem ipsum dolor sit amet.",
custom_id="description",
style=TextInputStyle.paragraph,
),
]
super().__init__(
title="Create Tag",
custom_id="create_tag", # the message ID needs to go here appended to the end
components=components,
)
# The callback received when the user input is completed.
async def callback(self, inter: disnake.ModalInteraction):
embed = disnake.Embed(title="Tag Creation")
for key, value in inter.text_values.items():
embed.add_field(
name=key.capitalize(),
value=value[:1024],
inline=False,
)
await inter.response.send_message(embed=embed)
# The command that creates the modal
class ModalHCommand(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.slash_command()
async def taghigh(inter):
"""Sends a Modal to create a tag."""
await inter.response.send_modal(modal=MyModal(inter))
def setup(bot):
bot.add_cog(ModalHCommand(bot))
!d disnake.Attachment.read
await read(*, use_cached=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves the content of this attachment as a [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes "(in Python v3.10)") object.
New in version 1.1.
this gives you the bytes data
you can use io.BytesIO to convert it into io.BufferedIOBase, and then pass it in discord.File to use it for the file kwarg
okay
Lmao I don't want to sleep all day long by not sleeping at night
Nothing to do anyways
Bro
Nice
In mongoDB, how do I get the ticket author from this list?
tickets[0].get('author') ig?
There is more than one element in the list
There may be many
I need to somehow get the author of this ticket and so for each ticket separately
basically, you have a thread id and you want the author id revalent to it, correct?
yea
Best thing. Use json.dumps and send the string form of dict to the MongoDB
But I don't know how to implement it in mongoDB
What module u using?
disnake
For MongoDB
i would just py thread = [ obj.get("author") for obj in tickets if obj.get("thread")== thread_id] 
Ohh, pymongo
and use the 0th index if the list was not empty
Use loop.run_in_executor
not sure if mongo provides some better internal ways
That's the way, yea iirc
so?
Used Mongo only once for HunAI and i am never using it again
inter.channel.id = thread.id
this ^
thread there is a list.
i find relational dbs easier to use, more readable π₯΄
can you try printing the tickets variable?
ah you did it wrong, you need to use the [0] on the thread variable, not the tickets variable inside the list comp
it would look like i would just ```py
thread = [ obj.get("author") for obj in tickets if obj.get("thread")== thread_id][0]
so?
I find JSON files the best DB
but if the data for that channel is not there in the db, the list will be empty and you will get an IndexError
Why are you doing obj.get("author") are there any cases in which author isn't available?
The author is always available
In case it leaves the server, it's worth checking
and it would return None if its not anyways
you can always check for it
YEeeeeeeeeeeeeeeeeeeeeeeeeeeeeee
thanks you so much
pleasure, also make a check for the cases i and sift just mentioned ( the list being empty or if the author is missing ), tho its shouldnt happen since you save the data for each thread right?
yea
You could ust do obj[1] then
could I get some help with this bit?
I don't think it's hard, I just don't know how to do it
I also have a bunch of checks, and if the user leaves the server, the on_member_remove event will work and if the user has an open ticket, the bot will delete him from the database
Okay, thanks
no?
thanks :D worked
!e ```py
obj = { "apple" : 0 }
print(obj[0])
@slate swan :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 2, in <module>
003 | KeyError: 0
Why not?
you see why^
Mb, obj['author']*
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: __init__() got an unexpected keyword argument 'label'
components = [
[discord.Button(
label='Next meme',
style=discord.ButtonStyle.blurple,
custom_id='next'),
discord.Button(
label='End interaction',
style=discord.ButtonStyle.red,
custom_id='exit')]]
message = await ctx.send(embed=meme_opt(), components=components)
id=message.id
yep
ah alright, all cool then.
It's discord.ui.Button, discord.Button is something else
For some reason, if several tickets are open, then this only works in one of them
and the data exists for other ticket too?
yea
When creating a new ticket, all data is recorded in the same way
do you get some errors or something?
No, just below the button, it just says "Interaction error"
nothing in ur terminal?
yea, only this
But in another ticket - everything works
your current code is checking the the tickets owned by the user who clicked the button, so you won't be able to see threads owned by others ( where author id is not ur id )
That's why I wrote the user ID in the database
What message ID? Sending a modal doesn't give a message?
try asking the author registered with that thread to do that interaction, that should do...
nah, I got it
the modal worked, but if the user hit cancel instead of send it would be stored for any user that wanted to use the modal
I wanted to add the user's ID so that the message would persist only for the user (or I could use the message ID and make it not persist at all)
I did so and now it displays everything correctly, as I need
pog
π
how do you stop output from a cog (excluding errors) from being displayed in the console?
Yeah ^
is there a way to hide the print statement from a cog without removing print()?
What does that even mean?
print is a function that writes to the console. That's all that it does.
Add this line at the top?
import sys
sys.stdout = None
If you want it to not write to the console, remove the print
Or if you want to see it but don't want it to run for whatever reason, comment it out
thanks, this worked
Add that line to the init (the second one)
yeah but its annoying to remove and add the all the print() everytime i want to see it
Ah, I see. That still doesn't seem like the most effective method but it's about the only thing that makes sense lol
ext/commands/core.py", line 209, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NameError: name 'view' is not defined
r=requests.get("https://meme-api.herokuapp.com/gimme")
res=r.json()
title=res["title"]
ups=res["ups"]
author=res["author"]
link=res["postLink"]
memes = discord.Embed(description=f"[{title}]({link})",colour=0x2f3136)
memes.set_image(url=res["url"])
memes.set_footer(text=f"π : {ups} βοΈ : {author}")
return memes
view = discord.ui.View()
item1 = discord.ui.Button(
label='Next meme',
style=discord.ButtonStyle.blurple,
custom_id='next')
item2 = discord.ui.Button(
label='End interaction',
style=discord.ButtonStyle.red,
custom_id='exit')
view.add_item(item1)
view.add_item(item2)
message = await ctx.send(embed=meme_opt(), view=view)
id=message.id
indents
!indent
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
how do i fix this error, when i run it on repl etc it works but not on desktop
Hunter is so smart
Meh
tried earlier still showed error
wtf do you mean be dpy v2 wtf
.......?
dpy v2 has interactions lol
So i meant dpy v2
Just telling him the same thing- Use a fork or 2.0
but but, they are just the forks of discord.py not v2
"use a fork of dpy or dpy v2"
*what's a discord.py fork, and what's discord.py v2 fork?
elaborate
I never said v2 fork smh
Ah wait nvm
I meant either use fork of dpy or use dpy v2
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.image' raised an error: IndentationError: expected an indented block (image.py, line 462)
id=message.id
while True:
try:
interaction = await self.bot.wait_for(
'button_click',
check=lambda inter: inter.message.id == message.id,
timeout=30)
except asyncio.TimeoutError:
for row in components:
row.disable_components()
return await message.edit(view=view)
if(interaction.author.id==ctx.author.id):
if(interaction.custom_id=="next"):
await interaction.edit_origin(embed=meme_opt(),view=view)
elif(interaction.custom_id=="exit"):
for row in components:
row.disable_components()
message=await ctx.fetch_message(id)
return await interaction.edit_origin(embed=message.embeds[0],view=view)
else:
await interaction.send("Hey! This is not for you!")
yes, that looks correct
!indent
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
The person I was helping understood, so I ain't editing the msg now
yes i did leave space now
Show a screenshot of the code
weird u already have an indent if I ain't missing smth
try:
interaction = ...``` π«
```py
try:
interaction = ...``` β
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.image' raised an error: SyntaxError: invalid syntax (image.py, line 472)
elif(interaction.custom_id=="exit"):
except asyncio.TimeoutError:
for row in components:
row.disable_components()
return await message.edit(view=view)
if(interaction.author.id==ctx.author.id):
if(interaction.custom_id=="next"):
await interaction.edit_origin(embed=meme_opt(),view=view)
elif(interaction.custom_id=="exit"):
for row in components:
row.disable_components()
message=await ctx.fetch_message(id)
return await interaction.edit_origin(embed=message.embeds[0],view=view)
else:
await interaction.send("Hey! This is not for you!")
U have an extra indent
using pycord right now my command goes through and the button interaction works properly but it says the application did not respond?
await interaction.response.defer()
# bunch of stuff
await interaction.message.edit(content = None, embed=embed , view=None)```
i tried await interaction.followup.send(content = f'{ctx.author.mention}') as well to ping the author and then embed but same thing
hi ,why this return 0
discord.Guild.sticker_limit
U can't edit the interaction message?
U need to do:
await inter.response.send_message(...)
await inter.edit_original_message(...)
i need the defer first but it wont let me do another response
Hm
U did ctx.guild.sticker_limit?
ye ofc
Intents?
already true
!d discord.Intents.emojis_and_stickers or smth
Whether guild emoji and sticker related events are enabled.
New in version 2.0.
This corresponds to the following events:
β’ on_guild_stickers_update()...
okay let me try
Nice
@left idol
await inter.response.defer()
msg = await inter.followup.send(...)
await msg.edit(...)
why send a followup? why not edit the original message?
^^^
sending and editing a followup is an unnecessary request
doesnt work
Disnaek top lib
i can't get rid of the msg the bot says that the application did not respond
and i thought i had to followup
maybe i just followup instead of edit
Yes u do
Well are you sure guild sticker limit is higher than 0
Defer it or respond.
The default limit is 5 even with no boosts
ye
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.image' raised an error: SyntaxError: 'await' outside async function (image.py, line 444)
view = discord.ui.View()
item1 = discord.ui.Button(
label='Next meme',
style=discord.ButtonStyle.blurple,
custom_id='next')
item2 = discord.ui.Button(
label='End interaction',
style=discord.ButtonStyle.red,
custom_id='exit')
view.add_item(item1)
view.add_item(item2)
message = await ctx.send(embed=meme_opt(),view=view)
while True:
try:
interaction = await self.bot.wait_for(
'button_click',
check=lambda inter: inter.message.id == message.id,
timeout=30)
Ok
goes up to 30 if i recall.
This code isn't in an async function as the error states.
print(ctx.guild.sticker_limit,len(ctx.guild.stickers))
intents.emojis_and_stickers = True
Nice
Yeah I said goes up to 30 tough the level 1 already goes up to 10
its not nice ;-;
it is
anyone know how to fix this?
Ask here
ratelimited
By stop using replit
Could you show more? The while True scares me as well.
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.
Or 10, or 60, or a day.
what does this error mean, never have seen it before
finally i found danny's discord profile
improper token
Legends say Ash lives in this channel.
not improper tho
ive even reset it a few times and put it in and made sure
The error under means your event policy is set to linux and the error above means the bot tried to do something it doesn't have access to. The middle is wrong token.
well, seems like it, regenerating it can possibly be a fix
nvm client isnt a thing anymore. gotta change everything to bot
who? me? no
it is still a thing
basically, according to the code, a guild with no boosts has 0 stickers.
which is untrue π
ye
or i just do check boost limit and get limit with that ;-;
You can fix the first by passing a proper token hence fixing error 2 as for error 3 set py if os.name == "nt": asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()) inside an __init__.py file or main file.
improper token passed still
Did you reset the token?
yea
Could you show how you run or start the bot?
I meant the function π
lmao
Seems like a mistake I would make.
Danny can't do anything
It's an API issue prolly. Ask in the API channel
ye still waiting π₯²
await interaction.response.defer()
# bunch of stuff
await interaction.followup.send(content = None, embed=embed , view=None)```
tried this instead but now i get the application did not respond before clicking my button
What's the question in what channel i can ask for you.
2 am π¨
Do u have an error handler?
sticker_limit returns 0 with code
ctx.guild.sticker_limit
Expected : 5
lib : disnake
im not getting any errors
That isn't really a question for discord-api.
uh ok
Or d.py is outdated
Disnake is being used
str.lower()```
Return a copy of the string with all the cased characters [4](https://docs.python.org/3/library/stdtypes.html#id15) converted to lowercase.
The lowercasing algorithm used is described in section 3.13 of the Unicode Standard.
never got this error before after a month of using this bot, fix?
Install ffmpeg
using
Hmm I smell music bot.
a part of the bot yes
Are you hosting the bot locally?
We don't contribute making those here π
await interaction.response.defer(invisible=True)
InteractionResponse.defer() got an unexpected keyword argument 'invisible'
is this not usable?
yes off vsc
its most probably the code from EvieePy's music cog gist
Usable? Yes.. it just doesn't take that kwarg
That's the most popular
ive never installed it, which one
everytime i see a voice related error being sent on discord. it reminds me of same
First link, probably
@boreal ravine You can stop knowingly contribute to a music bot.
then what do your recommend?
Getting a VPS
ffmgpeg is in the folder as im hosting the bot in but isnt working still
heroku?
await client.load_extension
why does my bot still say this after the command is over?
discord glitch
something with ctx.defer()?
py-cord?
ye
not working
If should
defer is for awaiting a slash response, that specific feature is typing
but it isn't stopping even after all the stuff in the command is done?
discord glitch. try adding a return at the end of your command instead (though it most probs won't do anything)
maybe i can followup too instead of send?
wait what, is it a slash command or a prefix?
slash command
then how is the bot typing...
idk
nice
No that's defer
what?
its still doing it so i'll try doing return
It's "thinking"
im blind
it uh wont change anything, just edit the original message or delete it
@left idol u need to send a followup to stop the bot from thinking
Hunter is such a helpful person
ye i was gonna try followup
doesn't a followup send a separate response?
No
nvm tent
inter.channel.send sends a separate response that isn't connected to the slash command in any way
tjen
I'll go back to sleep instead
Nice
why this error ?
SyntaxError: positional argument follows keyword argument this the error
i get this error when
async def rps(ctx, member: discord.Member):
embed = discord.Embed(title="",description ="",colour=discord.Colour.random())
buttons = [f":rock:,:scroll:,:scissors:"]
current = 0
msg = await ctx.send(embed=embed[current])
for button in buttons:
await msg.add_reaction(button)
try:
reaction, user = await client.wait_for("reaction_add", check=lambda reaction, user: user == ctx.author)
except asyncio.TimeoutError:
embed=embed[current]
member.send("Play")
await msg.clear_reactions()```
!e
code
!eval <code>
Can also use: e
*Run Python code and get the results.
This command supports multiple lines of code, including code wrapped inside a formatted code block. Code can be re-evaluated by editing the original message within 10 seconds and clicking the reaction that subsequently appears.
We've done our best to make this sandboxed, but do let us know if you manage to find an issue with it!*
user: user == ctx.author wtf
Oh wait that's a part of lambda
@vale wingwhy is that expression wrong
What line exactly does it point to
don't know
Show the full traceback please
Magic
hi I have been getting this error a lot lately
someone help me with this?
File "/workspaces/-------/project/project.py", line 1, in <module>
import discord
File "/home/ubuntu/.local/lib/python3.10/site-packages/discord/__init__.py", line 25, in <module>
from .client import Client
File "/home/ubuntu/.local/lib/python3.10/site-packages/discord/client.py", line 53, in <module>
from .webhook import Webhook
File "/home/ubuntu/.local/lib/python3.10/site-packages/discord/webhook/__init__.py", line 12, in <module>
from .async_ import *
File "/home/ubuntu/.local/lib/python3.10/site-packages/discord/webhook/async_.py", line 46, in <module>
from ..http import Route, handle_message_parameters, MultipartParameters, HTTPClient, json_or_text
ImportError: cannot import name 'handle_message_parameters' from 'discord.http' (/home/ubuntu/.local/lib/python3.10/site-packages/discord/http.py)```
Can you like ```py plz
it worked perfectly
I didn't get you
!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.
Anyway what version of lib did you install and how did you install it
Traceback (most recent call last):
File "/workspaces/69848642/project/project.py", line 1, in <module>
import discord
File "/home/ubuntu/.local/lib/python3.10/site-packages/discord/__init__.py", line 25, in <module>
from .client import Client
File "/home/ubuntu/.local/lib/python3.10/site-packages/discord/client.py", line 53, in <module>
from .webhook import Webhook
File "/home/ubuntu/.local/lib/python3.10/site-packages/discord/webhook/__init__.py", line 12, in <module>
from .async_ import *
File "/home/ubuntu/.local/lib/python3.10/site-packages/discord/webhook/async_.py", line 46, in <module>
from ..http import Route, handle_message_parameters, MultipartParameters, HTTPClient, json_or_text
ImportError: cannot import name 'handle_message_parameters' from 'discord.http' (/home/ubuntu/.local/lib/python3.10/site-packages/discord/http.py)
@slate swan ^
I installed the discord.py 2.0
And what did you use to install it
wait a minute
pip install -U git+https://github.com/Rapptz/discord.py
nope
thing is I'm making this for my project
so I am not really sure about anything atm
Ok then do these
$ python3 -m venv venv
$ . venv/bin/activate```
Then install the required modules after there's (venv) in front of your command line
Probably was an issue with the library itself
yeah I'm on 1.7.3 rn
And uh do you need 2.0
ss
actually I was on stackoverflow and someone suggested to use 2.0 to use interactive buttons
I don't remember if you can use buttons in 1.7
oh okay
!d discord.ui.View
class discord.ui.View(*, timeout=180.0)```
Represents a UI view.
This object must be inherited to create a UI within Discord.
New in version 2.0.
@slate swan yeah it is 2.0+
oh thanks
Anyway consider looking into virtual environments (venv), using them is a good practice and helps with packages management
@bot.command() async def raffle(ctx, num: int): num = random.randint(1, 1000) await ctx.reply("You get" + (num))
hello i'm new to python and i am trying to code this bot one of it's features is a raffle
so i basically want it to go like this when i do p!raffle roll it picks a number between 1 and 1000
how do i fix it in here
Dont pass num:int coz you want to find random so no need to pass that as your need
!eval py import random num = random.randint(1,1000) print(num)
@lyric apex :white_check_mark: Your eval job has completed with return code 0.
342
Although That works fine nothing to fix there
code
anyone know why my nsfw cmds arent working, i can send the code if u want. i dont get a error at all when using it too
how do variables work within cog files with discord.py? am I able to use variables in my main file that loads the cogs or do the each individually have to be defined in each cog
go ahead
code
!botvar
Python allows you to set custom attributes to most objects, like your bot! By storing things as attributes of the bot object, you can access them anywhere you access your bot. In the discord.py library, these custom attributes are commonly known as "bot variables" and can be a lifesaver if your bot is divided into many different files. An example on how to use custom attributes on your bot is shown below:
bot = commands.Bot(command_prefix="!")
# Set an attribute on our bot
bot.test = "I am accessible everywhere!"
@bot.command()
async def get(ctx: commands.Context):
"""A command to get the current value of `test`."""
# Send what the test attribute is currently set to
await ctx.send(ctx.bot.test)
@bot.command()
async def setval(ctx: commands.Context, *, new_text: str):
"""A command to set a new value of `test`."""
# Here we change the attribute to what was specified in new_text
bot.test = new_text
This all applies to cogs as well! You can set attributes to self as you wish.
Be sure not to overwrite attributes discord.py uses, like cogs or users. Name your attributes carefully!
Can you suggest? How to make the bot write "Select a channel" when entering cmd, after the person specified the channel, the bot creates a webhook and now logs will be sent to that channel.
!d discord.Client.wait_for
wait_for(event, /, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.10)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.10)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.10)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/latest/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
is multithreading possible in bot commands?
like making multiple api reqs at a time... using threads and getting back desired output
u mean use asyncio.gather and then run in a an event loop?
Sure
either make a class and have all the db functions as methods of the class so you can do self.bot = bot (in the __init__ method) and when you instantiate the class, you can pass in your main Bot to that, or pass a channel object/id when you call the function
i dont get it rly
usually you can press a button multiple times but I can't. Everytime there is an interaction error (using pycord, already tried with discord_components and there was the same problem)
how does your db.py currently look?
how do I set intents to true in a class Bot(discord.Client): ?
hmm
#db.py
def func1():
store()...
def func2():
read()...
like this?
class RedditAutomation():
def __init__(self):
self.RedditAutomationDB = BlueskiesDB["RedditAutomation"]
self.bot = bot```
no i classed tho
just pass bot to the def __init__(self, bot) and when you call the class as reddit_auto = RedditAutomation(main_bot_instance_in_your_mainpy_file) pass in the main bot instance
uh that will be aufull
it won't be
guys can you help me
ye lol ik"
why are you naming your class Bot when you are subclassing Client lol
anyways
class Client(discord.Client):
def __init__(self):
super().__init__(intents=discord.Intents.default()... or whatever intents)
hmm it's just an example
btw can that bot become like not 100% need to be used?
ofc
could you elaborate a bit?
hmm like can i use *bot?
noooo
i mean not all func there need bot
oh it can then, okie
then accept the bot argument in the functions themselves
ye so making *bot can fixit
then just like add if bot : self.bot = bot
no..
so?..
cant?
i mean i will give RedditAutomation(bot).func() if the func need bot, and if not i just put RedditAutomation().funcs()
What u tryna do
@brave flint
And why tf are u consuming all the args in the bot var?
What is better sublassing view or select
Depends on ur use case but View in most cases
alr ty
wdym.... (nvm)
how would i check if the Channel id provided as an input is accessible by the bot and is a text channel ?
just get/fetch the channel and check if it is None or not, and use isinstance function to check if it is a text channel
Also, if i get a channel as input.
<#xxxxxxxxxxx>
is what i get.
So, i have to get the integer only to use isinstance right ?
huh? you have to check the channel first
channel = get_channel(id) or await fetch_channel(id)
if not channel:
return send("I don't have permission to view that channel or improper channel ID was passed")
if isinstance(channel, discord.TextChannel):
...
you can just if channel.type == 0 to see if its a textchannel
uhh same thing, don't think either of them will have much impact on the time
btw, the if not channel check is useless here
!d discord.Client.fetch_channel cause an error is already raised if the channel does not exist
await fetch_channel(channel_id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a [`abc.GuildChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.GuildChannel "discord.abc.GuildChannel"), [`abc.PrivateChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.PrivateChannel "discord.abc.PrivateChannel"), or [`Thread`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Thread "discord.Thread") with the specified ID.
Note
This method is an API call. For general usage, consider [`get_channel()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.get_channel "discord.Client.get_channel") instead.
New in version 1.2.
Changed in version 2.0: `channel_id` parameter is now positional-only.
eh, weird
imagine handling that instead
thats a web request and you get a 404 response so raising an error is something you should actually do
while the dpy server π
π
Imagine
Waiting for a Helper's reaction in the server
Idts anyone will say anything
Tbh, I wish the or operator worked for errors too. So smth like file = cond-1 or cond-2 (provided, cond-1 raises an error if the file isn't there, but sadly that's not the case)
wouldn't really be consistent.....what's the point of raising errors if you're just gonna bypass them using or
Right now I have to do smth like:
try:
file = cond-1
except:
file = cond-2
bare exception
Not raising errors myself
But like fetch_user raises one
Ain't talking about dpy only
well
from contextlib import suppress
with suppress(ErrorToHandle):
...
iirc contextlib is what is used
Might as well use try except instead
How to fetch vc ?
!d discord.Guild.get_channel
get_channel(channel_id, /)```
Returns a channel with the given ID.
Note
This does *not* search for threads.
Changed in version 2.0: `channel_id` parameter is now positional-only.
!d discord.Guild.fetch_channel
await fetch_channel(channel_id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a [`abc.GuildChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.GuildChannel "discord.abc.GuildChannel") or [`Thread`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Thread "discord.Thread") with the specified ID.
Note
This method is an API call. For general usage, consider [`get_channel_or_thread()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.get_channel_or_thread "discord.Guild.get_channel_or_thread") instead.
New in version 2.0.
!e
from contextlib import suppress
uwu = [1, 2, 3]
with suppress(IndexError):
print(uwu[6])
print("uwu")
this looks uwuer
@slate swan :warning: Your eval job has completed with return code 0.
[No output]
but it'll run till the error isnt raised
Ig
that's the only catch

What is this
just an alternative to try except handling
Owo
Well I'm thinking of a scenario where u r using a lib method which raises an exception instead of returning None, so there u = some_lib.method() or 1 looks better rather than
try:
w = some_lib.method()
except Exception as e:
w = 1
Hunter writing essays

I'm on mobile, I hate the keyboard
that's not how python works....
401 bad request?
isnt it unauthorized
I'm totally not using 200 for Internal Server Error
yeah unauthorized
Hunter you are too smart to be understood by us
and uh refer to the official documentation -https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#client_error_responses
Nah lol I was jk. I'm using 200 for successful, 500 for internal and so on. I mean, I know I'm insane but not this much...
and it all slims down to a maybe
How can I do buttons instead of Reaction?
Not a maybe lol
How do u "do" buttons?
Do u mean how to use buttons instead of reactions?
Vocabulary
yeah
!d discord.ui.View
class discord.ui.View(*, timeout=180.0)```
Represents a UI view.
This object must be inherited to create a UI within Discord.
New in version 2.0.
And u need 2.0 dpy
Considering you are using discord.py version 2.0 or above
examples - https://github.com/Rapptz/discord.py/tree/master/examples/views
documentation - https://discordpy.readthedocs.io/en/latest/interactions/api.html?highlight=discord ui button#discord.ui.button
and
How do i trigger this event only when the content contains bot's command?
Using if?
Like?
if message.content.lower().startswith("uwu"):
...
):
kanal = [id1, id2]
If message.channel.id in kanal
kanal = (channel_id1, channel_id2)
if message.channel.id in kanal
thanks
using a tuple is faster
@slate swan :white_check_mark: Your eval job has completed with return code 0.
yes
still works
6.11. Boolean operations
or_test ::= and_test | or_test "or" and_test
and_test ::= not_test | and_test "and" not_test
not_test ::= comparison | "not" not_test
``` In the context of Boolean operations, and also when expressions are used by control flow statements, the following values are interpreted as false: `False`, `None`, numeric zero of all types, and empty strings and containers (including strings, tuples, lists, dictionaries, sets and frozensets). All other values are interpreted as true. User-defined objects can customize their truth value by providing a `__bool__()` method.
The operator [`not`](https://docs.python.org/3/reference/expressions.html#not) yields `True` if its argument is false, `False` otherwise.
When will this work lol
||this could be Another Method I Think||
hm? yes, it's applicable as well, but why clutter?
||much more code, whoever likes it? ||
||Shorten Life Now Needs Simple thing ik||
!e
my_uwu_channel_id_stored_in_a_really_really_long_variable_nobody_can_ever_think_of = (1,)
my_uwu_channel_id_two_stored_in_a_really_really_long_variable_nobody_can_ever_think_of = (2,)
if 1 in my_uwu_channel_id_stored_in_a_really_really_long_variable_nobody_can_ever_think_of and my_uwu_channel_id_stored_in_a_really_really_long_variable_nobody_can_ever_think_of in (1,) or 2 in my_uwu_channel_id_two_stored_in_a_really_really_long_variable_nobody_can_ever_think_of and my_uwu_channel_id_two_stored_in_a_really_really_long_variable_nobody_can_ever_think_of in (2,):
print("uwu")
@slate swan :warning: Your eval job has completed with return code 0.
[No output]
sigh
Lohl
||Looks like leaving discord is only a way now||
Jwek
me and my uwu variables, I love 'em all, equally
uwu
Ashley Has No Partiality ||Between|| Variables And Users
Sorry for my poor English
I had a stroke trying to understand
How would i check if a user exists ?
!d discord.Client.fetch_user wont raise an error if it exists
await fetch_user(user_id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User") based on their ID. You do not have to share any guilds with the user to get this information, however many operations do require that you do.
Note
This method is an API call. If you have [`discord.Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members "discord.Intents.members") and member cache enabled, consider [`get_user()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.get_user "discord.Client.get_user") instead.
Changed in version 2.0: `user_id` parameter is now positional-only.
alr, thanks
Actually, i am getting this,
In user_id: Value "<built-in function id>" is not snowflake.
even for an existing User ID
stop using id keyword as a variable
how to delete my bot's reply when context usage is deleted
from discord.ext import commands
import discord
class Test(commands.Cog):
def __init__(self, bot, channel):
self.bot = bot
self.channel = channel
@commands.command(name = "definir")
async def teste(self, ctx, canal : discord.TextChannel):
self.channel = str(canal.id)
await ctx.send("Pronto!\nNome do canal: " + str(canal) + "\nID do Canal: " + self.channel)
@commands.command(name = "enviar")
async def sugestao(self, ctx, * , sugestao = " "):
await ctx.send(channelID)
def setup(bot):
bot.add_cog(Test(bot))```
discord.ext.commands.errors.ExtensionFailed: Extension 'commands.test' raised an error: TypeError: Test.__init__() missing 1 required positional argument: 'channel'
...? you'll have to have a nice amount of trackers for that, and the api calls would be too many
Remove the self.channel and channel arg

tho it's doable as long as the bots in a small server @granite parcel
Hunter is so smart
delete
no
Adding reactions is more API calls than deleting command message on context since there's a possibility not always the msg is gonna get deleted but u gotta add a reaction on every msg and then delete the msg

but.....you'll have to fetch the context message again and again?
idk, I'm out, Hunter will help, he's the smartest
but I wanted to make a command that allowed me to set the channel where the bot would send messages. For example: .defineSuggestions #channel (it would define a specific channel for the suggestions) and then .sendSuggest (sugestao) and it would send the suggestion in that channel

U can use wait_for and set the timeout to None
and of course only for the channels on that server that the command is being used.
Supply a discord.TextChannel object when u r making an instance of the class
wait for?
!d discord.Client.wait_for
wait_for(event, /, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.10)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.10)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.10)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/latest/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
event?
message_delete
on?
using the on_message_delete is better in that case tbh
with a list of message IDs
await bot.wait_for("raw_message_delete", check=lambda payload: payload.message_id == ctx.message.id, timeout = None)
ew

Isn't triggered every time due to caching issues
I first had the thought of using that but there's a possibility that isn't gonna work
This is yr best bet tbh
raw_message_delete then
That's why I used that lol
use a global event...
if it has to be done in every command that is
Using a botvar and making a dict?
yeah, {message_id: channel_id} format
you want it for every cmd right?
yeah
consider making a bot variable (run !botvar for more info) that holds a dictionary of the format {message_id: channel_id}, and use the on_raw_message_delete event (run !d discord.on_raw_message_delete for more info) event to check when a message was deleted, and if the deleted message's id was found to be in the (bot) variable that holds the dictionary, get/fetch that message and delete it
lemmie see
get/fetch that message and delete it
πΆββοΈbot.http.delete_message(channel_id, message_id)saves an extra api call
un-danny moment
http.py over everything
imagine using dpy
in 2.0 we have to use await for loading extension?
yes?
nthg
await client.load_extension(extension)
^
SyntaxError: 'await' outside function```
if __name__ == "__main__":
for extension in extensions:
try:
await client.load_extension(extension)
except Exception as e:
print(f'Error Loading {extension}', file=sys.stderr)
traceback.print_exc()```
how to fix it
@slate swan.
the error says it all, I don't think I have anything to add
use an async function to start your bot or setup hook
import asyncio
async def main():
async with client:
for extension in extensions:
await client.load_extension(extension)
await bot.start("TOKEN")
asyncio.run(main())
or setup_hook
ImportError: cannot import name 'InvalidArgument' from 'discord' (/home/container/.local/lib/python3.8/site-packages/discord/init.py)
using replit i got setup tools deprecated error any idea why?
Too much work for him tbh
hunter uk?^
when i tried to run it just gave use standard tool pip to build....
async def join(ctx):
channel=ctx.message.author.voice.voice_channel
await bot.join_voive_channel(channel)
```The bot doesn't join to the channel
where is the mistake?
Show
voice.channel not voice.voice_channel
yeah will do after dinner
!d discord.VoiceState.channel
The voice channel that the user is currently connected to. None if the user is not currently in a voice channel.
Nice. Also please don't use replit
idk why. I actually nothing changed to my bot but now it is only working in direkt messages but on server I don't get a response
Do you have proper intents enabled
And yeah what was the last time you launched your bot and it ran successfully
of course
today
Message content intent enabled?
I only switched to a new library (pycord) but first when I started it with some things from pycord in it, it worked fine
yea
Create on_message listener and try printing out messages data
!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.
its not a project its a little bot i made for a community server its has only two commands so no extensive usage
If u still get a bad server, u r gonna get ratelimited no matter if yr bot' doesn't even send a single msg
hmm i see
U ran this yourself?
no
Poetry stuff
Yea
i just made a requirements.txt and installed it in shell thats it
There is a poetry file, can u share that?
Do u have a cc?
Samovar server
what do u think?
What's that?
Yes
The thing I host my bots on
smh i dont
Lol okay okay
Self hosting
Its a pain tbh
thx lemme see
The only pain is to setup network
Indeed
I don't wanna recommend it, but... Danbot is yr only option
mhm ok
could you explain wym?
Rip
hm
@bot.listen()
async def on_message(message):
print("Received a message")
print(message.content)```
hi
Hi
Hello
should I use listen or is event also working?
already did it
In listen you don't
i know
Nice
Disable pass length limit
How
Google (idk myself)
Okay thanks
soo when I send a message in direkt messages I can see it, but in a server the received message is invisible
intents.members = True```
message_content isn't included into default
You need to explicitly enable it like you did with members
but it worked fine without it a few hours ago and also the last months?
The last months probably
A few hours ago I have no idea
You could've changed a slight thing and didn't even notice it
I started working with buttons and for this I had to add a library
Let me guess - before you used dpy 1.7
no after
You couldn't have been using it after - it doesn't require you to explicitly enable message content intent, that's why it worked :)
How did you enable it
yeah, replit is very very basic
Replit is very very very cringe for hosting bots
429 error code knows its stuff
message_content = True
yeah just make a code to kill containers when 429 shows up
intents.message_content = True?
Won't make the IP unratelimited
well, when u kill container and restart repl, it starts off with a new container and new shared ip
kill any 1-14
i do that for my bot its chill
wtf it's like magic and it's now working. thanks alot
π u didn't mentioned that
anyways, i agree REPL IS SHIT. but its good if you know what to do and dont have money
Ok cool
If u want someone to copy ur code
I should probably insert new CPU inside my server
just name it something weird lmao
Man I legit posted AI antispam bot's source
Rip
@odd mango hold up, what about replit's ephemeral file storage

