#discord-bots
1 messages ยท Page 176 of 1
self.bot=bot
self.bot.database_handler ....
its in the setup where do i call it
how do i add a database ๐ญ im so sorry im not that advanced
where are u hosting
im not hosting the bot, im making the bot for sometone
then where are u making the bot at
vs code
๐
if u are using replit i will say json
but bro i dont think vs code have database
KEKW
i can ig
you dont need to import or call anything extra
im like so confused
self.bot.database_handler will give you the database class
access the method directly
here?
change it here?
@slate swan what am i supposed t oput for the value in the embed at the top?
yes
learn a database at first
i can't help if you have no idea about that
or atleast a dictionary
nono
record the data on a piece of paper
u can create ur own language from there ๐
this?
or remove the progress.database
self.bot.database_handler
.
yes....
show the fetchvalue function
ya...
dont think injection is possible there
also asyncpg has a fetchval already
3 weeks of time wasted
why making a new one
for reusing purposes
instead of .fetch use .fetchval
whats the dif
it returns the first object
oo
u wont have to do [0]
async def fetchval(self, query: str, *args: t.Any) -> t.Any:
assert self._pool is not None
async with self._pool.acquire() as conn:
return await conn.fetchval(query, *args)
here is mine
:quit_bot_dev_permanently:

