#discord-bots
1 messages · Page 304 of 1
but when i fill the info and click send i have an error
the error :
2023-09-17 19:13:37 ERROR discord.ui.modal Ignoring exception in modal <Questionnaire timeout=None children=2>:
Traceback (most recent call last):
File "C:\Users\canai\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ui\modal.py", line 188, in _scheduled_task
await self.on_submit(interaction)
File "c:\Users\canai\Desktop\bots\Partins\main_partins.py", line 282, in on_submit
await interaction.response.send_modal(f'Thanks for your response, {self.name}!')
File "C:\Users\canai\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\interactions.py", line 971, in send_modal
params = interaction_response_params(InteractionResponseType.modal.value, modal.to_dict())
^^^^^^^^^^^^^
AttributeError: 'str' object has no attribute 'to_dict'
fixed
but how do i get the responses from it ? @slate swan
Look at the examples https://github.com/Rapptz/discord.py/tree/master/examples/modals
seen but when people submit their answer i want the bot to send a copy in a channel how do i do that ?
.send_modal takes Modal not text
await interaction.response.send_modal(f'Thanks for your response, {self.name}!') ??
yes but no
2023-09-17 19:24:30 ERROR discord.client Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\canai\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "c:\Users\canai\Desktop\bots\Partins\main_partins.py", line 35, in f4
print(f"{str(message.author)} in {message.guild.name}: {message.content}")
^^^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'name'
Task exception was never retrieved
future: <Task finished name='discord-ui-modal-dispatch-269555a07cf95aa993f7d689c862e3f4' coro=<Modal._scheduled_task() done, defined at C:\Users\canai\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ui\modal.py:179> exception=NameError("name 'traceback' is not defined")>
Traceback (most recent call last):
File "C:\Users\canai\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ui\modal.py", line 188, in _scheduled_task
await self.on_submit(interaction)
File "c:\Users\canai\Desktop\bots\Partins\main_partins.py", line 303, in on_submit
await interaction.response.send_modal(f'Thanks for your demand, {self.name.value}!', ephemeral=True)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: InteractionResponse.send_modal() got an unexpected keyword argument 'ephemeral'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\canai\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ui\modal.py", line 190, in _scheduled_task
return await self.on_error(interaction, e)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "c:\Users\canai\Desktop\bots\Partins\main_partins.py", line 309, in on_error
traceback.print_exception(type(error), error, error.__traceback__)
^^^^^^^^^
NameError: name 'traceback' is not defined
do you read what i say? you literally just added ephemeral=True
Do you know the difference between send_modal and send_message
yes
Doesn't seem like it
send modal sends a modal and send message sends a message
So, why are you trying to make a modal ephemeral or send some message with it
so why you do opposite?
i've took the code from the github you've send
examples/modals/basic.py lines 57 to 58
async def on_submit(self, interaction: discord.Interaction):
await interaction.response.send_message(f'Thanks for your feedback, {self.name.value}!', ephemeral=True)```
There's a difference which apparently you "know"
nah blud be making those mistakes on purpose
#whitelist
class Whitelist(discord.ui.Modal, title='Whitelist'):
# Our modal classes MUST subclass `discord.ui.Modal`,
# but the title can be whatever you want.
# This will be a short input, where the user can enter their name
# It will also have a placeholder, as denoted by the `placeholder` kwarg.
# By default, it is required and is a short-style input which is exactly
# what we want.
name = discord.ui.TextInput(
label='IG Name',
placeholder='Your IG name here...',
)
# This is a longer, paragraph style input, where user can submit feedback
# Unlike the name, it is not required. If filled out, however, it will
# only accept a maximum of 300 characters, as denoted by the
# `max_length=300` kwarg.
feedback = discord.ui.TextInput(
label='Your infos?',
style=discord.TextStyle.long,
placeholder='Give us your hours on Astroneer , platforms and why you want to join the server',
required=False,
max_length=300,
)
async def on_submit(self, interaction: discord.Interaction):
await interaction.response.send_message(f'Thanks for your demand, {self.name.value}!', ephemeral=True)
async def on_error(self, interaction: discord.Interaction, error: Exception) -> None:
await interaction.response.send_message('Oops! Something went wrong.', ephemeral=True)
traceback.print_exception(type(error), error, error.__traceback__)
Thinking the same quite often
So is it possible or not ?
It's literally the example, so I think it's possible yes
You copy pasted and edited it
now i have this error :
Traceback (most recent call last):
File "c:\Users\canai\Desktop\bots\Partins\main_partins.py", line 353, in <module>
client.run(TOKEN)
File "C:\Users\canai\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 860, in run
asyncio.run(runner())
File "C:\Users\canai\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 190, in run
return runner.run(main)
^^^^^^^^^^^^^^^^
File "C:\Users\canai\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 118, in run
return self._loop.run_until_complete(task)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\canai\AppData\Local\Programs\Python\Python311\Lib\asyncio\base_events.py", line 653, in run_until_complete
return future.result()
^^^^^^^^^^^^^^^
File "C:\Users\canai\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 849, in runner
await self.start(token, reconnect=reconnect)
File "C:\Users\canai\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 777, in start
await self.login(token)
File "C:\Users\canai\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 621, in login
await self.setup_hook()
File "c:\Users\canai\Desktop\bots\Partins\main_partins.py", line 303, in setup_hook
await self.tree.sync(guild=TEST_GUILD)
File "C:\Users\canai\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\tree.py", line 1069, in sync
data = await self._http.bulk_upsert_guild_commands(self.client.application_id, guild.id, payload=payload)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\canai\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\http.py", line 739, in request
raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access
it says missing acces but my bot is an admin on my server and has the admin rights
Admins can't create app commans 🤷
You need to enable the app commands scope when inviting the bot
i enabled all but still the same error
you enabled all what
All scopes?
all scopes?
That doesn't sound like a good idea
yeah but not at the good place
Do you even know what a scope is
yes
So, why do you say you've enabled all scopes and "not at the good place"
it should look like this ?
enabled it all at bot permissions
Right so you haven't enabled all scopes
yes, now reinvite the bot
done still the same issue
So you didn't know what scopes are, at least before
Is the bot in the guild
Meaning, is the guild ID correct
in the code ?
Where else
i need to replace the 0 ?
readed them but its the only place where i can see guild can be placed
What's your thing now
my "thing" ?
About what you've edited duh 
TEST_GUILD = discord.Object(MY_GUILD_ID)
and what MY_GUILD_ID is?
the bot guild id
Which is
1140326509920395374
PS C:\Users\canai\Desktop\bots\Partins> & C:/Users/canai/AppData/Local/Programs/Python/Python311/python.exe c:/Users/canai/Desktop/bots/Partins/main_partins.py
2023-09-17 19:47:18 INFO discord.client logging in using static token
Traceback (most recent call last):
File "c:\Users\canai\Desktop\bots\Partins\main_partins.py", line 353, in <module>
client.run(TOKEN)
File "C:\Users\canai\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 860, in run
asyncio.run(runner())
File "C:\Users\canai\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 190, in run
return runner.run(main)
^^^^^^^^^^^^^^^^
File "C:\Users\canai\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 118, in run
return self._loop.run_until_complete(task)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\canai\AppData\Local\Programs\Python\Python311\Lib\asyncio\base_events.py", line 653, in run_until_complete
return future.result()
^^^^^^^^^^^^^^^
File "C:\Users\canai\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 849, in runner
await self.start(token, reconnect=reconnect)
File "C:\Users\canai\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 777, in start
await self.login(token)
File "C:\Users\canai\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 621, in login
await self.setup_hook()
File "c:\Users\canai\Desktop\bots\Partins\main_partins.py", line 303, in setup_hook
await self.tree.sync(guild=TEST_GUILD)
File "C:\Users\canai\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\tree.py", line 1069, in sync
data = await self._http.bulk_upsert_guild_commands(self.client.application_id, guild.id, payload=payload)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\canai\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\http.py", line 739, in request
raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access

Not code either but yeah whatever
Is the bot actually in that guild
We talked about the testing guild ID for the past minutes, think a bit..
okay
so i've out the bot guild into the code
and it is not working
and you want to see my code
Again, is the bot actually in that guild and how did you get the guild ID
how can you get the guild id on dev portal
Dev portal has no guild ID
hold on
Guild == Server
....
Right click on the guild in the Discord client and copy the ID from there, that's the actual guild ID
its supposed to be like that
normally its says logged in as ... and synced x commands
Then you eventually got rate limited from syncing commands 
Me when my bot doesn't immediately exit when it's connected to Discord 
already have that :
@client.event
async def on_ready():
# this runs when the account is logged into
print("We have logged in as {0.user}".format(client))
try:
synced = await client.tree.sync()
print(f"Synced {len(synced)} commands(s)")
except Exception as e:
print(e)
Yeah then wait 24 hours and see after 24 hours
wat
It's called a rate limit on syncing commands
no
And that rate limit gets reset after some hours or a day depends, so try later
Most useful try-except ever
GPT wouldn't put this nonsense comment
i do 🤓
It's not because you don't that people don't. I do comment on lots of things....
okay lets put that away
now that the command is working
when i enter the infos i dont have a copy of the responses
Which is unrelated to bot dev, thanks
What responses
There's a rule called staying on the channel topic which I'd like to follow ^-^
like if you enter Name : aaaa , Feedback : aaa . I want a copy of that
So, what's the issue
i dont have a copy of that
relax bro
no need to insult eachother
i'm upset that they're making fun of me but i dont say it
Send the actual code and the results you see
The whole or just the modal part ?
how is that code 😭
so when people fill this
i want a copy of the responses
Just get the code from that image, what's the problem 
If you want the aaa of the "What do you think...." then just add it to the message you send

#whitelist
# The guild in which this slash command will be registered.
# It is recommended to have a test guild to separate from your "production" bot
TEST_GUILD = discord.Object(1152621828641140796)
class MyClient(discord.Client):
def __init__(self) -> None:
# Just default intents and a `discord.Client` instance
# We don't need a `commands.Bot` instance because we are not
# creating text-based commands.
intents = discord.Intents.default()
super().__init__(intents=intents)
# We need an `discord.app_commands.CommandTree` instance
# to register application commands (slash commands in this case)
self.tree = app_commands.CommandTree(self)
async def setup_hook(self) -> None:
# Sync the application command with Discord.
await self.tree.sync(guild=TEST_GUILD)
class Feedback(discord.ui.Modal, title='Feedback'):
# Our modal classes MUST subclass `discord.ui.Modal`,
# but the title can be whatever you want.
# This will be a short input, where the user can enter their name
# It will also have a placeholder, as denoted by the `placeholder` kwarg.
# By default, it is required and is a short-style input which is exactly
# what we want.
name = discord.ui.TextInput(
label='Name',
placeholder='Your name here...',
)
# This is a longer, paragraph style input, where user can submit feedback
# Unlike the name, it is not required. If filled out, however, it will
# only accept a maximum of 300 characters, as denoted by the
# `max_length=300` kwarg.
feedback = discord.ui.TextInput(
label='What do you think of this new feature?',
style=discord.TextStyle.long,
placeholder='Type your feedback here...',
required=False,
max_length=300,
)
async def on_submit(self, interaction: discord.Interaction):
await interaction.response.send_message(f'Thanks for your feedback, {self.name.value}!', ephemeral=True)
async def on_error(self, interaction: discord.Interaction, error: Exception) -> None:
await interaction.response.send_message('Oops! Something went wrong.', ephemeral=True)
# Make sure we know what the error actually is
traceback.print_exception(type(error), error, error.__traceback__)
client = MyClient()
@client.tree.command(guild=TEST_GUILD, description="Submit feedback")
async def feedback(interaction: discord.Interaction):
# Send the modal with an instance of our `Feedback` class
# Since modals require an interaction, they cannot be done as a response to a text command.
# They can only be done as a response to either an application command or a button press.
await interaction.response.send_modal(Feedback())
no like
Nice code, what's the point to send it
thats literally example from discord.py repo
@slate swan wanted me to send it
xdd
so
Add the same for feeback 
the command is for an game server to whitelist people
so i want them to wrote their IG name and some infos
then i want the bot to send all the info from the command that the guy used into a channel
so i can take the IG name and whitelist it
hold on gonna make an exemple
My guy, there's no need... You already send the name. Now send the feedback as well
Then rename the TextInput data with whatever you want
If you want a username then set the label to something like "What's your in-game username?" instead
All right, so you can't replace a string by another one?
Have you taken into consideration learning Python before making a bot? At least the most basics, and the advanced topics it requires to know, e.g. async and OOP
yes but i've didnt done things like that be4
but i figured out how to have the feedback
So you haven't learned the advanced topics that discord.py requires you to have, which includes OOP
now the thing i want to know is how do i can make the bot send all the modal infos into a specific channel
get_channel(id, /)```
Returns a channel or thread with the given ID.
Changed in version 2.0: `id` parameter is now positional-only.
!d discord.TextChannel.send
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File) object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list) of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File) objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed) object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list) of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed) objects. **Specifying both parameters will lead to an exception**.
Done this
async def on_submit(self, interaction: discord.Interaction):
await client.get_channel(1152966656314855484)
await channel.send({self.name.value} , {self.feedback.value} )
await interaction.response.send_message(f'Thanks for your feedback', ephemeral=True)
but it's not working
yea it's not working but why
look at the return type of get_channel
lmao
need to replace await with return ?
probably also enable pyright bc if you have static type hinting enabled, vsc would already have detected the issue
did you read the docs
channel = client.get_channel(1152966656314855484) or await client.fetch_channel(1152966656314855484)
get_channel get the channel for bot cache
if it dosent exist it returns None in which case you can make a request to discord api to fetch it
seen that on the doc
then how do you handle it ?
i dont have any errors
then do you know how to handle errors in modals?
giving me an error only into the modal
what does that supposed to mean?
async def on_submit(self, interaction: discord.Interaction):
channel = client.get_channel(1152966656314855484) or await client.fetch_channel(1152966656314855484)
await channel.send({self.name.value} , {self.feedback.value} )
await interaction.response.send_message(f'Thanks for your feedback', ephemeral=True)
idk
but thats weird i dont have any errors in vscode
do u know how to handle or get errors in views ?
No i guess ?
view errors are under an on_error callback which u need to override
also use a fstring in channel.send
!d discord.TextChannel.send
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File) object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list) of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File) objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed) object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list) of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed) objects. **Specifying both parameters will lead to an exception**.
The modal says 'An error has occured'
but dont have any in vscode
and changed this also
``` await channel.send(f'{self.name.value} , {self.feedback.value}' )````
its hard to debug if u dont send a traceback
.
SKILL ISSUE
PS C:\Users\canai\Desktop\bots\Partins> & C:/Users/canai/AppData/Local/Programs/Python/Python311/python.exe c:/Users/canai/Desktop/bots/Partins/main_partins.py
2023-09-17 20:39:20 INFO discord.client logging in using static token
2023-09-17 20:39:21 INFO discord.gateway Shard ID None has connected to Gateway (Session ID: 6279143f8c844b87948f46755a064db9).
read what i sent
......
and how do i override it ?
async def on_error(self, interaction: discord.Interaction, error: Exception) -> None:
await interaction.response.send_message('Oops! Something went wrong.', ephemeral=True)
# Make sure we know what the error actually is
traceback.print_exception(type(error), error, error.__traceback__)
can you still make discord bots? I thought bots like groovy were banned?
You can still make bots yes, why would it not be allowed
What you can't do are bots breaching terms of services, which groovy and other music bots were doing
And that's been the case since forever
hi
i get an 'interaction failed' error everytime i run my code. without any error in console ofc
here is my code;
@client.event
async def on_select(ctx, interaction):
try:
custom_id = interaction.custom_id
selected_value = interaction.values[0]
if custom_id == "crypto_select":
if selected_value == "USDT":
embed = discord.Embed(
title="USDT Information",
color=0x00ff00
)
embed.add_field(name="Symbol", value="USDT", inline=True)
embed.add_field(name="Description", value="Tether (USDT) is a stablecoin.", inline=True)
embed.set_thumbnail(url="URL_TO_USDT_ICON_IMAGE")
elif selected_value == "LTC":
embed = discord.Embed(
title="LTC Information",
color=0x0000ff
)
embed.add_field(name="Symbol", value="LTC", inline=True)
embed.add_field(name="Description", value="Litecoin (LTC) is a peer-to-peer cryptocurrency.", inline=True)
embed.set_thumbnail(url="URL_TO_LTC_ICON_IMAGE")
elif selected_value == "ETH":
embed = discord.Embed(
title="ETH Information",
color=0xff0000
)
embed.add_field(name="Symbol", value="ETH", inline=True)
embed.add_field(name="Description", value="Ethereum (ETH) is a blockchain platform.", inline=True)
embed.set_thumbnail(url="URL_TO_ETH_ICON_IMAGE")
await ctx.send(embed=embed)
except Exception as e:
print(f"An error occurred: {e}")```
You still can. The story with the music bots is that Discord prohibits bots from using streaming services such as YT, Spotify and SoundCloud. Using those to stream music for your bot is considered a breach of TOS, and Discord has been enforcing and ramping up efforts to crack down on this. Thus, that's why the bots are slowly dying and being picked off one by one
to be also clear, streaming music illegally from YT, Spotify and SoundCloud also is illegal and results in copyright violations and a whole legal battle so...
@quick brook can u help
figure it out yourself
dont think if i'm replying to someone else's question that i will automatically help you. no it doesn't work that way. I pick and choose
there question had nothing to do with python
im making a help channel bruh so useless
go ahead
also insulting me like that proves to me that you are weak than anything else
you're not responding using the Interaction object, also why you're accepting ctx and Interaction?
I am trying to make my bot say the weather, but for some reason the code doesn't work. (I got the code from github)
ah yes the average copy pasta 🍝 
assuming that was an insult is genuinely applaudable. If you think that was an insult, you would explode in the real world .
im confuseled, i always use ctx for everything but wdym not responding using the object
what library are you using?
rapptz'
there isn't? i thought i saw some docs that said there was, what event do i use instead
!d discord.on_interaction
discord.on_interaction(interaction)```
Called when an interaction happened.
This currently happens due to slash command invocations or components being used.
Warning
This is a low level function that is not generally meant to be used. If you are working with components, consider using the callbacks associated with the [`View`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View) instead as it provides a nicer user experience.
New in version 2.0.
do i replace this w/ on_select
This is a low level function that is not generally meant to be used.
just read the examples here
hello, I have a question about aiohttp
nope,
consider using the callbacks associated with the View instead as it provides a nicer user experience.
cool 👍
the thing is that when i call a request that returns ~7k lines of json its goes very quickly, but when i try to call .json() or .text() on it it processed for a couple seconds (~30/45), can i somehow speed it up?
thats most likely not related to discord bots so head over to #1035199133436354600
i thought i clicked on #async-and-concurrency lol, sorry
im using view
on_interaction is the only event for interactions in dpy. for all types of them
there are no on_select, on_button_click or anything like that
okay how do i change it to use on_select
It made sense to recommend it in his case
generally doesn't mean that should'nt ever be used
what other lib can i use to use onselect
Do your research 
You don't need to bring in a whole another library just to see what options a user selected
okay ill use on interaction
You shouldn't use on interaction either
See the examples linked above for listening to select menus
zlhawg ok
How do I load the JSON one?
Cna you elaborate?
I want to load the JSON file only once, not open it every time someone types a message
# JSON
channel_rules = {
1067851901355430040: {
'flex': 1067851927381090365,
'duo': 1067851927381090365,
'duoq': 1067851927381090365,
'aram': 1067851927381090365,
}
}
# Code
# Load channel_rules from JSON file
with open('channel_rules.json', 'r') as file:
channel_rules = json.load(file)
@client.listen()
async def on_message(message):
content = message.content.lower()
for channel_id, keyword_mapping in channel_rules.items():
for keyword, to_channel_id in keyword_mapping.items():
if keyword in content:
await message.channel.send(
f"Please use <#{to_channel_id}> for {keyword} related LFGs in order to keep this channel more clean.")```
How can you tell it's opening the file every time?
Because I'm using
with open('channel_rules.json', 'r') as file: channel_rules = json.load(file) right?
Yeah, that just opens the file, reads the contents into channel_rules, and closes it
So isn't it better to load it on startup and save it in the memory?
That's what you're doing
So I can't change the json file on the fly to update the list without restarting the bot?
Correct
Alright
If you wanted to do that, you would probably bind channel_rules to your bot instance, and you'd have a command to re-load the file and update the state
Can I get help with making shift logger system
There's still more you can say...
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: IndexError: list index out of range
what is that means?
@glad cradle :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 2, in <module>
003 | x[2]
004 | ~^^^
005 | IndexError: list index out of range
huh
how to get bot invite link from the token?
hello peeps
You can't.
You don't...
so how someone make this?