someone help me to inject
;-;
you can use fstring for declaring the table name
use a f string
nothing wrong in it
but yeah use placeholder for arguments
@bot.slash_command(name="editchannel", description="A command to quickly edit your channels!")
@default_permissions(administrator=True)
@commands.cooldown(1, 3, commands.BucketType.user)
async def editchannel(ctx, editname:Option(str, "Input new channel name.", required=True)):
await channel.edit(name=editname)
em = discord.Embed(title="Channel Name Changed!", description=f"You channel name has been changed to, {ctx.channel.name}")
em.set_footer(icon_url = ctx.author.avatar, text=f"Invoked by {ctx.author.name}")
await ctx.respond(embed=em)```
My slash command, does not work. im using pycord
edit channel name
i dont think f strings work for query
it works for only table name?
It does
string1 = f"SELECT $1 FROM {table} WHERE userid = $2"
execute with string 1
can someone help me here
execute with string1?
Execute with the query
Just the query var
2 trials and fked both of them up equally hard
await self.bot.db.fetchval(string1, ...)
wtf
lol that was a comment
not code i sent
i meant string1 becomes your new query string
and u use that to execute
yeye got it now
wdym dosent work
i have been here for 1 year but is still dumb af ๐
how it dosent work
await channel.edit(name=editname)
this line doesnt work, application not respond
Nothing works in pycord
channel isn't defined
And provide an error with the question next time
then how do i define it?
ctx.channel ig
ctx.channel.edit and u have to respond in 3 secs so either send a message first then edit or defer then send a message
display_avatar
alr thxs it works
havent be so desperate to get bot's reply before
do i change everything to string in database
something like playerid = string type
or do i need to add int() on the thing
Show code
i added str() and int()
And what's the code
wait mb i thought i send it ๐
oo thanks
i feel like smashing table now ;-;
what is this
fetchval returns a string
( or whatever the data type was )
why would you use [item] on it again
what options are there to create a selection list on slash command other than using an Enum list?
how did you call the function
ah
you can't use placeholder for column name too
await self.bot.db.fetchval(f"SELECT {item} FROM {tablename} WHERE playerid = $1", userid)```
:/
What error are you getting?
I have no idea what "same" is
Just show the error
I need the entire traceback
It's https://hastebin.com/acebemorax by the way, adding .py to then end tries to get you to download it, not open in browser.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
await ctx.send(mess_channel, embed=embed)
!d discord.abc.Messageable.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 "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 "(in Python v3.11)") of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "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 "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 "(in Python v3.11)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
What are you adding mess_channel into the send for?
the channel the command is being run in?
That's what the ctx is for.
!d discord.ext.commands.Context
class discord.ext.commands.Context(*, message, bot, view, args=..., kwargs=..., prefix=None, command=None, invoked_with=None, invoked_parents=..., invoked_subcommand=None, ...)```
Represents the context in which a command is being invoked under.
This class contains a lot of meta data to help you understand more about the invocation context. This class is not created manually and is instead passed around to commands as the first parameter.
This class implements the [`Messageable`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable "discord.abc.Messageable") ABC.
help()``````py
help(request)```
Invoke the built-in help system. (This function is intended for interactive use.) If no argument is given, the interactive help system starts on the interpreter console. If the argument is a string, then the string is looked up as the name of a module, function, class, method, keyword, or documentation topic, and a help page is printed on the console. If the argument is any other kind of object, a help page on the object is generated.
Note that if a slash(/) appears in the parameter list of a function when invoking [`help()`](https://docs.python.org/3/library/functions.html#help "help"), it means that the parameters prior to the slash are positional-only. For more info, see [the FAQ entry on positional-only parameters](https://docs.python.org/3/faq/programming.html#faq-positional-only-arguments).
This function is added to the built-in namespace by the [`site`](https://docs.python.org/3/library/site.html#module-site "site: Module responsible for site-specific configuration.") module.
!pypi discord.py
make sure u have the correct library installed
yes i doo
reinstall it then
now im getting this?
you got the code from somewhere that isn't discord.py
it is i coded it
bot.slash_command isn't a thing in the library
you might have been using some fork
its tree_command?
yes pycord isnt compatible with discord.py
oh
bot.tree.command
most things won't work you'll have to rewrite your code for slash Commands
when you added the the bot to your server from the developer portal did you click bot and client.commands?
Because client.commands is what enables slash commands
yes ofc
show me your code !paste
i used a fork of discord.py that bot.slash_commands but o forgot the name
!pastebin
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.
without token
this is my new problem lmfao
aight
@slate swan https://paste.pythondiscord.com/kutesiviqo
hmm
how do i send back what the user sent
I have to go @amber ether maybe someone else will find it.
ok ๐ฆ
How are they sending it?
Anyone knows?
for example if i say hi i want it to send hi back
^
just copy the user
if message.content.startswith('$hello'):
await message.channel.send('Hello!')```
no not that
.
!d discord.on_message
discord.on_message(message)```
Called when a [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message") is created and sent.
This requires [`Intents.messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.messages "discord.Intents.messages") to be enabled.
Warning
Your botโs own messages and private messages are sent through this event. This can lead cases of โrecursionโ depending on how your bot was programmed. If you want the bot to not reply to itself, consider checking the user IDs. Note that [`Bot`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot "discord.ext.commands.Bot") does not have this problem.
i used a fork of discord.py that bot.slash_commands but o forgot the name
anyone?
i have that
wdym?
!d discord.Message
class discord.Message```
Represents a message from Discord.
x == y Checks if two messages are equal.
x != y Checks if two messages are not equal.
hash(x) Returns the messageโs hash.
You need to give every argument of the slash command callback a type hint
i just want it to send whatever is sent in chat
if i say hi it says hi back
if i say bye it says bye back
essentially what im asking for is to copy paste the text
!d discord.Message.content
The actual contents of the message. If Intents.message_content is not enabled this will always be an empty string unless the bot is mentioned or the message is a direct message.
if message.content.startswith('Bye'):
await message.channel.send('Bye i will miss your ass')
yeah i tried this but it sends nothing back
:/
Show use your code then
i dont want it to be hardcoded
wdym hardcoded
Make sure you've enabled message content intents.
Reading the docs would have told you that
Show us your code.
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.members = True
intents.messages = True
bot = commands.Bot(command_prefix='-', intents=intents, help_command=None,)
@bot.event
async def on_ready():
print('up and running')
@bot.listen()
async def on_message(message):
if message.author == bot.user:
return
embed = discord.Embed(color=0x00ff00)
mLink = message.jump_url
embed.add_field(name="Jump", value=f"[Go to message!]({mLink})", inline=False)
embed.add_field(name="Message", value=message.content, inline=False)
await message.channel.send(embed=embed)
message_content intent
READING THE DOCS would have told you that
you need message intents smh!
did you make this using chatgpt my guy
, help_command=None,)
no
i used a fork of discord.py that bot.slash_commands but o forgot the name
please helllpp
Know the difference between an integer and a string yet?
...what?
Do you?
It's really really hard to teach anyone Discord.py when they don't even know the basics of python.
Yes, I know this is a project that more than a few people want to make as their first thing but that's like asking a child to run a triathlon.
i dont think its related to my question..
I see your problem here, your traceback is flat out telling you what needs fixed. But I'm not even sure you would understand if I told you what it was. No shade on you, you just don't understand the terminology well enough for us to even help you with this.
just use .all() its like 3 intents extra anyways
and u would need them at some point
except maybe presence intent
also dev portal as well
bro ik but i would have to rewrite..
and i forgot things on python bc of school
i dont think it gonna work with the fork either
also there were 10s of forks if not even more
if u have the env still u can try checking
i've used a fork before i wrote the code.
lol in short there are tons of forks
how are we supposed to know
and even now almost all libs have bot.slash_command for syntax
We know, you keep saying that.
What we are saying is that we here know discord.py, not the forks. if you want to use the fork then most of us are not going to know much about it.
they are forks from the main lib after all
So feel free to use the fork, just don't get upset when no one has any idea what you are talking about
how do you make it send a embed?
send(embed=embed)
then what?
That's all, but before you send it, you have to make the Embed.
What do you have so far?
You should at least have some OOP knowledge before trying discord.py
async def say(ctx, *what):
await ctx.send(" ".join(what))```
instead of ctx.send which is a plain message, i want a embed
!d discord.Embed
class discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, timestamp=None)```
Represents a Discord embed.
len(x) Returns the total size of the embed. Useful for checking if itโs within the 6000 character limit.
bool(b) Returns whether the embed has any data set.
New in version 2.0.
x == y Checks if two embeds are equal.
New in version 2.0...
thank you
!d discord.TextChannel.send
also, how would I make it so the users input would decide what the embed says for example ?say hi bye the bot responds with hi bye in the embed?
Embed = discord.Embed(title="Top Shelf")
await Embed.set_thumbnail(url="https://img.izismile.com/img/img2/20091118/funny_crazy_faces_25.jpg")
ctx.send(embed=Embed)
Take an argument and use it to create the embed
RuntimeWarning waiting to happen
Calm down cat, just giving the new person an example they can work with.
Anyone got any ideas why the command work but doesn't show in the "slash command menu"
import discord
from discord.ext import commands
intents = discord.Intents().all()
client = commands.Bot(command_prefix='/', intents=intents)
@client.command()
async def hello(ctx):
await ctx.send('Hello!')
client.run(TOKEN)
That's not how you create slash commands
Well that could be the problem then hehe ๐
Get it figured out?

You need to sync the commands, everything else seems quite professional 
And how would i do that?
I'm just trolling 
lol
discord.py 2.0+ slash command info and examples. GitHub Gist: instantly share code, notes, and snippets.
have fun reading.
I just love Cunningham's law
๐
ash's guide is much more brief compared to the other one, why? cuz the first one talks more about what not to do than what can you do
its moreover focused on syncing
My point still stands, If I didn't post what I did. I don't think Ash would have ever posted that to correct me and would have just left the new person hanging.
Like I said, I just love Cunningham's law.
yes, I was going to
LOL, nice coverup buddy.
But you have fun, I'm off for now.
maybe, not a point of argument lol
I didn't even edit 

go study
i just got back from class shush
go back for extra class
How do I store the url for an embed?
database, and why the url
I want to add it for the infractions, so that you can navigate using the link
oh well you can grab the message link using discord.Message.jump_url
Like this?
# Get the link of the embed
action_log = embed.url
# Send the embed to the channel
await channel.send(embed=embed)
# Insert warning document into the warnings collection
warnings_collection.insert_one({"case_id": case_id, "user_id": member.id, "reason": actual_reason, "moderator_id": ctx.author.id, "timestamp": timestamp, "action_log": action_log})```
Message.jump_url, you need a message object not an Embed object
But I want to store the url for a embed not a regular message.
a message contains embeds, so you only access the message url
Thanks
ok
Hello
What library can be used to create a bot that automatically sends Reddit posts to Discord?
I want when i posted on my Reddit account, it will also be posted on Discord with bot
Should I change error handler:
@modlogs.error
async def modlogs_error(ctx, error):
if isinstance(error, commands.MemberNotFound):
await ctx.send(f"I could not find the user {error.argument}")```
to
```python
if isinstance(error, discord.ext.commands.errors.MemberNotFound):
Same thing
The first one gives me errors, the second one actually sends out the message that it couldn't find the user.
Do you know why?
because commands is a sub-package, it cannot be accessed directly
So it's not the same thing in that case?
it is the same thing but you cannot use it without import explicitly
import discord
discord.ext.commands.MemberNotFound
# wont work
from discord import ext
ext.commands.MemberNotFound
# wont work
from discord.ext import commands
commands.MemberNotFound
# will work
I'm already using 'from discord.ext import commands' but still getting the error with the first example.
hello guys i am begginer at discord.py bot is there any resourses to learn?
No it's a prefix command
what error does it raise?
the docs are mostly sufficient
!d discord
In order to work with the library and the Discord API in general, we must first create a Discord Bot account.
Creating a Bot account is a pretty straightforward process.
where can i get it
There are also examples to help you get a feel for it.
https://github.com/Rapptz/discord.py/tree/master/examples
How new are you to python in general by the way?
i dont know anything about discord.py
also python in general
This is something you are not going to want to hear but using Discord.py without knowing basic python is like trying to run before you can crawl.
Not saying you can't do it, but it's going to be harder than it need to be when ask you about a function you made and you respond with "What's a function?"
what the basics of python , like what
A few hours of reading
https://automatetheboringstuff.com/#toc
is arrangement of funcs make difference?
Yes.
what func should i start by and end?
See? this is why I gave you that link for the basics.
oh ok i am going to read it if i have any problem can i ping you?
hi, how do create a slash command when a bot will respond with a message and react to it with emoji
I am not going to be around for a lot of today, you would get more help by asking on this server.
ok
thx
Good luck, I know it can be hard.
Ash made something you might like #discord-bots message
[2023-01-10 17:00:44] [ERROR ] discord.client: Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\Gamer\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\bot.py", line 1349, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Gamer\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\core.py", line 1015, in invoke
await self.prepare(ctx)
File "C:\Users\Gamer\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\core.py", line 932, in prepare
await self._parse_arguments(ctx)
File "C:\Users\Gamer\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\core.py", line 839, in _parse_arguments
transformed = await self.transform(ctx, param, attachments)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Gamer\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\core.py", line 709, in transform
return await run_converters(ctx, converter, argument, param) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Gamer\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\converter.py", line 1340, in run_converters
return await _actual_conversion(ctx, converter, argument, param)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Gamer\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\converter.py", line 1222, in _actual_conversion
return await converter().convert(ctx, argument)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Gamer\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\converter.py", line 262, in convert
raise MemberNotFound(argument)
discord.ext.commands.errors.MemberNotFound: Member "39538538" not found.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\Gamer\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\core.py", line 211, in wrapped
ret = await coro(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Gamer\Desktop\blitz.py", line 1338, in modlogs_error
if isinstance(error, commands.MemberNotFound):
^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'Command' object has no attribute 'MemberNotFound'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Gamer\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "C:\Users\Gamer\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\bot.py", line 1394, in on_message
await self.process_commands(message)
File "C:\Users\Gamer\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\bot.py", line 1391, in process_commands
await self.invoke(ctx) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Gamer\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\bot.py", line 1353, in invoke
await ctx.command.dispatch_error(ctx, exc)
File "C:\Users\Gamer\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\core.py", line 635, in dispatch_error
await injected(ctx, error) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Gamer\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\core.py", line 217, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Command' object has no attribute 'MemberNotFound'

File "C:\Users\Gamer\Desktop\blitz.py", line 1338, in modlogs_error
if isinstance(error, commands.MemberNotFound):
^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'Command' object has no attribute 'MemberNotFound'```
What does that mean? Why is ' if isinstance(error, discord.ext.commands.errors.MemberNotFound):' working? I already use 'from discord.ext import commands'
import random
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
@client.event
async def on_ready():
print(f'Je bent ingelogd als: {client.user}')
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('!hello'):
await message.channel.send('Hello, world!')
client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('!help'):
await message.channel.send('!help, laat dit zien')
await message.channel.send('!dice, Rol een getal tussen de 1 en 6.')
await message.channel.send('!echo, Herhaal wat je zegt.')
@client.event
async def on_message(message):
# we do not want the bot to reply to itself
if message.author == client.user:
return
if message.content.startswith('!echo'):
# the user wants the bot to echo a message
# get the message to echo by removing the '!echo' prefix and the channel mention
message_to_echo = message.clean_content[6:]
# send the message
await message.channel.send(message_to_echo)
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('!dice'):
result = random.randint(1, 6)
await message.channel.send(f"You rolled a {result}")
client.run('token')```
my bot can only run !dice. When I put that command in the comment, the echo works
You keep overriding the event
how do I fix that
And use commands.Bot if you want to make prefix commands
AttributeError: 'Command' object has no attribute 'MemberNotFound'
``` like it says, `Command` has no idea what `'MemberNotFound'` is
Do you have a function named commands
how do I do that?
Wrong reply, whatever
stop naming your command function as commands :V
use the name argument in the @command decorator
Yeah I actually added a 'commands' command to show all available commands for the bot.
define that in the decorator of the command and change the function name
@command(name = "commands")
You mean like this right?
@client.command(name='commands')
async def commands(ctx):
yeah change the function name
I was just using
@client.command()
async def commands(ctx):
So this cause the issue with the error handling?
yeah
Is it recommended to use if isinstance(error, commands.MemberNotFound): anyway?
I mean instead of if isinstance(error, discord.ext.commands.errors.MemberNotFound):
yeah ofc
It's the same thing just easier to read
Hey, I've got a question
I programmed a Bot and a former friend of mine invited the bot
Since I don't want this bot to be on his server, I want it to leave the server
how can I do that?
discord.ext.commands is not usable without explicitly importing, so pretty much not
!d discord.Guild.leave
await leave()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Leaves the guild.
Note
You cannot leave the guild that you own, you must delete it instead via [`delete()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.delete "discord.Guild.delete").
I am trying to send an embedded message every day at specific time. This is the code I am using.
@client.event
async def on_ready():
channel = client.get_channel(931582403015737457)
async def job():
content = get_content()
word=get_word(content[0].text)
embed = discord.Embed(title=f"{content[0].text}", description=f"-> {content[1].text}\n-> {content[2].text}\n", color=0x00ff00)
embed.add_field(name="", value=f"[Google it!](https://www.google.com/search?q={word})")
await channel.send(embed=embed)
schedule.every().day.at("22:20").do(job)
while True:
schedule.run_pending()
time.sleep(1)```
I am getting the following warning at the specified time:
`RuntimeWarning: coroutine 'job' was never awaited
self._run_job(job)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback`
Except this nothing happens.
How can I fix this? Or what other way can I use except schedule module?
Why not use tasks?
!d discord.ext.tasks.Loop
class discord.ext.tasks.Loop```
A background task helper that abstracts the loop and reconnection logic for you.
The main interface to create this is through [`loop()`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.loop "discord.ext.tasks.loop").
I didn't know about that. Thanks I'll look into it.
Hey! Is it possible to send an image thats created by the script to a discord webhook without downloading it? My script makes matplotlib graphs, and i want to send them to a webhook, without downloading them..
Wdym "downloading"?
Use bytesIO
He means he doesn't want it to save locally on his pc
Issue? This is normal behavior
Ah, of course
plot_io = io.BytesIO()
plot.savefig(plot_io, format="png")
plot_io.seek(0)
# you can use discord.File(plot_io) now```
this is good, but it sends it as an image and not as a file
Specify filename kwarg with extension
Like discord.File(plot_io, filename="plot.png")
yea ik i just wanted someone to help me code something like that
i know thats a tree command
but i have a hard time with the rest of the coding
thanks โค๏ธ
you are welcome
is there maybe a way to send this inside an embed? without downloading it. Asking cuz its a file
Don't you got the URL of the image?
no, its created realtime.
could someone help me code something like this im very new
What have you got so far?
i know how to start the command off but everything else is a blur
@client.tree.command
you want it for the developer badge?
If you want to have this embedded you need an URL.
so that is basically like you ping a user and it will send a specific message like โyouโve been offeredโ
? no its for a project
@cloud dawn
Have you tried anything?
im very new to coding this type of language im currently a lua developer but im confused on everything but starting the command
so no
Do you have one command working?
Could you show that command?
yep
@manic knoll this is a pretty nice and beginner friendly tutorial: https://www.youtube.com/watch?v=jh1CtQW4DTo
Hey!
Thanks for watching today's video, I hope you enjoyed and joined my discorddd... also thanks for 2.63K subscribers!!
LINKS -
Join my Discord - https://discord.gg/twHW4UUJGq
Learn Bot Dev - https://youtu.be/e9SYmj1QF8I
Learn Nextcord Slash Commands - https://www.youtube.com/watch?v=yCZMhkSQjCE
Thanks if you read all ...
recommend watching this
I assume this works?
yep
You can convert the image to bas64 then use url encoding.
have you got maybe an example for that please?
Could you share the code?
yep
async def offer(interaction: discord.Interaction):
bot_latency = round(client.latency * 1000)
await interaction.response.send_message(f"Pong! {bot_latency} ms.")```
!local-image
!local-file
Thanks to discord.py, sending local files as embed images is simple. You have to create an instance of discord.File class:
# When you know the file exact path, you can pass it.
file = discord.File("/this/is/path/to/my/file.png", filename="file.png")
# When you have the file-like object, then you can pass this instead path.
with open("/this/is/path/to/my/file.png", "rb") as f:
file = discord.File(f)
When using the file-like object, you have to open it in rb ('read binary') mode. Also, in this case, passing filename to it is not necessary.
Please note that filename must not contain underscores. This is a Discord limitation.
discord.Embed instances have a set_image method which can be used to set an attachment as an image:
embed = discord.Embed()
# Set other fields
embed.set_image(url="attachment://file.png") # Filename here must be exactly same as attachment filename.
After this, you can send an embed with an attachment to Discord:
await channel.send(file=file, embed=embed)
This example uses discord.TextChannel for sending, but any instance of discord.abc.Messageable can be used for sending.
read the part below, you can just use attachment://file.png

doesn't need a location or a seperate url, "attachment://" refers to the current messages' files
That could work since File also accepts IO bytes.
yeah any bufferable io
Well if you use this you only need to change the response and command name/ desc.
Learned something new :)
well
async def offer(interaction: discord.Interaction):
await interaction.response.send_message(f"")```
so far im coding
the tree part
but how do i code something like where im able to ping a user
You don't need to provide a "/" in the name.
oh ok
in hikari you could just do ๐คบhikari.Embed().set_image(hikari.Bytes(your bytes, "file.png"))
Typehint the user ```py
async def offer(interaction: discord.Interaction, member: discord.Member):
If no value is set then you are required to yes.
If a value is set then that is the default value.
with open(plot_io) as f:
TypeError: expected str, bytes or os.PathLike object, not BytesIO```
mhmhmh
ignore the above part
you need the part below
you already have the file prepared, now create an embed and use embed.set_image(url="attachments://plot.png")
note that you'll have to send both the embed and file
so what line would that go in this script
But, no. I want the image to be part of an embed
Well on the middle since I copied your code part and added that argument.
Then we got the member, now we need to add it to the string using an f-string.
and i dont know the name of the image
plot_io = io.BytesIO()
plt.savefig(plot_io, format="png")
plot_io.seek(0)
embed = discord.Embed()
# Set other fields
embed.set_image(url="attachments://plot.png")
oh so i would basically have to remove "async def offer interaction" etc and replace it with the new one?
Yes.
^^^
i kinda need help with f strings
how so
!f-strings
Creating a Python string with your variables using the + operator can be difficult to write and read. F-strings (format-strings) make it easy to insert values into a string. If you put an f in front of the first quote, you can then put Python expressions between curly braces in the string.
>>> snake = "pythons"
>>> number = 21
>>> f"There are {number * 2} {snake} on the plane."
"There are 42 pythons on the plane."
Note that even when you include an expression that isn't a string, like number * 2, Python will convert it to a string for you.
@client.tree.command(name="offer", description="Where Head Coaches offer players")
async def offer(interaction: discord.Interaction, member: discord.Member) -> None:
await interaction.response.send_message(f"{member.mention} has been offered by {interaction.user.mention}!")
``` Here is it with the right f-string.
f-string aka format- string
Yes, also reduce the caps.
did you even try what i told you to do?
that will do the same
thanks man no where without you or panda
should i test it?
Of course.
but from what do i know the filename
Everything needs proper testing.
i dont define it anywhere here
plot_io = io.BytesIO()
plt.savefig(plot_io, format="png")
plot_io.seek(0)
embed = discord.Embed()
# Set other fields
embed.set_image(url="attachments://plot.png")
You can offer yourself lol.
you created the discord.File object earlier, and removed that line of code lol.
it had the file name saved as plot.png
Let's do it.
this ? file=discord.File(plot_io, filename="plt.png"
So if statements. Familiar?
yes
now send both the embed and the file
filename="plot.png"*
another thing is we need to first make sure you have a role named "head coach" if not then you wont be able to offer anyone it should give you a error saying "you are not a head coach"
Let's add this first.
yep sounds so familar from lua
In embeds.0.image.url: Scheme "attachments" is not supported. Scheme must be one of ('http', 'https').
ok so how would we start this one this is also a if statement right
attachment, not attachments
ok so how would i start the if statement
it works
finally, thank you very much @slate swan ๐ฅฐ
no problem
ok added it
if condition:
...
added
@client.tree.command(name="offer", description="Where Head Coaches offer players")
async def offer(interaction: discord.Interaction, member: discord.Member) -> None:
msg = f"{member.mention} has been offered by {interaction.user.mention}!"
if interaction.user.id == member.id:
msg = f"Hey {member.mention}! You cannot offer yourself."
await interaction.response.send_message(msg)
Can you also offer bots?
nah
Discord identifies channels, users, messages and roles using a role ID. Role IDs can be used in conjunction with bots or embeds to directly point to the appropriate section in Discord. Including ID information when embedded can greatly improve the experience of navigating through your Discord server.
โถ Website: https://slurptech.com
โถ Discord S...
after enabling what else
That's it
Then right click role id
And tap copy id
discord on phone 
Iphone ๐ถ
reload discord.
forgib
ok got it
assuming genders in 2023
bruh
It*
Correct
Showing what?
Right click on my user and it says copy id correct?
yep
Then it's working
ik
I'll provide the end code an explain it..
Hardest edit ngl
@client.tree.command(name="offer", description="Where Head Coaches offer players")
async def offer(interaction: discord.Interaction, member: discord.Member) -> None:
msg = f"{member.mention} has been offered by {interaction.user.mention}!"
if 807415650778742785 in [role.id for role in member.roles]:
msg = f"Sorry, but you don't have the head coach role to perform this command."
elif member.bot:
msg = f"You cannot offer bots since they are sentient beings, thus are immortal."
elif interaction.user.id == member.id:
msg = f"Hey {member.mention}! You cannot offer yourself."
await interaction.response.send_message(msg)
Big ****** for a male.
What's goin on up here ๐คจ
?
@manic knoll, so here we do an if statement with an elif. I used an elif since if multiple are true it will only grab the first one it encounters. If they don't have access it occurs first, then check for if it's a bot then if the user mentioned hiself.
๐
okay
State that 80741565077874278 is the role id.
N-nothing..
didnt work sadly
Did you replace the right id?
yea
async def offer(interaction: discord.Interaction, member: discord.Member) -> None:
msg = f"{member.mention} has been offered by {interaction.user.mention}!"
if 1062450539595567275 in [role.id for role in member.roles]:
msg = f"Sorry, but you don't have the head coach role to perform this command."
elif member.bot:
msg = f"You cannot offer bots since they are sentient beings, thus are immortal."
elif interaction.user.id == member.id:
msg = f"Hey {member.mention}! You cannot offer yourself."
await interaction.response.send_message(msg)```
nope
^^^
What's the issue?
Doesn't work, @manic knoll right?
No?
"Doesn't work" doesn't really help :/
What isn't working? Is the command not appearing? Have you synced? Is the command not sending the appropriate respond?
@cloud dawn
You're supposed to answer that silly lol
๐
half of the command is working like the offer part
but
i dont have the head coach role which is the part that isnt working
@fading marlin
What is the reponse when you don't have the head coach role?
Should it not be:
if 1062450539595567275 not in [role.id for role in member.roles]:
# . . .
Oh yeah
(Not my code but I'm guessing 1062450539595567275 is the head coach role ID)
yep
@client.tree.command(name="offer", description="Where Head Coaches offer players")
async def offer(interaction: discord.Interaction, member: discord.Member) -> None:
msg = f"{member.mention} has been offered by {interaction.user.mention}!"
if not member.get_role(1062450539595567275):
msg = f"Sorry, but you don't have the head coach role to perform this command."
elif member.bot:
msg = f"You cannot offer bots since they are sentient beings, thus are immortal."
elif interaction.user.id == member.id:
msg = f"Hey {member.mention}! You cannot offer yourself."
await interaction.response.send_message(msg)
fwiw, Member.get_role exists and does what you're doing in the first if
?
I'm just nitpicking lmao. You can probably shorten the first statement with if not member.get_role(...):
How do I acknowledge an interaction?
now
we make a embed
wait
wait yes we make a embed that sends to the person we offered dms
@cloud dawn
use the on_interaction event
I use await interaction.response.defer()
!d discord.InteractionResponse.is_done
is_done()```
[`bool`](https://docs.python.org/3/library/functions.html#bool "(in Python v3.11)"): Indicates whether an interaction response has been done before.
An interaction can only be responded to once.
okay now im uncertain about the question
You still have to send a response afterwards though. I'm talking in the context of buttons and modals. I'm pretty sure you don't have to respond with anything, you can just acknowledge (god that's a hard word to type) it
@cloud dawn
No documentation found for the requested symbol.
Hmm perhaps if I edit_message without doing anything?
ยฏ_(ใ)_/ยฏ
!d discord.InteractionResponse lmao
class discord.InteractionResponse```
Represents a Discord interaction response.
This type can be accessed through [`Interaction.response`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction.response "discord.Interaction.response").
New in version 2.0.
You went from 3 to 8 real quick lol
Ya, that.
Embeds are part of the message you can just pass them.
ok so im just gonna make a embed real quick
I'm making a modal with a single text input field. In the text input you should input something that you want to write to a shell's stdin. What would be a proper label for the text input?
conf_embed.add_field(name="Offered:", value=f"{member.mention} has been kicked from this server by {ctx.author.mention}.", inline=False)
await ctx.send(embed=conf_embed)```
@cloud dawn
welp
holdon
wait
actually how would a put a embed into this @cloud dawn
here ya go, I'll just give you what I'm using.
class TestInput(discord.ui.Modal, title="Quiz"):
Guess = discord.ui.TextInput(label="What is your guess?", placeholder="????", style=discord.TextStyle.short,
required=True, max_length=20)
async def on_submit(self, interaction: discord.Interaction,):
await interaction.response.defer()
pardon me but, what
That a modal with a single text input.
ty but that's not really what I need
What would be a proper label for the text input?
What's the text input for?
you write stuff that'll be forwarded to a shell/bash process' stdin
label="you write stuff that'll be forwarded to a shell/bash process' stdin"
Label is just the text that shows up right above the text input
yeah, ik, but I need something more simple/short
for instance the modal's title is named "Write to stdin"
Ah, conveyance problems.
What kind of people are going to be using this, normal users or people that know what they are doing?
hopefully people that know what they're doing
Then get technical
I just need a simple label that I can use ๐ญ
make a message command
as in wait_for?
y modal ๐
no
easier
just a sec I'll link u to docs
oh no
what i am telling is even easier
hmm, perhaps, but then again I don't think you know the entire context
ik in disnake in dpy iirc it was contextmenu
why not?
you can only have up to 5 (last time I checked), it's for an extension that I'm working on, and you have to have a shell session active to be able to write
plus the Modal really isn't that complicated
class StdinManager(discord.ui.Modal):
stdin: discord.ui.TextInput = discord.ui.TextInput(label="To stdin:")
def __init__(self, process: Process, /):
super().__init__(title="Write to the process' stdin")
self.subprocess = process.process
async def on_submit(self, interaction: discord.Interaction, /) -> None:
self.subprocess.stdin.write(f"{self.stdin.value}\n")
await interaction_response(...) # TODO: do
sure but still dont see the reason not to use a message command just having 5 is not a problem unless u have other plans for it and for the shell session its easy to write a class or function and have it return the output made one eval command similar way before
while I'm at it, does anyone know what args I should pass to TextInput[...]? is it the modal or something else?
oh you're in the dpy server
I'm trying to add some stdin writing stuff to this <#957063746918957056 message>
thats nice
idk, adding a context menu will probably only make it a lot more complicated
meanwhile I can just add a button next to the kill thingy and send the modal there
it's probably more friendly in terms of UX imo
the view
typehinting right?
yup, ty :D
discord/ui/text_input.py line 50
V = TypeVar('V', bound='View', covariant=True)```
yeah, I just found it weird since text inputs won't always have views?
can anyone help me code this to put a embed inside of it
@client.tree.command(name="offer", description="Where Head Coaches offer players")
async def offer(interaction: discord.Interaction, member: discord.Member) -> None:
msg = f"{member.mention} has been offered by {interaction.user.mention}!"
if not member.get_role(1062450539595567275):
msg = f"Sorry, but you don't have the head coach role to perform this command."
elif member.bot:
msg = f"You cannot offer bots since they are sentient beings, thus are immortal."
elif interaction.user.id == member.id:
msg = f"Hey {member.mention}! You cannot offer yourself."
await interaction.response.send_message(msg)
@fading marlin
you can use the discord.Embed class to create an embed, and then use the add_field method to add fields to the embed.
@shrewd apex it sitll does:
so like where at in the code tho
!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.
unknown interaction error
can anyone let me know why
could be because you're trying to perform an interaction on a message that doesn't exist anymore
hence the "unknown message" error
how does that happen tho
no msg is being deleted
can't tell tbh, I don't use v2 stuff :/
how would i add a description for this member.mention?
so i want a slash command to take a list of numbers
is there any way for this to be possible?
probably an option you can add in the argument of your command
how would i do that
examples/app_commands/basic.py line 62
@app_commands.describe(text_to_send='Text to send in the current channel')```
getting this unknown interaction error when using interaction.response.defer but not sure why
Code:
class Select(discord.ui.Select):
def __init__(self, session, name, user):
self.session = session
self.name = name
self.user = user
options=[
discord.SelectOption(label="Overall"),
discord.SelectOption(label="Solos"),
discord.SelectOption(label="Doubles"),
discord.SelectOption(label="Threes"),
discord.SelectOption(label="Fours")
]
super().__init__(placeholder="Select a mode",max_values=1,min_values=1,options=options)
async def callback(self, interaction: discord.Interaction):
await interaction.response.defer() # <-------------------------------------------------------- HERE
mode = self.values[0].lower()
refined = self.name.replace('_', r'\_')
message = await interaction.original_response()
if not interaction.user.id == self.user:
await interaction.followup.send(content=f"{refined}'s {mode} session:", file=discord.File(f'{os.getcwd()}/database/{self.name}.png'),ephemeral=True)
else:
await interaction.edit_original_response(content=f"{refined}'s {mode} session:", attachments=[discord.File(f'{os.getcwd()}/database/activerenders/{message.id}/{mode}.png')])
class SelectView(discord.ui.View):
def __init__(self, session, name, user, *, timeout = 300):
super().__init__(timeout=timeout)
self.add_item(Select(session, name, user))
async def on_timeout(self) -> None:
self.clear_items()
await self.message.edit(view=self)
Error:
Traceback (most recent call last):
File "C:\Users\Lenovo User\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ui\view.py", line 425, in _scheduled_task
await item.callback(interaction)
File "c:\Users\Lenovo User\Desktop\LifeAsPy\Hypixel Api\SessionStats\ui.py", line 41, in callback
await interaction.response.defer()
File "C:\Users\Lenovo User\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\interactions.py", line 636, in defer
await adapter.create_interaction_response(
File "C:\Users\Lenovo User\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\webhook\async_.py", line 218, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction```
I've read somewhere that this is because between your callback and initial select is longer than 3 seconds, is this correct?
well i used await interaction.response.defer() so it shouldnt have that problem but that seems to be the problem
can't tell, sorry man
how can i call a function infinitely in a command?
do you want an answer other than a while True loop?
well i have a function, in there is a while x, which x will be true, but when it is true its only executing once and not actually looping
updating an embed
hmm sounds more like a duty for tasks than a while loop
well its a music thing, so while its playing, update current song
you should update it each time a new song is played then
cant grasp how to go about getting the next song in a loop for a specific message, am i meant to use tasks to get a message and modify it?
well you have a queue right? maybe you can dispatch an event once an item from the queue is removed (assuming that's how it works)
yeah i can see that but are you saying with tasks? because right now im trying to get this to work with a just nowplaying command,
run cmd, message is sent with current song, update it when next starts
so im stuck on how to execute something to start essentially checking if that happens, which is why i was using a loop prior
hmm, that makes stuff a bit more complicated
if you want an easy way, just don't update the message. Let users execute the now playing command whenever they want to know what's currently playing
haha
uhh i mean
theres nothing solid right now, its kind of all over the place with testing
its basically just
run cmd, send the now playing, then i was attempting a loop to edit the message with new info every 3 seconds for testing
do you at least have some sort of play command that adds the song to a queue?
yes
ok, I guess we can start from there
there is a queue, and i can check when a new song is played
its just a looping problem right now, as when i have a while True within a cmd its just running through once and quitting, even if calling it as a function
well then you can do stuff when a new song is played, correct?
but how am i to call that, either in a command, or when a song is added to queue ( which is still a command )
because it would either need to be called each song, or start once a command is sent, which in my mind are both loops anyway
can you send the code for your command that adds a new song?
its just creating a queue bound to server id, with track info which i can globally use, nothing special
yeah but like, what type of queue? is it a custom class? is it a datatype?
its just through lavalink, its not custom or anything
it would be helpful to see the code, otherwise I'm just gonna be guessing stuff
How would i count the amount of times a member was mentioned?
in a single message?
In a single message?
jinx
lol
yikes, no good
That's gonna take a while
lmme be more specific holdon
Please
so whenever someone runs a slash command itll @ them and then i want it to add that to a running counter, so the goal is the user runs the slash command and the bot says "this person has been mentioned x amount of times now!"
or something like that
is it temporary? is it guild-specific?
you could probably use a dictionary and an on_message
would it not work using slash commands? ```py
@app_commands.describe(vote='Your vote')
async def vot(interaction: discord.Interaction, vote: Literal['Duwap', 'Astro']):
astroID = '@eager hill'
if vote == "Astro":
# await interaction.response.send_message()
await interaction.response.send_message(f'You voted {astroID}')
votes = len(discord.Member.mention)
await interaction.response.send_message(f'{astroID} has {votes} votes')
something like this?
Sure, but you can't respond to an interaction twice
alright so lemme remove the astro has votes
TypeError: object of type 'property' has no len(). Is there another way to count it without using len? or am i just being dumb and i can use len
discord.Member.mention is a property of an instance of the class discord.Member. When instantiated, Member.mention returns the formatted way to mention a user (e.g. <@531961974972481536>), not the amount of times the user has been mentioned
ohhh
so it doesnt return the amount of times the user has been mention but how could i get the amount a user has been mentioned?
on_message
so maybe if i do ifmessage.content.startswith("@"): then ?
how would i count that
watcha trying to do @eager hill
@blazing condor
!d discord.Message.mentions you could check this for mentions
A list of Member that were mentioned. If the message is in a private message then the list will be of User instead. For messages that are not of type MessageType.default, this array can be used to aid in system messages. For more information, see system_content.
Warning
The order of the mentions list is not in any particular order so you should not rely on it. This is a Discord limitation, not one with the library.
how do I remove a user from timeout?
!d discord.Member.timeout - set until to None
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 "(in Python v3.11)").
You must have [`moderate_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.moderate_members "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 "discord.Member.edit").
Using intents in discord.py
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.
async def clear_error(ctx, error):
if isinstance(error, commands.MissingRequiredArgument):```
I'm doing this as a command handler instead of doing `commands.MissingRequiredArgument` is there a way I can see what argument is missing so I can say something specific based on the argument that's missing
Just use commands.MissingRequiredArgument, why do you want to change it
I want to see the specific argument missing that's what I'm asking
!d discord.ext.commands.MissingRequiredArgument.param
The argument that is missing.
appreciate it
if I'm checking would I make the arg a string like this
if commands.MissingRequiredArgument.param == "arg":
pass```
no, error.param
I switch t hat with commands.MissingRequiredArguments.param or "arg"
commands.....
it should look like this py if error.param.name == "arg": ...
ahh
do I change anything if I have * before a variable so like *text
nope
ai
:incoming_envelope: :ok_hand: applied mute to @onyx rapids until <t:1673423042:f> (10 minutes) (reason: newlines rule: sent 119 newlines in 10s).
The <@&831776746206265384> have been alerted for review.
Happens
!unmute 433691548543090698
:incoming_envelope: :ok_hand: pardoned infraction mute for @onyx rapids.
!paste sorry about that, please use this ๐๐ป
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.
https://paste.pythondiscord.com/wesawaxaqa keep getting this error, anyone know why?
what does discord.ext.commands.errors.CommandInvokeError: Command raised an exception: UnboundLocalError: local variable 'channel' referenced before assignment mean?
It means exactly what it says
and how do i fix it?
!e
def fn(b: bool):
if b:
var = 1
print(var)
fn(False)
@naive briar :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 7, in <module>
003 | File "<string>", line 5, in fn
004 | UnboundLocalError: cannot access local variable 'var' where it is not associated with a value
If b isn't true, the variable var wouldn't exist
This isn't even out of basic Python knowledge
https://paste.pythondiscord.com/wesawaxaqa keep getting this error, anyone know why?
Just read it
I mean how tf is it possible not to understand that, it even tells you what you need to do to fix it
Some people just don't want to read
That code looks like it was generated by chatgpt
u dont
Bro is five years ahead of us
Why would GPT generate code that doesn't work? discord.Client never had the command decorator
It does, it just has skill issues
Well, function (or partial?)
nah it got skill issues serious ones when it has never seen the real stuff
๐
messages that are how old, cannot be deleted by channel.purge?
actually lemme check the docs
14 days
thanks
Hey! I have been facing a new issue with my bots recently, it keeps giving me the error that member or user object has no attribute avatar_url, although it did before and used to work just fine, any solutions?
Changed in 2
!d discord.User.avatar
property avatar```
Returns an [`Asset`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Asset "discord.Asset") for the avatar the user has.
If the user does not have a traditional avatar, `None` is returned. If you want the avatar that a user has displayed, consider [`display_avatar`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.display_avatar "discord.User.display_avatar").
it looks like you havent given the bot the proper intents...
thank you 
hello i'd like to do a Vinted Bot but first i need an API Key
i dont find where to get it
they dont have website
this is not the right channel anyways 
This is for Discord bots.
i do the bot as a discord bot
well ok, how does your issue have anything to do with this channel
your question does not belong here 
and where can i ask so
This is for Discord, why are you expecting us to know anything about vinted?
https://www.vinted.com/forum looks like a good place to start.
LMAO, https://www.vinted.fr/forum-rules
Hope you know French.
I do but it just hurts my brain 
????
why don't they allow everyone to access the website? ๐
i am french ๐
imagine
YA, imagine still following that stupid "French is bad" meme in 2023.
when did that become a meme 
It's not just a meme if it's real
๐
Something something anime profile picture.
this channel got a lot more hostile ever since zippy started talking
No worry, I'll solve that problem for all of us.
okaay
he left lmao
Give a dozen minutes and a piece of paper with a pen it's pretty easy to figure out nearly all of that token. You better reset it. Is it really that hard to change the string to "TEST" before taking a screenshot?
i dont think anyone will put in that much effort lmao
It's just double click, ctrl-x and TEST
from discord.ext
yes i fixed sorry but new problem x)
share it
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.
async with x Asynchronously initialises the bot and automatically cleans up.
New in version 2.0.
discord.Bot is something you'd see in pycord iirc
hey peoples
i created a script which fetches memes from reddit and makes video compilation
i want to deploy it online so the program works online forever
how can i do so
...
Have you got internet
yes
there is no method get_db_data
the method is in the cog
u are using self instance of the view
How can I make it find users that are not in the server but existing in the database?
# Modlogs command
@client.command(name = 'modlogs')
async def modlogs(ctx, member: discord.Member = None):```
https://paste.pythondiscord.com/emuhatogaf Why can my bot only do !hello and how do I fix it?
Should I better use 'async def modlogs(ctx, member: commands.MemberConverter = None):'?
you have an on_message that's eating all of your commands
@client.event
async def on_message(message):
if message.content.startswith('!hello'):
await message.channel.send('Hello!')
also, commands take commands.Context as their first argument, not discord.Message
You can use discord.User instead
Do you know how I can fix it?
You can use a listener like you were doing 2 functions above, or process_commands in the event
But this will not work with the error handling?
@modlogs.error
async def modlogs_error(ctx, error):
if isinstance(error, discord.ext.commands.errors.MemberNotFound):
await ctx.send(f"I could not find the user {error.argument}.")```
Try it and see
It doesn't. When I'm typing a user that doesn't exist it gives me no errors, nothing.
It raises UserNotFound instead. Your other errors are probably being eaten somewhere
so basically replace client.command with client.listen?
No, not your commands, your event
ohh
https://paste.pythondiscord.com/juxivuyadi
I did this, thats wrong, isnt it?
Looks good to me ๐คท
Hey guys I have a problem. I've been coding some slash commands recently and finished one, although I am trying to create a new slash commands but everytime I restart the bot the second command do not show at all. Only the first one I've made show but not the second one
@client.tree.command(name="hello", description="Create a new ")
@app_commands.checks.has_role(ADMIN_ROLE)
async def releases(itr: discord.Interaction, releasee: str, namee: str):
print(releasee)
print(namee)
The command is really basic as its the second one and im simply trying to make it appear
Yeah, I had to change it to 'if isinstance(error, discord.ext.commands.errors.UserNotFound):' instead of 'if isinstance(error, discord.ext.commands.errors.MemberNotFound):'
Have you synced?
bruh I think I know why and thanks that's probably why hahah
You don't have any command called echo in the snippet you sent ๐ค
Also, you have an event and a command with the same function name
Commands don't take a message object, they take in a Context object. They don't take in the client either
@fading marlin Thank you hahah, forgot to sync man โค๏ธ
No problem
I still tried just in case
but what line do I need to change to what?
^
Thanks @fading marlin
Sure thing
Hi, How do I make my bot add multiple reaction at the same time?
Might be because english isnt my first language, but idk how the solve it
await message.add_reaction()
await message.add_reaction()
it's reaction_add innit
!d discord.Message.add_reaction
await add_reaction(emoji, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Adds a reaction to the message.
The emoji may be a unicode emoji or a custom guild [`Emoji`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Emoji "discord.Emoji").
You must have [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") to do this. If nobody else has reacted to the message using this emoji, [`add_reactions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.add_reactions "discord.Permissions.add_reactions") is required.
Changed in version 2.0: `emoji` parameter is now positional-only.
Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.11)") instead of `InvalidArgument`.
it's add_reaction
that works but can I make it at the same time?
no, it takes one
alternative is using buttons... they appear simultaneously
Who can help ? My bot does not respond to messages and does not give out the participant's level for them and does not write about it in the chat. Just please don't throw me a link to the documentation for this module
!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.
read this and you'll have your fix
you can't read docs apparently
You just want the docs read out FOR you