Make what
get bot invite link from the token
actually I knew
just get the id
and set it in the link
nvm
Actually, the first bit before the dot can be decoded to base64, that's the string of the users id
It's possible if you know how to decode it
print(f"https://discord.com/api/oauth2/authorize?client_id={str(bot.user.id)}&permissions=8&scope=bot")
so how I did it in one line?
That's not the bot token.
how did I get the bot.user.id ?
from the token, so I didnot need any info execpt the tokens
what
?
you didn't get the invite from the token, you got it from the bots user ID
The first bit of your token is the users ID converted to base64
Decode it, then you'll have your user ID
It's extremely easy as well
Just use base64
Can you edit an embed? Or do you need to make a new one to change anything
I'm decently sure you need to just make a new one
You could just copy the embed though, and edit the fields you want
Yea I'm gonna tinker with that lol
youtube_dl.utils.DownloadError: ERROR: oQAPiSBWvoE: YouTube said: Unable to extract video data - I can't fix this. Can someone explain it deeply
!rule 5
5. Do not provide or request help on projects that may violate terms of service, or that may be deemed inappropriate, malicious, or illegal.
I wonder, if the actual Python discord, codes there own bots in python 
we do
oh noice
I need help, I'm trying to make stuff like, events, but I realise I need a handler, can someone help, I have cogs set up, I need my Event Handler and stuff for my @bot.event
Nevermind, figured it out
Nevermind, it didn't work 💀
can u reframe that? Are you trying to add an event to a cog?
maybe 💀
why, am I not supposed to?
No? What have you tried?
I never said that, I was just asking
import discord
from discord.ext import commands, tasks
import os
import json
TOKEN = ""
class Solaris(commands.Bot):
def __init__(self):
super().__init__(
command_prefix="s!",
intents=discord.Intents.all()
)
async def setup_hook(self):
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
try:
await self.load_extension(f'cogs.{filename[:-3]}')
except Exception as e:
print(f'Failed to load {filename[:-3]} cog. Error: {str(e)}')
Solaris().run(TOKEN)
This is my main bot.py file, where and how can I add a event handler 
just override it within your subclass
subclassed bot
so where do I put it....
bot.py line 387
async def on_guild_join(self, guild: discord.Guild) -> None:```
get some rest
no
I must achieve my goals
of getting my event handler done
even then, I have college in 6 hours, so I can't sleep
still get some sleep. you have classes starting in 6 hours so you might as well get some rest. even 6 hours of sleep is better than none
nahhhhhhhhhhh
Do I place this in the setup_hook?
damn
@quick brook
pretty much the same idea
you dont place it in setup_hook, but place it just like setup_hook
so, if not in the hook, where?
ex:
class MyBot(commands.Bot):
def __init__(self):
super().__init__(
command_prefix="s!",
intents=discord.Intents.all()
)
async def setup_hook(self):
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
try:
await self.load_extension(f'cogs.{filename[:-3]}')
except Exception as e:
print(f'Failed to load {filename[:-3]} cog. Error: {str(e)}')
# Override the event here. Essentially this allows the bot to listen to the event this way
async def on_guild_join(self, guild: discord.Guild):
print(f"Guild {guild.name} just joined!")
yes just llike the example
thanks so much
Np
Hey uh, I wanna make the on_guild_join send an embed to the use who added the bot, how can I, I tried but it didn't send a message to me when I tried
And I accidentally pasted my code and got rid of it
bruh
i'll give you the basic outline on how it should be done: obtain the channel, verify that in fact it is a channel and is a text channel, and then log the info there. Alternatively, the way i would approach it is to send it via webhooks to the desired channel instead
I mean like, in a DM
DM the user who added the bot
dont think u can
Oh
plus, DMing the user is purely annoying. Imagine every single time that you earned a new rank in an leveling system, and that notifcation gets DMed to you. You would quickly get annoyed with this. Your consumer satisfaction would decrease (or in economics, consumer utility), and you would want to get rid of the bot. To drive home the point, any bot that performs any sort of DMs is considered annoying and an invasion of privacy
Yea, that's a good point
Also, may I ask, as I don't know if this is ToS breaching, but is message logging, (like Dynos) ToS breaching and am I allowed to code my own? @quick brook
It shouldn't be against ToS but I don't think it's needed to log every message I'd say only log deleted messages or something similar
deleted messages
Why shouldn't it?
As u can just view every message in discord
That's worse
If a user deleted their message, it means that they don't want anyone to see it
Cuz even if we don't log the messages are visible to us it's just about scrolling
Oh
Meanwhile people using RPC
RPC?
Rich Presence
Where's the c?
idk
Presence
No - Remote Procedural Calls
Right 😼

And all Discord clients have an RPC server running you can interact with

Which is often used by people to log any messages sent/deleted/whatever
As it sends similar events as the gateway
pretty sure python discord logs them 
They do
yeah
Welp sometimes deleted message are needed as proofs
To be fair it's kind of normal to log deleted messages these days
Does Discord even care about them? I wonder
Welp they have no way of detecting even if being logged
its a event they send after all
u have to respond to the event data from the gateway no?
they can atleast be sure whether data is being received wether its stored they will prolly never know
real
Idk what else to do for my bot then
Does anyone know how to use Discords timeout feature for a bot command?
!d discord.Member.timeout
await timeout(until, /, *, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Applies a time out to a member until the specified date time or for the given [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta).
You must have [`moderate_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.moderate_members) to do this.
This raises the same exceptions as [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.edit).
thanks
You only need to keep sending heartbeats, no need to respond to every event you receive
u do send some response right to the event? or is it not required
i see
each heartbeat you send contains the last sequence number received by discord so i believe they can be reasonably sure on how up-to-date your client is on events (although i haven't tested how they handle outdated sequences)
edit: a quick check shows nothing special happens if the sequence is behind, at least by a bit ruby discord_ws.client.client ( DEBUG) => Received hello from gateway discord_ws.client.heartbeat ( DEBUG) => Waiting 42.16s for heartbeat discord_ws.client.client ( DEBUG) => Received READY event discord_ws.client.client ( DEBUG) => Received GUILD_CREATE event root ( WARNING) => Resetting sequence from 2 to 1 discord_ws.client.heartbeat ( DEBUG) => Sending heartbeat, last sequence: 1 discord_ws.client.client ( DEBUG) => Received heartbeat acknowledgement
how to make this bot?
Using python and a discord bot lib along with psutil and datetime module XD
Oh and u will need to use platform module too
can give example?
@turbid condor
Welp i can only tell you how to do that not providing an example
You can get the processor using platform module
As for the uptime u need to create a variable that stores the time when bot goes online and then use the current time (the time at which command is used) after that u can minus the variable u created earlier with current time to get the uptime
And for the disk usage and memory usage u need to use psutil module
!pip psutil
Check the docs on how to get the memory usage and disk usage
fair
They just use it for resuming don't they?
you also need it when sending heartbeat
what would I change?
2023-09-18T15:15:00.641693433Z File "/home/user_535268127639076885/main.py", line 3, in <module>
2023-09-18T15:15:00.641706105Z from discord.ui import Button, ButtonStyle
2023-09-18T15:15:00.641746318Z ImportError: cannot import name 'ButtonStyle' from 'discord.ui' (/usr/local/lib/python3.11/site-packages/discord/ui/init.py)
2023-09-18T15:15:13.038967257Z Traceback (most recent call last):
2023-09-18T15:15:13.039025791Z File "/home/user_535268127639076885/main.py", line 3, in <module>
2023-09-18T15:15:13.039051238Z from discord.ui import Button, ButtonStyle
2023-09-18T15:15:13.039091115Z ImportError: cannot import name 'ButtonStyle' from 'discord.ui' (/usr/local/lib/python3.11/site-packages/discord/ui/init.py)
!d discord.ButtonStyle
class discord.ButtonStyle```
Represents the style of the button component.
New in version 2.0.
its not in ui
okay thank you
Uhm...
Well first of all you leaked your token.
Second, your indenting is wrong. It needs to be outside the command.
how do i remove it from the function
Move it down?
def func():
something()
inside()
def func():
something()
outside()
but i tried it again, but ye thanks
i also need to learn how to use the def
so yall are gonna fuck my token now abi
idk
and check if it is in a huge list
Well I mean those gateway events are very tiny
And that’s also why discord uses a websocket connection so it’s not super expensive compared to like a regular http request
As for how they handle it they most likely cache a config that has the word list
And then just reference that config
yo
It’s fairly inexpensive plus when you get really big you have separate applications aka shards
how do i make a slash commands in python
I mean any of the main python libs support slash commands
They have examples in their documentation
I personally use disnake which is a fork of discord.py lemme see if I can get you the examples for that
ok ty
Yeah just look at their read me
ty
Yep
Well I mean it has instructions in the readme
Like code you can literally copy and paste and it should get you up and running
ah
If you have ever used discord.py it’s the same thing
ye i have
then yeah for your case just treat this like discord.py
alr cool
You might eventually find some differences but that’s once you get farther
ima restart coding then
i personally refuse to support any of the dpy forks. discord.py itself already implements every single feature that the forks have. There is no point of using these forks because you will find less support for them, and oftentimes contain poor code design and failed promises (in the case of pycord).
The only reason why you would want to use them is if you already have an existing codebase written during the hiatus period for dpy
and snipy please dont be a fork shill
stop being a disnake shill please
Compares Discord libraries and their support of new API features
take a look for yourself
this lists only the features officially supported by the discord api
that's the point
dpy supports the features provided by discord. Internal features between the projects are not considered
no perspective api
how can i stop the crashing
its not my api
not entirely true, views aren't provided by discord so why d.py is implementing them? the closest library to the original discord api is hikari
Views are way to contain the features such as buttons. Then again why is disnake implementing them as well
I believe Discord works off of Action Rows, discord.py tries to abstract it further with a single "View" container
.topic
Suggest more topics here!
Interesting
it was already there when the fork was created
no it wasn't
all of the forks are forked off of dpy 1.7.3. Views was not a concept introduced at that time
#381965829857738772 message it was released in 2.0 but the development started already after 1.7.3
then why are you actively not using dpy?
i don't like some things like the interaction class
use subclasses for different interaction types is better for typing
thats dope, very useful for what im doing even if its not practical, ty
what is this opinion? just because it's a "preference?"
Isn't it all about preferences?
you asked why i'm not using d.py not why i'm not reccomending it, if i should choose something it's obvious that i would choose something that i prefer
in the past i also listed why i reccomend it, in the end the user choose what he needs
blasphemy
Hi everyone. I have an problem with youtube_dl exactly this:
Unable to extract video data
Download error
!ytdl
Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.
For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:
The following restrictions apply to your use of the Service. You are not allowed to:
1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service; (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;
3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTube’s robots.txt file; (b) with YouTube’s prior written permission; or (c) as permitted by applicable law;
9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
We don't help with youtube_dl, sorry
hi again robin, u helped last time it worked but now i have another issue,
File "/workspaces/codespaces-blank/bot.py", line 172, in check
int(message.content)
ValueError: invalid literal for int() with base 10: ''
def check(message):
return message.channel == interaction.channel and message.author == interaction.user
try:
# Wait for a response from the same user in the same channel
response_message = await client.wait_for("message", check=check, timeout=600) # Adjust the timeout as needed (in seconds)
userid = int(response_message.content)
guild = interaction.guild
member = guild.get_member(userid)
if response_message == interaction.user.id:
return await interaction.channel.send("You cannot add yourself to the ticket.")
await interaction.channel.set_permissions(member, view_channel=True, send_messages=True)
# Process the user's response, for example:
await interaction.channel.send(f"Added @<{response_message.content}> to the ticket")
except asyncio.TimeoutError:
# Handle the case where the user did not respond within the specified timeout
await interaction.channel.send("You did not respond in time. The conversation has ended.")```
Looks like response_message.content was blank. Did you have message contents enabled?
yes, i do, ive also confirmed that by adding a print 'msg.content' and it returns a blank statement
What message did you send when it's waiting?
one moment
excuse the light mode, its natural
i forget that lightmode is an irregularity on discord
!paste Hmm. Can you pastebin your whole code? This is odd.
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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
All of your code, please
ok
It is easier to help when I have the full picture
Can you also paste the bot file?
what bot file
The file where you define your bot instance
import discord
from discord.ui import Select
import asyncio
from discord.ui import View
from discord import SelectOption
intents = discord.Intents.default()
intents.typing = False
intents.presences = False
client = discord.Client(intents=intents)
@client.event
async def on_ready():
print(f'Logged in as {client.user.name}')```
Yeah you're missing message content intents
Default doesn't include message content, as it's a privledged intent
intents.message_content = True
yes it worked
i just used .all so i dont gotta enable anything that shud be later on, thanks bro
Would not recommend enabling all. Takes up more processing power
Enable only what you need
oh ok
How do I disable / change this?
oh wait @sick birch
raise ValueError('target parameter must be either Member or Role')
ValueError: target parameter must be either Member or Role
if embed:
await interaction.response.send_message(embed=embed)
await asyncio.sleep(1)
await interaction.channel.send(embed=idembed)
def check(message):
return message.channel == interaction.channel and message.author == interaction.user
try:
# Wait for a response from the same user in the same channel
response_message = await client.wait_for("message", check=check, timeout=600) # Adjust the timeout as needed (in seconds)
userid = int(response_message.content)
guild = interaction.guild
member = guild.get_member(userid)
if response_message == interaction.user.id:
return await interaction.channel.send("You cannot add yourself to the ticket.")
await interaction.channel.set_permissions(member, view_channel=True, send_messages=True)
# Process the user's response, for example:
await interaction.channel.send(f"Added @<{response_message.content}> to the ticket")
except asyncio.TimeoutError:
# Handle the case where the user did not respond within the specified timeout
await interaction.channel.send("You did not respond in time. The conversation has ended.")```
i thought it would work
You can pass in None into help_command kwarg while you construct your bot to disable it:
bot = commands.Bot(command_prefix=";", help_command=None)
thank you!
Did you delete the pastebin? It's 404'ing me
yes
Can you re-upload please? It's very hard to help without having everything
await interaction.channel.set_permissions(member, view_channel=True, send_messages=True)
File "/usr/local/python/3.10.8/lib/python3.10/site-packages/discord/abc.py", line 935, in set_permissions
raise ValueError('target parameter must be either Member or Role')
ValueError: target parameter must be either Member or Role
Looks like member = guild.get_member(userid) returned None
Make sure your bot can "see" the user that ID is associated with
wut
ima try user=member
await interaction.channel.set_permissions(user=member, view_channel=True, send_messages=True)
TypeError: GuildChannel.set_permissions() missing 1 required positional argument: 'target'
@sick birch ^
That's not going to change anything. discord.py is expecting a Member or Role object as the first positional argument
yes, i did put the member object
userid = int(response_message.content)
guild = interaction.guild
member = guild.get_member(userid)```
@sick birch ^
That's not a Member object. That's why the error is happening - it's None
Is the ID you input in the same guild?
yes
You might try enabling the members intent, then, to see if your cache is not being populated correctly
okay let me c
it worked!
thanks robin
after countless days, i have done it, i made an auth bot that can join servers for people
i have a question, did you use the user's personal access token as authentication for the oauth2 API routes, in your case to join guilds ?
we made our own discord module and yes its access tokens and refresh tpkrns
Umm are you doing your requests asynchronously
I.e are you using aiohttp
Or the async client in httpx
how do I fix this? (discord.py)
show code
My guess is that you didn’t put an f before your string
then how did they get the ping variable to show?
intresting
When i use
await vc_channel.set_permissions(dueño, manage_channels=True, manage_permissions=True)
It doesn't do nothing
But if i use:
await vc_channel.set_permissions(dueño, manage_channels=True)
await asyncio.sleep(0.5)
await vc_channel.set_permissions(dueño, manage_permissions=True)
It does put the manage permissions but not the manage channels one, any help?
for the bottom snippet, it replaces it, so thats why
but the top snippet, i tried that, and it works for me
So what can I use instead?
Uuh, well, it does nothing for me, let me send the entire command.
@bot.command()
async def crearvc(ctx, dueño: discord.Member, nombre_canal):
staff_role = ctx.guild.get_role(staff_role_id)
if staff_role and staff_role in ctx.author.roles:
category = ctx.guild.get_channel(categoria_personalizada_id)
if category and isinstance(category, discord.CategoryChannel):
# Crea el canal de voz en la categoría especificada
vc_channel = await category.create_voice_channel(name=nombre_canal)
await vc_channel.set_permissions(dueño, manage_channels=True, manage_permissions=True)
session = Session()
vc_personalizado = VCPersonalizado(
nombre_canal=nombre_canal,
id_canal=str(vc_channel.id),
id_dueño=str(dueño.id),
id_categoria=str(categoria_personalizada_id)
)
session.add(vc_personalizado)
session.commit()
session.close()
embed = success_embed("Éxito", f'Se ha creado el canal de voz "{nombre_canal}" para {dueño.mention}.')
await ctx.send(embed=embed)
else:
embed = error_embed("Error", 'No se encontró la categoría especificada.')
await ctx.send(embed=embed)
else:
embed = error_embed("Error", 'No tienes permiso para ejecutar este comando o no tienes el rol de staff requerido.')
await ctx.send(embed=embed)
It's on spanish btw, it just creates a voice channel and saves the info on the database.
I need help, I made a server backup bot, but upon restoring, the channels that didn't have a category, are getting put into a category, when I don't want them to be, can anyone help, I can provide code
Show code
SnowflakeList('Q', [363328781022265344, 364822725467832321, 364846629175427073, 384173364849410048, 403953822441013248, 509682779571617801, 690298992474849292, 702584168525332580, 702584184052645930, 826152032071188491, 1045358666104193125, 1072364127491739679, 1105823156037496933, 1110851398159056967, 1112505356921339904, 1116526892191862816, 1117164006197690460, 1117164805367804044, 1148248251900907600, 1152675123678162997, 1152675562217812009])
What kind of list is this ? and how do you work with it?
can u tell what type of function it is?
how do you set an embed's image to a file
Imagine that you're coding a Discord bot and every time somebody uses a command, you need to get some information from a database. But there's a catch: the database servers are acting up today and take a whole 10 seconds to respond. If you do not use asynchronous methods, your whole bot will stop running until it gets a response from the database. How do you fix this? Asynchronous programming.
What is asynchronous programming?
An asynchronous program utilises the async and await keywords. An asynchronous program pauses what it's doing and does something else whilst it waits for some third-party service to complete whatever it's supposed to do. Any code within an async context manager or function marked with the await keyword indicates to Python, that whilst this operation is being completed, it can do something else. For example:
import discord
# Bunch of bot code
async def ping(ctx):
await ctx.send("Pong!")
What does the term "blocking" mean?
A blocking operation is wherever you do something without awaiting it. This tells Python that this step must be completed before it can do anything else. Common examples of blocking operations, as simple as they may seem, include: outputting text, adding two numbers and appending an item onto a list. Most common Python libraries have an asynchronous version available to use in asynchronous contexts.
async libraries
The standard async library - asyncio
Asynchronous web requests - aiohttp
Talking to PostgreSQL asynchronously - asyncpg
MongoDB interactions asynchronously - motor
Check out this list for even more!
how do you check if the person running the command is_owner
i couldn't find anything for slash commands
define your own check
wdym
yes
i need help with this i dont understand
Traceback (most recent call last): File "c:/Users/rivar/Desktop/Poll discord/main.py", line 4, in <module> client = commands.Bot(command_prefix = '!') TypeError: __init__() missing 1 required keyword-only argument: 'intents'
Well the error is pretty self explaining
It says you haven't put intents inside you bot class
!intents
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.
There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.
Afterwards in your code, 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
# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.
Anyone knows how to fix?
define a log_channels varriable?
Didn't I already do this?
doesnt look like
Can you help me with that tho? I'm a beginner and it's been some time when I last coded too
log_channels hasn’t been defined
Pretty self explanatory
Will this function also be triggered when messages are edited by users?
@client.listen()
async def on_message(message):```
No
!d discord.on_message_edit
discord.on_message_edit(before, after)```
Called when a [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message) receives an update event. If the message is not found in the internal message cache, then these events will not be called. Messages might not be in cache if the message is too old or the client is participating in high traffic guilds.
If this occurs increase the [`max_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client) parameter or use the [`on_raw_message_edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_raw_message_edit) event instead.
The following non-exhaustive cases trigger this event...
So you can't create a function that works on both new and edited messages? You have to create a separate function for that?
Not unless you want to create your own
Not really sure why you would want that though
I want a function to get triggered by both new and edited messages
Why though
Because it's a bad word filter 
So just use 2 events, and create a function to filter it
Call the function in both events
It should apply to messages even after they've been edited
Right, thanks
You mean something like this:
@client.listen
async def on_message(message):
await handle_message(message)
@client.listen
async def on_message_edit(before, after):
if before.content != after.content:
await handle_message(after)```
Yeah
For some reason it's not working
@client.listen
async def on_message(message):
await handle_message(message)
@client.listen
async def on_message_edit(before, after):
if before.content != after.content:
await handle_message(after)
async def handle_message(message):
if not isinstance(message.author, discord.Member):
return
# Code here```
Oh I'm missing parentheses
How I can edit description in embed? (pycord)
.
I realized that it's easier for me to create a new embed rather than change the old one. Thanks!
who good with excel? i got a question i can pay pm me right now
!rule pay
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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
or paste it there
2023-09-19 23:51:18 ERROR discord.client Ignoring exception in on_guild_join
Traceback (most recent call last):
File "FILE", line 441, in _run_event
await coro(*args, **kwargs)
File "FILE", line 70, in on_guild_join
embed.set_author(icon_url=guild.owner.default_avatar, name=guild.owner, url=f'https://discord.com/users/{guild.owner_id}')
^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'default_avatar'```
I dont get it, the guild that the bot is being added to has a valid owner, then why does it says guild.owner is None?
its a big error
!paste
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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
dude paste it there if its too big, dont flood the chat
wha else then
pls ping if anyone knows ^^
do u have necessary intents enabled?
discord.Intents.default() should enable the guilds intent as well right?
u need members iirc
but I am fetching the guild owner not member
i need help with this error
https://paste.pythondiscord.com/6EZQ
sometimes it returns the guild owner, but most of the time it returns None
technically guild owner is also a member
try with server members intent i would say
File "/workspaces/MyFirstDiscordBot/bot.py", line 28, in on_ready
await bot.load_extension("commands") # Replace "commands" with the actual filename without the ".py" extension
check on_ready in bot.py
this is not your code is it?
it is
i have it there
i put the the thang there so i remember for later
new discord bot coder thats why i put that there
oh it works. but will discord even verifiy my members intent just for some join and leave logs?
tbh idk it depends on the person verifying your bot
i fixed it
You can use guild.owner_id then get/fetch the member yourself if that happens
no
discord will probably deny you that intent if you say it's for join/leave logging purposes
this is hence why I plan on removing that intent from mine and just leaving message content since my bot is using hybrid commands. And for message content, i plan on creating an essay on why
why don't you fully migrate to slash commands? i mean discord enforced them to not give message content intent to bots for commands
read the source code here. It's 12.8K lines of Python code
feel free to make a pr to convert all of them to slash commands once you understand how complex the bot is
i'm not here to go against you 😭 but i don't think that's a valid excuse for discord, even big bots were forced to migrate
they have a team. I'm a solo developer. Migrating my bot would take too much effort and would not quantify the time spent
the goal is to create a module that depends on message_content that solves an issue that most people face
wdym?
Just curious what's the point of passing the pool thru bot when you're passing the bot already
https://github.com/No767/Kumiko/blob/4e4d642fb08eb1165fac622cfecab9518bbd3eb8/Bot/kumikocore.py#L42
Bot/kumikocore.py line 42
bot, interaction.user.id, bot.pool```
more explict
most if not all of my helper coros follow this design of passing in the pool object directly, so it makes sense to implement it as so
fair
!d typing.TYPE_CHECKING
https://github.com/No767/Kumiko/blob/4e4d642fb08eb1165fac622cfecab9518bbd3eb8/Bot/Libs/utils/blacklist.py#L41 might be helpful
typing.TYPE_CHECKING```
A special constant that is assumed to be `True` by 3rd party static type checkers. It is `False` at runtime.
Usage:
```py
if TYPE_CHECKING:
import expensive_mod
def fun(arg: 'expensive_mod.SomeType') -> None:
local_var: expensive_mod.AnotherType = other_fun()
``` The first type annotation must be enclosed in quotes, making it a “forward reference”, to hide the `expensive_mod` reference from the interpreter runtime. Type annotations for local variables are not evaluated, so the second annotation does not need to be enclosed in quotes.
Bot/Libs/utils/blacklist.py line 41
# Circular import so bot is untyped```
FYI i know about this already and have tested this
does not work in my case
unless you want to demostrate that in fact, you can make it work, feel free to make a pr and i'll test and code review it to ensure it will work
bet I'll do that when I'm home
ok i will be expecting to see a PR in a couple of hours
Just made 2 changes in the code ( on my cloud environment)
from __future__ import annotations
from typing import Dict, TYPE_CHECKING
if TYPE_CHECKING:
from Bot.kumikocore import KumikoCore
# in function
async def get_or_fetch_blacklist(bot: KumikoCore, id: int, pool: asyncpg.Pool) -> bool:
``` worked like a charm for importing in a file
I couldn't test on a running bot since I don't have a dev environment rn but importing this way can have no issues \:)
ok thanks for letting me know
What is the point of TYPE_CHECKING?
they are importing that function in the file where KumikoCore is defined, which would lead to a circular import if not imported under TYPE_CHECKING
do you know from __future__ import annotations as well? if you don't import it you should annotate things imported under type checking as strings
you should annotate things imported under type checking as strings
What?
from typing import Dict, TYPE_CHECKING
if TYPE_CHECKING:
from Bot.kumikocore import KumikoCore
# in function
async def get_or_fetch_blacklist(bot: "KumikoCore", id: int, pool: asyncpg.Pool) -> bool:
the future import does that for you
you know that my project keeps compatibility with 3.8 - 3.11? I would rather explicitly import from __future__ import annotations instead
String annotations work with any version from 3.8 on
hm ok
Can I retrieve a message object with just it's ID?
Or do I need the channel as well
channel as well
Gross. Alright
hey uh how would i add command cooldowns
!paste
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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
Can someone help, I keep getting this error on this code
https://paste.pythondiscord.com/TTAA
Heyy! Is there any way I can make a Interaction.Modal appear when I press a button?
use discord.app_commands.checks.cooldown decorator for app commands, and commands.cooldown decorator for text commands
Does anyone know what this means?
(venv) PS C:\Users\boyle\PycharmProjects\NoteWizzard> py -3.10 -m pip install -U wavelink
No suitable Python runtime found
Pass --list (-0) to see all detected environments on your machine
or set environment variable PYLAUNCHER_ALLOW_INSTALL to use winget
or open the Microsoft Store to the requested version.
You need a better Python Runtime
--list
Do I run that in the termal?
yuh
At line:1 char:3
+ --list
+ ~
Missing expression after unary operator '--'.
At line:1 char:3
+ --list
+ ~~~~
Unexpected token 'list' in expression or statement.
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : MissingExpressionAfterOperator
Are you using pycharm?
Yes
Could you screenshot your interpreter settings?
^
You’re doing 3.10 here
And you have 3.11 installed
so I just change 3.10 to 11?
You shouldn’t need to use the version at all
You’re in a venv, you should only have 1 interpreter
I got it...
discord.ext.commands.errors.ExtensionFailed: Extension 'Cog' raised an error: TypeError: module() takes at most 2 arguments (3 given)
import discord
from discord import app_commands
from discord.ext import commands
import wavelink
from typing import Any
intents = discord.Intents.default()
intents.message_content = True
class player(wavelink.player):
def __init__(self, bot: discord.member, *args: Any, **kwargs: Any):
super().__init__(*args, **kwargs)
self.bot = bot
@app_commands.command(name="play")
async def connect(self, interaction: commands.Context, *, channel: discord.VoiceChannel | None = None):
try:
channel = channel or interaction.author.channel.voice
except AttributeError:
return await interaction.reply("User is not in voice channel.")
vc: wavelink.player = await channel.connect(cls=wavelink.player)
return vc
@app_commands.command(name="sync")
async def slash_sync(self, interaction):
await interaction.response.send_message("Commands Successfully synced!")
await self.bot.tree.sync()
async def cog_load(self):
print(f"{self.__class__.__name__} loaded!")
async def cog_unload(self):
print(f"{self.__class__.__name__} unloaded!")
async def setup(bot):
await bot.add_cog(player(bot=bot))
What’s the full traceback
the full error?
Sure
Traceback (most recent call last):
File "C:\Users\boyle\PycharmProjects\NoteWizzard\main.py", line 16, in <module>
NoteWizzard().run(TOKEN)
File "C:\Users\boyle\PycharmProjects\NoteWizzard\venv\Lib\site-packages\discord\client.py", line 860, in run
asyncio.run(runner())
File "C:\Users\boyle\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 190, in run
return runner.run(main)
^^^^^^^^^^^^^^^^
File "C:\Users\boyle\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 118, in run
return self._loop.run_until_complete(task)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\boyle\AppData\Local\Programs\Python\Python311\Lib\asyncio\base_events.py", line 653, in run_until_complete
return future.result()
^^^^^^^^^^^^^^^
File "C:\Users\boyle\PycharmProjects\NoteWizzard\venv\Lib\site-packages\discord\client.py", line 849, in runner
await self.start(token, reconnect=reconnect)
File "C:\Users\boyle\PycharmProjects\NoteWizzard\venv\Lib\site-packages\discord\client.py", line 777, in start
await self.login(token)
File "C:\Users\boyle\PycharmProjects\NoteWizzard\venv\Lib\site-packages\discord\client.py", line 621, in login
await self.setup_hook()
File "C:\Users\boyle\PycharmProjects\NoteWizzard\main.py", line 14, in setup_hook
await self.load_extension("Cog")
File "C:\Users\boyle\PycharmProjects\NoteWizzard\venv\Lib\site-packages\discord\ext\commands\bot.py", line 1013, in load_extension
await self._load_from_module_spec(spec, name)
File "C:\Users\boyle\PycharmProjects\NoteWizzard\venv\Lib\site-packages\discord\ext\commands\bot.py", line 938, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'Cog' raised an error: TypeError: module() takes at most 2 arguments (3 given)
If you want to sent the solution or help me understand the errors, send them in my dms im heading off to bed
heyyy so im makin a discord bot for a friend to troll somenoe, and im tryna make it have a toggle. so anyone with an admin role id would be able to toggle it on or off, and I cant figure out the toggle bit
Toggle = False
@bot.command()
async def toggle(ctx):
if is_admin(ctx):
Toggle
await ctx.reply('Toggle is now ON')
else:
await ctx.send('You dont have permission to use this command')
@bot.event
async def on_message(message):
vowels = "Uu"
if Toggle:
if is_snake(message):
if any(v in vowels for v in message.content.lower()):
await message.delete()
else:
await message.channel.send("Function disabled")
rn the issue is its just sending "function disabled" over andover at any message
because the is admin condition isn't being satisfied
Bind the toggle to your bot instance
Python scope doesn't really work like that
so do i just slap the toggle bit under bot event or
And yes use has_role
idk im still new ish and i do python in small bursts, so most of the terminology is non existent in my head
Instead of defining Toggle = False you'd do bot.toggle = False at the very top
To toggle it on you'd do bot.toggle = True
In your on_message you would check if bot.toggle
so for the has_role bit it would be
if message.author has_role(admin_id):
bot.toggle = True
wait no that doesnt work
!d discord.ext.commands.has_role
@discord.ext.commands.has_role(item)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check) that is added that checks if the member invoking the command has the role specified via the name or ID specified.
If a string is specified, you must give the exact name of the role, including caps and spelling.
If an integer is specified, you must give the exact snowflake ID of the role.
If the message is invoked in a private message context then the check will return `False`.
This check raises one of two special exceptions, [`MissingRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingRole) if the user is missing a role, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage) if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure).
Changed in version 1.1: Raise [`MissingRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingRole) or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage) instead of generic [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure)...
i got that, but regardless of the role its still spamming "function disabled"
It sure will
You never change the variable's value from False to something else
So, the if Toggle statement will never be true
def get_messages(sender, recipient, message):
sender = sender.lower()
sender_role = "assistant" if sender == "assistant" else "user"
role = recipient.lower() if sender == "assistant" else sender
user = get_user(role)
personality = user['personality'] if user else config["global_personality"]
bot_context=config["system_context"]
system_role={"role": "system", "content": f"{bot_context}."}
prefix='' if sender_role == 'assistant' else f"{personality}"
add_message({"role": sender_role, "content": f"{prefix} {message}"})
return [
system_role,
*[{"role": obj['role'], "content": obj['content']} for obj in history]
]
async def generate_response(message):
try:
if message.author == bot.user:
return
def call_openai_api():
logger.info('Звоню на Апишник')
return openai.ChatCompletion.create(
model=config["model"],
messages=get_messages(message.author.name, 'assistant', message.content),
temperature = 0.7
)
await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name="a " + message.author.name))
async with message.channel.typing():
logger.info(message.author.name + ": " + message.content)
response = await bot.loop.run_in_executor(None, call_openai_api)
content = response['choices'][0]['message']['content']
await message.reply(content)
get_messages('assistant', message.author.name, content)
logger.info("Assistant: " + content)
logger.info("Токены: " + str(response["usage"]["total_tokens"]))
#changing presence and error handling
So, the problem is, i need to have {message.author.name} at the end of system prompt/request, but im not sure i know where should i put it.
how do i do that
@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | False
002 | True
or maybe at the start of system prompt, idk.
Error
Code:
import discord
from discord_slash import SlashCommand
client = discord.Client(intents=discord.Intents.all())
slash = SlashCommand(client, sync_commands=True) # Declares slash commands through the client.
@client.event
async def on_ready():
print("Ready!")
client.run("my_token_here")
but its already installed...
then how come it shows no module named 'discord_slash'?
Because there's no module named discord_slash, not even in the screenshot
If you're using discord.py, none; discord.py already support slash commands
Oh.
What about pycord?
What do I need to install?
py-cord also support slash commands
Oh.
Looks like ChatGPT code
You are using dpy so no u don't
Here is a short example of how to use discord.py's slash commands as well as general information on them:
https://gist.github.com/AbstractUmbra/a9c188797ae194e592efe05fa129c57f
This currently covers free commands and groups at the Bot level, as well as within Cog classes.
It also includes information and gotchas relating to syncing and whatnot.
NOTE: This will be migrating to https://about.abstractumbra.dev/ as soon as I can be bothered to finish it.
My site for random things and stuff. Including a custom pip index and walkthroughs, both for discord.py!
Also please don't get me started on the story of how I got banned from the Pycord server for pointing out a flaw with their bot
Yes that's an actual story that happened a couple of weeks ago btw
Yes that was chatgpt code, as i dont want to paste my thousands of lines code here (of my original bot)
But, I have an already working bot (made 1-2 years ago)
but it has this error
and heres the python libaries installed
start of the code:
import discord
from discord.ext import tasks, commands
from discord.ext.commands import cooldown, BucketType
import sys, traceback
import os
import time
import random
import asyncio
import json
import os
import aiohttp
import mysql.connector
import numpy as np
from discord import Intents
from discord import default_permissions
from discord.ext import commands
from discord.commands import Option
the bot was originally hosted locally on my pc, and it still runs perfectly
but now i want to switch it to cloud hosting
this is what i put in requirements.txt
discord.py==2.3.0
aiohttp==3.8.4
async-generator==1.10
async-timeout==4.0.2
mysql-connector-python==8.0.33
numpy==1.24.2
py-cord==2.4.1
requests==2.28.2
Get rid of py-cord since the package namespaces overlap and you are already mainly using dpy from what I can tell
Remove Pycord as mentioned
ok
discord.py
aiohttp
async-generator
async-timeout
mysql-connector-python
numpy
requests
Successfully installed aiohttp-3.8.5 aiosignal-1.3.1 async-generator-1.10 async-timeout-4.0.3 attrs-23.1.0 certifi-2023.7.22 charset-normalizer-3.2.0 discord.py-2.3.2 frozenlist-1.4.0 idna-3.4 multidict-6.0.4 mysql-connector-python-8.1.0 numpy-1.26.0 protobuf-4.21.12 requests-2.31.0 urllib3-2.0.5 yarl-1.9.2
Traceback (most recent call last):
File "/home/container/awwpika.py", line 18, in <module>
from discord import default_permissions
ImportError: cannot import name 'default_permissions' from 'discord' (/home/container/.local/lib/python3.11/site-packages/discord/init.py)
container@pterodactyl~ Server marked as offline...
[Bot-Hosting Daemon]: ---------- Detected server process in a crashed state! ----------
[Bot-Hosting Daemon]: Exit code: 1
[Bot-Hosting Daemon]: Out of memory: false
[Bot-Hosting Daemon]: Aborting automatic restart, last crash occurred less than 600 seconds ago.
still same error
It's pycord.
ah
then why are you installing discord.py 
pycord also doesn't have it btw
it has discord.commands.default_permissions
but not discord.default_permissions
ah ok it seems they import everything in discord
https://docs.pycord.dev/en/stable/api/application_commands.html#discord.commands.default_permissions
Command Permission Decorators: Commands: Shortcut Decorators: Objects: Attributes full_parent_name, qualified_id, qualified_name. Methods@ after_invoke,@ before_invoke,@ error, def get_cooldown_ret...
then just don't install discord.py together with pycord
so do i need to install pycord or no?
thanks so much
what's the best approach to keep looping a song in a vc for a particular period of time
def get_messages(sender, recipient, message):
sender = sender.lower()
sender_role = "assistant" if sender == "assistant" else "user"
role = recipient.lower() if sender == "assistant" else sender
user = get_user(role)
personality = user['personality'] if user else config["global_personality"]
bot_context=config["system_context"]
system_role={"role": "system", "content": f"{bot_context}."}
prefix='' if sender_role == 'assistant' else f"{personality}"
add_message({"role": sender_role, "content": f"{prefix} {message}"})
return [
system_role,
*[{"role": obj['role'], "content": obj['content']} for obj in history]
]
async def generate_response(message):
try:
if message.author == bot.user:
return
def call_openai_api():
logger.info('Звоню на Апишник')
return openai.ChatCompletion.create(
model=config["model"],
messages=get_messages(message.author.name, 'assistant', message.content),
temperature = 0.7
)
await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name="a " + message.author.name))
async with message.channel.typing():
logger.info(message.author.name + ": " + message.content)
response = await bot.loop.run_in_executor(None, call_openai_api)
content = response['choices'][0]['message']['content']
await message.reply(content)
get_messages('assistant', message.author.name, content)
logger.info("Assistant: " + content)
logger.info("Токены: " + str(response["usage"]["total_tokens"]))
#changing presence and error handling
So, the problem is, i need to have {message.author.name} at the end of system prompt/request, but im not sure that iknow where should i put it.
Hard to fall in the joke with such a bad quality picture
does anyone know why this doesnt edit permissions to do this
await channel.set_permissions(ctx.guild.default_role, read_messages=True, send_messages=False)
its not even right colour
!
does anyone know why this doesnt edit permissions to do this
await channel.set_permissions(ctx.guild.default_role, read_messages=True, send_messages=False)
not to mention its only in dms 😭
nah it can be used in guilds too
no? its in servers
just you need attach file sperms
since when
yo down, my favourite helper can you help
judging from discord/discord-api-docs#6082, it requires the Send Voice Messages permission, not Attach Files
no i wanna know why it doesnt edit perms here
oh oops, i dont edit channel permissions from my bot often so i wouldn't know
it's been for a while
Traceback (most recent call last):
File "C:\Users\boyle\PycharmProjects\NoteWizzard\venv\Lib\site-packages\discord\ext\commands\bot.py", line 935, in _load_from_module_spec
spec.loader.exec_module(lib) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "<frozen importlib._bootstrap_external>", line 940, in exec_module
File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
File "C:\Users\boyle\PycharmProjects\NoteWizzard\Cog.py", line 10, in <module>
class player(wavelink.player):
TypeError: module() takes at most 2 arguments (3 given)
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\boyle\PycharmProjects\NoteWizzard\main.py", line 16, in <module>
NoteWizzard().run(TOKEN)
File "C:\Users\boyle\PycharmProjects\NoteWizzard\venv\Lib\site-packages\discord\client.py", line 860, in run
asyncio.run(runner())
File "C:\Users\boyle\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 190, in run
return runner.run(main)
^^^^^^^^^^^^^^^^
File "C:\Users\boyle\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 118, in run
return self._loop.run_until_complete(task)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\boyle\AppData\Local\Programs\Python\Python311\Lib\asyncio\base_events.py", line 653, in run_until_complete
return future.result()
^^^^^^^^^^^^^^^
File "C:\Users\boyle\PycharmProjects\NoteWizzard\venv\Lib\site-packages\discord\client.py", line 849, in runner
await self.start(token, reconnect=reconnect)
File "C:\Users\boyle\PycharmProjects\NoteWizzard\venv\Lib\site-packages\discord\client.py", line 777, in start
await self.login(token)
File "C:\Users\boyle\PycharmProjects\NoteWizzard\venv\Lib\site-packages\discord\client.py", line 621, in login
await self.setup_hook()
File "C:\Users\boyle\PycharmProjects\NoteWizzard\main.py", line 14, in setup_hook
await self.load_extension('Cog')
File "C:\Users\boyle\PycharmProjects\NoteWizzard\venv\Lib\site-packages\discord\ext\commands\bot.py", line 1013, in load_extension
await self._load_from_module_spec(spec, name)
File "C:\Users\boyle\PycharmProjects\NoteWizzard\venv\Lib\site-packages\discord\ext\commands\bot.py", line 938, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'Cog' raised an error: TypeError: module() takes at most 2 arguments (3 given)
Getting this error, and I don't 100% undstand what it is trying to let me know is wrong. Can someone try to help me figure out that?
This is my orignal Code:
import discord
from discord import app_commands
from discord.ext import commands
import wavelink
from typing import Any
intents = discord.Intents.default()
intents.message_content = True
class player(wavelink.player):
def __init__(self, bot: discord.member, *args: Any, **kwargs: Any):
super().__init__(*args, **kwargs)
self.bot = bot
@app_commands.command(name="play")
async def connect(self, interaction: commands.Context, *, channel: discord.VoiceChannel | None = None):
try:
channel = channel or interaction.author.channel.voice
except AttributeError:
return await interaction.reply("User is not in voice channel.")
vc: wavelink.player = await channel.connect(cls=wavelink.player)
return vc
@app_commands.command(name="sync")
async def slash_sync(self, interaction):
await interaction.response.send_message("Commands Successfully synced!")
await self.bot.tree.sync()
async def cog_load(self):
print(f"{self.__class__.__name__} loaded!")
async def cog_unload(self):
print(f"{self.__class__.__name__} unloaded!")
async def setup(bot):
await bot.add_cog(player(bot=bot))
?
You need to subclass commands.Cog
You can't subclass wavelink.player and magically have the class turn into a cog
bot is also typehinted wrong
It's not discord.member, nor discord.Member
Your interaction typehint is also wrong
discord.Interaction.reply() doesn't exist as well
You're also loading a cog named Cog
What should I use and where?
So what do I do?
.
What are you trying to do
Create a music but by using wavelink
To let the user know the error
What's wrong with using send_message
Can I not reply to the users interaction
class discord.Interaction```
Represents a Discord interaction.
An interaction happens when a user does an action that needs to be notified. Current examples are slash commands and components.
New in version 2.0.
Read the docs
discord.ext.commands.errors.ExtensionFailed: Extension 'Cog' raised an error: TypeError: module() takes at most 2 arguments (3 given)
but like what is failing here
Already explained it.
class Cog(commands.Cog):
def __init__(self, bot):
self.bot = bot
class Player(wavelink.player):
def __init__(self, bot: discord.member, *args: Any, **kwargs: Any):
super().__init__(*args, **kwargs)
self.bot = bot
Is that what you meant?
Same error
^
Yes, because doing that makes no sense
await bot.add_cog(Cog(bot=bot))
It is this?
You shouldn't be nesting classes
You should have 1 class, which inherits from commands.Cog
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
OOP and async programming are the recommended bare essentials for discord.py
Inheriting is basic OOP
You need to inherit commands.Cog in your main class, not wavelink
I just really want to make a music bot.
Okay, you've been given the solution
If you want to load a cog it has to inhert from commands.Cog
Not wavelink
Why not just use one of the existing ones
Because I want to design and improve and add features that preexisting ones do not have. Its also helps me to know what I can and not do. I want to also feel good about learning, and developing bots for my friends and others to enjoy,
@thorny tangle
<@&831776746206265384>
Spam/potential raid
I think it's a self-bot tbh
The reactions were added very quickly
Anyway, how should I go about testing functions/blocks of code for speed/efficiency
I'm also interested in this, all that comes to my mind is log the times that things are triggered with datetime.now
!e
prcnt = 50
print(f"[{'=' * prcnt}{' ' * (100 - prcnt)}]({prcnt}%)")
@pastel token :white_check_mark: Your 3.11 eval job has completed with return code 0.
[================================================== ](50%)
nice
prcnt = 25
print(f"[{'=' * prcnt}{' ' * (100 - prcnt)}]({prcnt}%)")
!e
prcnt = 25
print(f"[{'=' * prcnt}{' ' * (100 - prcnt)}]({prcnt}%)")
@pastel token :white_check_mark: Your 3.11 eval job has completed with return code 0.
[========================= ](25%)
holy shit
wait what if i do the old command
!e
prcnt = 50
print('['+('=' * prcnt) + (" " * (100 - prcnt))']' + '(' + str(prcnt) + '%)')
@pastel token :x: Your 3.11 eval job has completed with return code 1.
001 | File "/home/main.py", line 2
002 | print('['+('=' * prcnt) + (" " * (100 - prcnt))']' + '(' + str(prcnt) + '%)')
003 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
004 | SyntaxError: invalid syntax. Perhaps you forgot a comma?
ok fstrings it is
#bot-commands
THAT EXISTS?!?
…

I wonder as well, but also I've ran it twice in the same command to run some tests and it seems to be fairly consistent with the short time spans between the beginning and end of commands. Like... 0.002 secs
!docs discord.TextChannel.create_webhook
await create_webhook(*, name, avatar=None, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a webhook for this channel.
You must have [`manage_webhooks`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_webhooks) to do this.
Changed in version 1.1: Added the `reason` keyword-only parameter.
if you only have the url though, there is a sync alternative such as SyncWebhook.from_url
!d discord.SyncWebhook.from_url
classmethod from_url(url, *, session=..., bot_token=None)```
Creates a partial [`Webhook`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Webhook) from a webhook URL.
uh... that requires that webhook to already exist, right?
I thought we were looking at creating a brand new webhook
i mean, you create it once, and that's it, after that you always reference the url
!d discord.Webhook.url
property url```
Returns the webhook’s url.


