#discord-bots
1 messages · Page 171 of 1
await start_a_tour()
await message.channel.send(f"{sleep_amount} saniye içerisinde geldim.")
except:
await message.channel.send(f"Oda boş olduğundan ya da hedef oda da olmadığından dolayı bot gelmiyor. Hedefler aşşağıda")
for victim_user_id, percentage in targeted_victims:
idlist = await bot.fetch_user(victim_user_id)
chance = (percentage * 100)
await message.channel.send(f"{idlist.display_name} ve %{chance:.0f}")```
What
okay i will write cleaner
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
Right now, output is like
Target#xxxx and chance was %xx
Target2#xxxx and chance was %xy
i want like
Target2#xxxx and chance was %xy```
Output where
except one is output
Also add py after the first triple backticks to highlight the syntax
Then just put it in the code block 🤷
Join them together
I
I hate formatting
!e
ml = []
for a in (0, 1, 2):
ml.append(f"Int({a})")
print("{}\n{}\n{}".format("'''", "\n".join(ml), "'''"))
@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | '''
002 | Int(0)
003 | Int(1)
004 | Int(2)
005 | '''
str.join(iterable)```
Return a string which is the concatenation of the strings in *iterable*. A [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError") will be raised if there are any non-string values in *iterable*, including [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes "bytes") objects. The separator between elements is the string providing this method.
could someone please help me with #1060137860260438046
aiosqlite > asqlite
py except: await message.channel.send(f"Oda boş olduğundan ya da hedef oda da olmadığından dolayı bot gelmiyor. Hedefler aşşağıda") for victim_user_id, percentage in targeted_victims: idlist = await bot.fetch_user(victim_user_id) list = "" list += (f"{idlist.display_name} ve %{chance:.0f}") chance = (percentage * 100) await message.channel.send(f"3xbacktick{list}3xbacktick")
UnboundLocalError: local variable 'chance' referenced before assignment
3xbacktick = ```
Put py before the backticks to highlight the syntax so it's more readable
Also you're creating new string for every iteration
This variable won't exist in the first iteration
and you just put it so your message doest break?
no, there is no 3xbacktick on code, i wrote it because discord really fucks it up and i dont know how to fix it
ah ok i thought so
this is code
You're still creating new list variable in every iteration
Also don't override built-in functions
swap the chance = ... and list += ... lines

name it something like percent_list or smth
okay, i swapped
and it worked but not exactly
it worked for 1 time, not for loop
it wrote only one loop
Read
oh fuck i didnt see it
output: Dyno ve %50ValoMarket Bot ve %50
okay it works but new line not works
you didnt put a new line
because of course i didnt add it
You're not adding new line
😂
okay, i added ...0f}\n") and seems like it works
Thank you guys @somber imp@naive briar
np 🙃
Hi
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.
still the error
ahh i had intents=Intents
It's prefix command
no slash command ?
ah u are right
its a prefix command
but why its not a slash cpmmand.?
im using pycord
hello
which rdp do yall reecommend
What's rdp
remote desktop protocol
I have a question
Just ask it
Because you made it a prefix command
Can I make a bot in Python?
ofc
i dont see my nc cmd
You didn't register as slash command
what u mean
Are you using pycord
ye
@bot.slash_command(name="nc")
remove @bot.command
and add this
cant send embed in a slash command ?
@slate swan
Switch line 19 and 20
embed=discord.Embed(...
embed.set_author...
@option since when is that a decor?
Pycord
O that…
Traceback (most recent call last):
File "main.py", line 23, in <module>
client.run(tkn)
File "/home/runner/carbon/venv/lib/python3.8/site-packages/discord/client.py", line 828, in run
asyncio.run(runner())
File "/nix/store/2vm88xw7513h9pyjyafw32cps51b0ia1-python3-3.8.12/lib/python3.8/asyncio/runners.py", line 44, in run
return loop.run_until_complete(main)
File "/nix/store/2vm88xw7513h9pyjyafw32cps51b0ia1-python3-3.8.12/lib/python3.8/asyncio/base_events.py", line 616, in run_until_complete
return future.result()
File "/home/runner/carbon/venv/lib/python3.8/site-packages/discord/client.py", line 817, in runner
await self.start(token, reconnect=reconnect)
File "/home/runner/carbon/venv/lib/python3.8/site-packages/discord/client.py", line 746, in start
await self.connect(reconnect=reconnect)
File "/home/runner/carbon/venv/lib/python3.8/site-packages/discord/client.py", line 672, in connect
raise PrivilegedIntentsRequired(exc.shard_id) from None
discord.errors.PrivilegedIntentsRequired: Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.```
how to fix this
Hello, I'm trying to add a timeout/untimeout feature to my Discord.py bot but I can't figure out how to do it. I've tried looking on YouTube but they either don't work or only work with custom commands prefixes when I need slash commands. Can anyone help out please? (Beginner to coding, so dumb it down for me please <3)
Read the error, that's the answer
There's already an built-in timeout slash command
I know but later down the road I might want to have my bot setup an audit log with the moderation commands so I figured it would help if I made a timeout command within my bot
You took more than 3 seconds to respond
Defer the Interaction at the beginning of the callback and send followup instead of response where you want to
i didn't use a callback
thanks it worked
any idea how can i split this embed so it gives me percentage?
yea
do it the same way like how u do this embed?
huh? its not my embed tho
oo
try to get the message first
after that do some message filter
Hi I'm trying to make premium bot commands (for members with the premium role in my server). But its not storing the info in premium_users.json. Using d.py Help needed pls thanks
nope, created it twice
meaning?
u cant get the percentage if u dont get the message yes?
nono its an embed sent by a bot thats not mine
then how do u plan to do it
that's why i came here
use regex.
not like I know how it works
you could achieve the same without regex too
But messy
Hello!
Is it possible to restart the bot within istelf without killing the script? I want to use this feature because I'm running my bot on a Unix server and my problem is when I use a service such as nohup to keep it running, I'm not able to kill it when I pull new changes from GitHub. How would I go about doing this?
Updating the bot without killing the script is done through reloading extensions
I would recommend using docker instead of nohup
That's completely different thing tho
https://www.pythondiscord.com/pages/guides/python-guides/docker-hosting-guide/ consider looking into this @rustic edge
This guide shows how to host a bot with Docker and GitHub Actions on Ubuntu VPS
!e
from re import findall
string = """0000 :emoji: • Lvl. 1 • 50.0%
0001 :emoji: • Lvl. 5 • 49.0%"""
print(findall("[0-9]*\.[0-9]+%", string))
@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.
['50.0%', '49.0%']
Better \d+(?:\.\d+)% imo
uve just spoon fed him
Who
catgal
What else are you gonna do 🤷
Catgal isn't one who needs spoonfeeding
regex pro exenvifix
no, catgal has just spoonfed the other guy
Thanks 😱
let him explore and figure out on his own
Rate link regex https?://[-\w]+\.\w{2,4}(?:/[-\w%&?=#@]+)*
Spoons cycle in nature
!e
import re
pattern = r'\d+\.?\d*%'
string = """0000 :emoji: • Lvl. 1 • 50.0%
0001 :emoji: • Lvl. 5 • 49.0%"""
print(re.findall(pattern, string))
@shrewd apex :white_check_mark: Your 3.11 eval job has completed with return code 0.
['50.0%', '49.0%']
😎
🐁
did someone say meh
I said bobuz
ew
🥶
Ash vs Asher 🥶 battle
who's the real one
none
thought so
Asher has an advantage of being bobux developer
Idk how that's an advantage but anyway
net worth is higher
Ah yes
I'm gonna have a dog like this
nice
u all still have aspirations 😔
Why have a dog when you can be the dog 😳
wtf
crocolate
also !ot
we don't need 2 Ashleys here do we
Discord bots is for everything
^
Like when you say "I am going to get this dog" you actually mean "how can I make a discord bot that can give me a dog based on my calculations"
!dog
» dotenv
» docstring
💀
shut up bot
!pypi exenenv
Dogstring
Almost same
😳
Lol wtf
how does dog relate to docker lmao
how does it make docker simple
I'm mad at this lib for taking the name 'dog' so unnecessarily
By barking
why're you sitting in this unworthy channel
😔 you're too much of a person who "thinks out of the box"
I am spying on infernum
huge server
Dayumn
brah
I haet disney internals 😡🤬😤
# noinspection PyProtectedMember
interaction._state._modal_store.remove_modal(interaction.author.id, interaction.custom_id)```
You were supposed to read manuals
which manual
I don't understand anything from that
how ru publicising the bot?
You mean what
I use exponential growth
None yet
in short how to get the bot to join more servers
You can join development server we share news there but you will be able to spend it
Exponential growth
man i was hopin we could convert it to robux :(
People see bot, they want to add it to their server
The more servers the more people
And the bigger servers
We can actually count how many users bobux serves rn
140k
Not that much but something
Lmao
Um actually 1000 1000 1011 1000 00
the hell
no wonder
💀
Nice
Lmao
I think u all will want to move this to an ot
Um actually, according to my calculations, we are currently talking about a discord bot
🤓
Not discord bot development
Still not the convo about discord bot development
Ok
We could talk about how bobux bot could be made better
Guys what's best implementation for settings
Smh
We got development plan for 4 versions ahead so too early
I thought of selectmenu
💀 Can I contribute
Wait, bobux is your bot?
Yeah I am project manager and there are 4 other devs in team
legendary team
It's closed source tho
Am I the only one who thought it was some random bot giving free currency lmao
'cause you're there 💀
Idk
cringe

exenifix carries us
lmao
But good work, having 140k users, Evenifix!
We will probably invite someone else if one of current devs leaves or when we will be developing site
js
For my bot, its hardly 9.2k 😭
For my bot it’s 1
Eh, but my bot is hardly used lmao
💀 tf js is so uwu
People escaped the lockdown 😔
pokelore?
🔥
yeah
sad
Meh, its a repeated idea
Moreover, its dev lost interest so u cannot blame the users lmao
legit burn bro go apply ice
.......?
...
Lockdown in hunter's basement?
I don't have one
I got a first floor tho
you just said
meh
ewu
yooooo guys
What's mean of ```py
'NoneType' object has no attribute 'id
That means your object is None
@paper sluice :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | AttributeError: 'NoneType' object has no attribute 'id'
your get method is returning None, meaning the ID is wrong or u r passing a string instead of int
aha
what is this code problem? ( about your suggestion?)
https://paste.pythondiscord.com/elukaxohoy
@maiden fable @paper sluice
Can u show the whole traceback?
sure!
Traceback (most recent call last):
File "C:\Python\Python311\Lib\site-packages\discord\app_commands\tree.py", line 1242, in _call
await command._invoke_with_namespace(interaction, namespace)
File "C:\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 887, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 880, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'createyoutuberchannel' raised an exception: AttributeError: 'NoneType' object has no attribute 'id'
Is that it?
weird
Hey also
Use interaction.guild.get_role
You prolly can, but the question is suited for #python-discussion
what is get??
discord.utils.get
oh 👀
wym
Tbh the only thing u can do is print all the objects and see if something is returning/printing None
and my problem is when i use youtuber_id as arg for using it in slash command , it won't find that
good idea✌️
u
whats wrong with using a laptop 🗿
not everyone has access to that I guess, I've seen way to many people even code on mobile, that's dedication
Sell phone buy laptop
bro has ipad no laptop am i supposed to believe that? 🗿
Well if he's addicted to apple, laptop can only mean "mac book pro max 69 ultra"
And it def costs more than ipad
parents restrictions ig
I've saved up for that model for years
Actually normal laptop is around 700$ ig
give the man a nice chromebook
yeah about that
Um mom I need RTX 4090 for my studies
u can get a decent model as well
but how will i get the vals of the embed 🥹
POV they bought you the 4090 but no other hardware
gaming on a graphic cards
sleep sleep
gaming in real life
Heh I would just sell it and get whole PC but with RTX 3070 prob
Mom wouldn't probably see the difference between 4090 and 3070
what isn't a list
idtts your question's even related to this channel
.split() returns a list, not replaces the string with list
!e py s = "stuff, vodka, free bobux" words = s.split(", ") print(words)
@vale wing :white_check_mark: Your 3.11 eval job has completed with return code 0.
['stuff', 'vodka', 'free bobux']
free bobux you say?
Yus
How is this related to discord bots
i use this in my bot
its just py though lmao
im sorry where should i ask for help?
just ask in #python-discussion seeing as its simple
I use a RandomForestClassifier machine learning model in my code, it's definitely more of discord bot than AI
🤓
use the global keyword, and you should be using botvars for these things
!e
a = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
print(a[0:10:4])
print(a[::4])
@lean palm :white_check_mark: Your 3.10 eval job has completed with return code 0.
001 | [1, 5, 9]
002 | [1, 5, 9, 13, 17]
@client.command()
async def test(msg):
embed=discord.Embed(title='Hello', description='This is a Embed', color=0x1936275)
await msg.channel.send(embed=embed)```
Why it is not sensing me response prefix is !
I writing
!test it not giving me response
It's quite complex - are you up for it?
make sure message_content intent is enabled
!d discord.Intents
class discord.Intents(value=0, **kwargs)```
Wraps up a Discord gateway intent flag.
Similar to [`Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions "discord.Permissions"), the properties provided are two way. You can set and retrieve individual bits using the properties as if they were regular bools.
To construct an object you can pass keyword arguments denoting the flags to enable or disable.
This is used to disable certain gateway features that are unnecessary to run your bot. To make use of this, it is passed to the `intents` keyword argument of [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client").
New in version 1.5.
client = commands.Bot(command_prefix ='!', intents=discord.Intents.all())
I would not recommend undertaking an invite system unless you can work at a high level
@slate swan
(And follow imperative instructions)
I was talking to @slate swan sorry
Do you have an on_message event eating up the messages
So on_message is called whenever the bot sees a message being sent, which by default calls await Bot.process_commands(), which basically tells the bot to treat the message as a command. You've overwritten this event but not called the process_commands method.
wdym
Oh and also, the hex digit passed as your embed colour is 7 digits when it must be a 6-digit hex number @jade lodge
Am invite system. Discord doesn't just tell you who a new member was invited by. You need to cache the total invites for each server in memory, and do a differential lookup for each new on member. Update the cache again
Also why bro is coding in the 1800s
@slate swan pydroid 3
Fkin d.py
@client.event
async def on_message(msg):
if msg.content == "!embed":
embed=discord.Embed(title='Hello', description='Hello mannn')
msg.channel.send(embed)```
@slate swan
Im new
it's not related to discord.py but related to python
welp just delete all the spaces that you've in indentation of that function & replace 'em with either space or tab
What is it
!indent
Indentation
Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.
Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.
Example
def foo():
bar = 'baz' # indented one level
if bar == 'baz':
print('ham') # indented two levels
return bar # indented one level
The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.
Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines
More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation
@client.event
async def on_message(msg):
print(colored(msg.channel.id,color="green"),"kanalındaki",colored(msg.author,color="red"),"`in mesajı:\n",colored(msg.content,color="cyan"))
if msg.content == "!embed":
embed=discord.Embed(title='Hello', description='Hello mannn')
await msg.channel.send(embed)```
await msg.channel.send(embed = embed)
you use the embed kwarg to send "one" embed
Now i trying it haha
"haha"
an embed*, the embeds kwarg is for sending embeds
msg.channel.send(embed=embed)
Forgive me okimii
🤨
TypeError: Embed.set_image() takes 1 positional argument but 2 were given```
@sick birch
!d discord.Embed.set_image
set_image(*, url)```
Sets the image for the embed content.
This function returns the class instance to allow for fluent-style chaining.
i can't use it with a file from my pc ?
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ui\view.py", line 425, in _scheduled_task
await item.callback(interaction)
File "C:\Users\user\Desktop\Other\Bots_For_Sell\Hesham hope bot\bot.py", line 37, in join_callback
await clickj.response.defer()
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\interactions.py", line 592, in defer
await adapter.create_interaction_response(
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\webhook\async_.py", line 219, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction```
@primal token can u help ?
hi, i am learning python and the first thing i want to do with it is to create a discord bot. Do you know ways to learn making discord bots? because youtube videos and most courses are not really good code
you're not responding to the interaction fast enough
Maybe not the best idea 😓
Making discord bots in Python is quite difficult and not geared towards beginners.
I would recommend learning intermediate Python at least before getting started with Discord bots.
And you're right, youtube videos and courses aren't really that good here
Use the !resources tag in #bot-commands for some resources to learn Python
okay ty
what should you recommend to learn first?
because it seems really fun to make discord bots to me
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
flow control, scopes, object oriented programming, asyncio basics, and a basic idea about how apis work ( what a request is, ratelimits).
As a bobux bot developer I approve this
can make infinite bobux 4 me ??
Hey guys, does anyone know if there’s any way to actually pull user/member connections through commands? I know that bots aren’t able to access that info. But if you give your application the “connections” parameters in your OAuth2, how can that be utilized?
Hello!
I am trying to make a /payment command where it asks for a amount, type, and user
Code:
https://hastebin.com/uwovufiroz.py
But during the class PayPalButton
When the user clicks the button, I want the button to disable, but what I have doesn't work!
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
What's the function to stop the function from running until voice_clients.play() finishes?
can someone hep me ot says ‘bot’ onject has no attribute ‘slash_command’
What wrapper are you using?
well theres not a function specifcally for that but you can passa function into play() that will be called once the audio finishes. play(..., after=<function>)
@polar wigeon hey you know python right? i need some help
<&
@slate swan
my code should send a webhook when a user changes their avatar, which is does, however their avatar before the change for whatever reason is not displayed.. I noticed this & tested it myself, my avatar before & after both display
Here’s my code:
if before.display_avatar.url != after.display_avatar.url:
e = discord.Embed(colour = 0x2f3136)
e.set_author(name = f"{before.name} changed their avatar!", icon_url = self.bot.user.display_avatar.url)
e.description = "The images will be provided below."
e.set_footer(text = "This event occured:")
e.timestamp = discord.utils.utcnow()
e1 = discord.Embed(colour = 0x2f3136)
e1.set_author(name = f"This is {before.name}'s avatar before:")
e1.set_image(url = before.display_avatar.url)
e2 = discord.Embed(colour = 0x2f3136)
e2.set_author(name = f"This is {before.name}'s avatar after:")
e2.set_image(url = after.display_avatar.url)
await logWeb.send(embeds = [e, e1, e2])
Here’s some attachments:
please ping me if anyone responds :)
because the avatar has been deleted from the discord CDN, so until and unless it's in user's cache, it will not be displayed
how can I get it in my users cache in that case?
^ I’m gonna try fetch the user
your cache, not your bot's cache
and the bot can't interact with it lol
ah
is there really no workaround whatsoever
not that im aware of
works in right instance but not the left been fucking with it for hours
What
the cmd_clan_accept and cmd_clan_create
what about it? I just see some red squiggly lines in async
Is there a way to use checks with slash commands?
Been looking around and haven't found much..
Just need to check if a user has one role out of a few when their running the command, and it won't run if they don't.
And then having a sepreate check under that, which will also allow them to run the command if they have the Admin or Manage Guild perms.
The bot command version would be:
@bot.command(name='yy')
@commands.check_any(commands.is_owner(), is_guild_owner(), commands.has_role("x"), commands.has_role("y"), commands.has_role("x"))
@commands.check_any(commands.has_permissions(administrator=True), commands.has_permissions(manage_guild=True))
async def xx(ctx):
'''Code'''
@pulsar bridge I would probably create a custom check combining both of those requirements
https://discordpy.readthedocs.io/en/stable/interactions/api.html?highlight=check#discord.app_commands.check
!d discord.app_commands.check
@discord.app_commands.check(predicate)```
A decorator that adds a check to an application command.
These checks should be predicates that take in a single parameter taking a [`Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction"). If the check returns a `False`-like value then during invocation a [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CheckFailure "discord.app_commands.CheckFailure") exception is raised and sent to the appropriate error handlers.
These checks can be either a coroutine or not.
Examples
Creating a basic check to see if the command invoker is you...
!d discord.app_commands.checks.has_role
@discord.app_commands.checks.has_role(item, /)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check "discord.app_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.
This check raises one of two special exceptions, [`MissingRole`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.MissingRole "discord.app_commands.MissingRole") if the user is missing a role, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.NoPrivateMessage "discord.app_commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CheckFailure "discord.app_commands.CheckFailure").
New in version 2.0...
There's also this
Time to learn something new 
Thanks again, Robin!
Always so speedy and helpful
how does one setup a command that will make a cache of the data?
i wanna make a role react command for my discord and a friends that will be something like yagpdb
!addrolereact message.id role.id emoji
i mean you could save the old, but youd have to somehow grab it prior to them changing it to have the before
What are you gonna cache exactly
If you're making react roles, you should use a database 🍬
what's the recommended db?
i saw sqlite and peewee as the main ones people have made content and using it as their db.
ty!
and for larger projects...? just curious
Postgres
Just use postgres since it'll be easier later
json wen
no db when
json is not a db
bro
is there an easier way to read the discordpy.readthedocs.io? cause honestly, this is annoying not having a list of all possible events/listeners...etc
Hey @pulsar bridge!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
Ran into this error when trying to start my bot. (Error -> https://paste.pythondiscord.com/ahuqutukef)
I'm using only application commands.
Line 46 is:
load_dotenv();
PERSONAL_GUILD_ID = os.getenv('PERSONAL_GUILD_ID')
PERSONAL_GUILD = discord.Object(id=PERSONAL_GUILD_ID)
class TheClient(discord.Client):
def __init__(self, *, intents: discord.Intents):
super().__init__(intents=intents)
self.tree = app_commands.CommandTree(self)
async def setup_hook(self):
self.tree.copy_global_to(guild=PERSONAL_GUILD)
await self.tree.sync(guild=PERSONAL_GUILD) # <- Line 46
client = TheClient(intents = intents)
Maybe I've invited the client wrong?
I'm used to using a bot, and bot commands, but now I'm using interactions / slash commands.
Is there a different way I should be inviting it?
!else
for-else
In Python it's possible to attach an else clause to a for loop. The code under the else block will be run when the iterable is exhausted (there are no more items to iterate over). Code within the else block will not run if the loop is broken out using break.
Here's an example of its usage:
numbers = [1, 3, 5, 7, 9, 11]
for number in numbers:
if number % 2 == 0:
print(f"Found an even number: {number}")
break
print(f"{number} is odd.")
else:
print("All numbers are odd. How odd.")
Try running this example but with an even number in the list, see how the output changes as you do so.
use #bot-commands , this is for discord bot development not using the server bots
Just sending a message so this is still visible
Show the cmdtas whatevrr funtion
and whatever's around it
just a bit
'''Code'''
await interaction.response.send_message(embed=embed)
@client.tree.command(name='view_command')
@app_commands.checks.has_any_role("Mod", "Moderator", "Discord Staff", 'Community Assistant')
#@app_commands.checks.has_permissions((administrator==True))
@app_commands.describe(
ID='The ID of the command you want to see details of.'
)
async def cmd_dtas(interaction: discord.Interaction, ID: int = None):
proceed = 2
''' Code '''
change the name of the ID parameter to lowercase
Kk
ty!
welcome
so if ur on... discord.on_ready()... you can't put anything in the ()? so then how does it call members, guild info, etc?
With your bot instance
For the love of God, go to #bot-commands
oops i thought it was bot commands lmao
my bad im really sorry
don't use on_ready to do api calls
so it doesn't need the data to run cogs? I should run cogs a different way? this way it does a separate api call?
loading cogs doesn't make api requests
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix='>', intents=intents)
@bot.command()
async def ping(ctx):
await ctx.send('pong')
bot.run('token')
Would this work?
it should work
Make sure to define what token is.
How does one create an on_error event listener for application commands?
Specifically one dealing with the CommandOnCooldown error instance.
This is what I have so far...
@client.event
async def on_application_command_error(error):
if isinstance(error, discord.app_commands.errors.CommandOnCooldown):
time = error.retry_after
time = int(time)
'''Irrelevent Code'''
await error.channel.send(f'{(str(ctx.command)).capitalize()} is still on cooldown for {hours} hours, {minutes} minutes and {seconds} seconds!')
But it ain't triggering.
I've tried it with:
on_command_error on_error on_application_error on_application_command_error
Ideas?
Is this discord.py
Pretty sure Discord does that for you if you don't set the row
Or it has enough space to put there
Indeed.
Hasn’t been implemented yet?
How to add callback to Select menu?
!d discord.app_commands.CommandTree.error
@error(coro)```
A decorator that registers a coroutine as a local error handler.
This must match the signature of the [`on_error()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree.on_error "discord.app_commands.CommandTree.on_error") callback.
The error passed will be derived from [`AppCommandError`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.AppCommandError "discord.app_commands.AppCommandError").
Chocolagator
😔

!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.
Hello
An exception has occurred while executing command delete_verification:
Traceback (most recent call last):
File "/home/container/.local/lib/python3.10/site-packages/discord_slash/client.py", line 1353, in invoke_command
await func.invoke(ctx, **args)
File "/home/container/.local/lib/python3.10/site-packages/discord_slash/model.py", line 210, in invoke
return await self.func(*args, **kwargs)
File "/home/container/nitro.py", line 121, in delete_verification
if database_verif.get_verification(guild, role_id) is not None:
File "/home/container/database_verif.py", line 20, in get_verification
cursor.execute(query, (guild_id, role_id))
sqlite3.InterfaceError: Error binding parameter 0 - probably unsupported type.
@slash.slash(name = "delete_verification", description = "Delete verification and channel")
async def delete_verification(ctx, role_id):
guild_id = ctx.guild.id
guild = ctx.guild
if (not ctx.author.guild_permissions.ban_members):
await ctx.send(f"You are not authorized to use this command {ctx.author.mention}")
return
if database_verif.get_verification(guild, role_id) is not None:
database_verif.remove_verification(guild_id, role_id)
channel = discord.utils.get(guild.text_channels, name="verification")
await channel.delete()
await ctx.send("The verification is removed successfully")
else:
await ctx.send("The verification is not in place")```
def remove_verification(self, guild_id : int, role_id : int):
cursor = self.con.cursor()
query = "DELETE FROM verif WHERE guild_id =? AND role_id =?;"
cursor.execute(query, (guild_id, role_id,))
cursor.close()
self.con.commit()```
you can help me
?
What query did you use to create verif table
I created it by hand
This is SQlite
import os
import sqlite3
class Verification:
def __init__(self, database_name : str):
self.con = sqlite3.connect(f"{os.path.dirname(os.path.abspath(__file__))}/{database_name}")
self.con.row_factory = sqlite3.Row
def add_verification(self, guild_id : int, role_id : int):
cursor = self.con.cursor()
query = "INSERT INTO verif (guild_id, role_id) VALUES (?, ?);"
cursor.execute(query, (guild_id, role_id))
cursor.close()
self.con.commit()
def get_verification(self, guild_id : int, role_id : int):
cursor = self.con.cursor()
query = "SELECT * FROM verif WHERE guild_id =? AND role_id =?;"
cursor.execute(query, (guild_id, role_id))
result = cursor.fetchone()
cursor.close()
return result
def get_role_id(self, guild_id : int):
cursor = self.con.cursor()
query = "SELECT role_id FROM verif WHERE guild_id =?;"
cursor.execute(query, (guild_id,))
result = cursor.fetchone()
cursor.close()
return result[0]
def remove_verification(self, guild_id : int, role_id : int):
cursor = self.con.cursor()
query = "DELETE FROM verif WHERE guild_id =? AND role_id =?;"
cursor.execute(query, (guild_id, role_id,))
cursor.close()
self.con.commit()```
role_id is str in the command?
same as button
async def button_callbacken(interaction):
await interaction.response.send_message("Message")
Can someone help me
I have a button currently sends a message after pressing but i want to change it.
After I press the button must trigger another command (a select menu)
how can i connect them
no is int
Where are you converting it to int?
in the table role_id is INTEGER
And in your query you're passing a str
Also.can you print(type(guild_id)) before making the query?
I can't
why r u opening the file
this kinda defeats the whole point lol
you're not actually using environment variables
How to make the slash command parameter required instead of optional?
Don't set the default value
All arguments by default are required
async def on_guild_join(guild):
test = guild.channel.create_invite()
channels = bot.get_channel(UNESI ID OD TVOG KANALA)
await channels.send(f"{test}")
Ignoring exception in on_guild_join Traceback (most recent call last): File "/home/container/.local/lib/python3.10/site-packages/discord/client.py", line 377, in _run_event await coro(*args, **kwargs) File "/home/container/app.py", line 32, in on_guild_join test = guild.channel.create_invite() AttributeError: 'Guild' object has no attribute 'channel'
Any who can help?
the errors says it as much
and you should not do what you're trying to do here
ikr
You must respect the privacy of the user
What
let me try do this for you
read the messages after that, I'm not even helping you
K ty
@bot.event
async def on_guild_join(guild):
test = guild.channel.create_invite()
channels = bot.get_channel(UNESI ID OD TVOG KANALA)
await channels.send(f"{test}")
so the bot.get_channel
are you trying to get a channel with that name?
I forgot await
did you even read the error "and stop helping with features that would break the TOS and privacy of the users"
Yeah
nice answer
ty?
welcome?
Lol thats not breaking any tos its classic log system
🧠
they were trying to send invites to themselves
normal logging would be printing stuff
No its log in one channel
For logs
huh
"tos"
you're violating the user's privacy
I'm not even arguing just forgive me
logging the name is fine, but not invite links to their server
What can i do with 1 invite? Hack discord ? Hack google?
Where did google come from 💀
The interaction fails, no error, just the text on discord that it fails
edit:nevermind, I forgot to link the callback
aliases commands works only with command.commands in COGS ?
@client.command()
async def hi(ctx):
await ctx.reply("hi")
@client.command()
async def hii(ctx):
hi(ctx)
why i cant do this
invoke
whats that
is it possible to make a global error handler that will affect all commands, if the user_id is not in the database, then it would give an error, otherwise you don’t want to write a check in all commands?
ok i can do this i have to put await
!d discord.ext.commands.Context.invoke
await invoke(command, /, *args, **kwargs)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Calls a command with the arguments given.
This is useful if you want to just call the callback that a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") holds internally.
Note
This does not handle converters, checks, cooldowns, pre-invoke, or after-invoke hooks in any matter. It calls the internal callback directly as-if it was a regular function.
You must take care in passing the proper arguments when using this function...
yo im new with cogs im trying to understand but i have error that i dont know how to fix
You need setup function
where
?
Just run it, see what happens
add_cog is async, you need to await it, also you load extension by bot.load_extension, you shouldn't import the function
no, normal commands work too
lol 
as flowerpad said, use load_extension
dpy 2.0 requires setup to be async
oh? didn't know, stopped using dpy
Not after discord.py 2.0
!pypi python-dotenv when the
you should be able to do it? you're not awaiting hi though
Yeah they should just await it
how to get interaction author name
I am gonna teach you how to get that info from docs
First of all, check attributes of Interaction class
@tacit horizon
!d discord.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.
ok
i did
Ok now, which of them do you think represents the interaction user?
tip: answer is in the question
user
🎉
The user or member that sent the interaction.
Type
Union[User, Member]
yes
it means that it can be any of those 2 instances
that will be interaction.User ?
Great now check attributes of the discord.User class and find out which represents the name
name
👏
so that will be interaction.user.name
Congratulations now you can use docs for finding information
it didn't work it showed this intents.message_content = True
AttributeError: 'Intents' object has no attribute 'message_content'
update your wrapper
How to do the ghost message thing, basicly a "message" that only targeted user can see and has that little dismiss text that makes it disapear, like some ones in slash commands that are used for errors
something like this, but without this glow, just a message
they're called ephemeral responses
ok
!d discord.InteractionResponse.send_message you have to set the ephemeral keyword argument to True
await send_message(content=None, *, embed=..., embeds=..., file=..., files=..., view=..., tts=False, ephemeral=False, allowed_mentions=..., suppress_embeds=False, delete_after=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Responds to this interaction by sending a message.
thanks
If I want to check if the user that interacts with Interaction I should use Interaction.user to compare, yes or no?
Yea
I did just change it so people do see my token
How can I get all "_id"`s from a table so that they are in a list with aiosqlite
Sqlite doesn't support array type if you mean that
I have messages array provided by ctx.channel.history
how do I check for all of them if they are not older than 14 days
!d discord.TextChannel.history
async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.11)") that enables receiving the destination’s message history.
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.
Examples
Usage...
just use the after kwarg?
My idea is that I fetch x messages, filter ones that are not older than 14 days to one array, filter ones that are older than 14 days to another one, bulk delete them(I accounted for 100 at time limit) and then fetch and delete rest of them, that is why I want to filter out them from already fetched array and not with kwarg
use the filter function and seperate the messages that are under 14 days by checking message.created_at
!d filter
filter(function, iterable)```
Construct an iterator from those elements of *iterable* for which *function* returns true. *iterable* may be either a sequence, a container which supports iteration, or an iterator. If *function* is `None`, the identity function is assumed, that is, all elements of *iterable* that are false are removed.
Note that `filter(function, iterable)` is equivalent to the generator expression `(item for item in iterable if function(item))` if function is not `None` and `(item for item in iterable if item)` if function is `None`.
See [`itertools.filterfalse()`](https://docs.python.org/3/library/itertools.html#itertools.filterfalse "itertools.filterfalse") for the complementary function that returns elements of *iterable* for which *function* returns false.
btw this is essentially what discord.py does when you use the purge() method
https://github.com/Rapptz/discord.py/blob/v2.1.0/discord/abc.py#L140-L164
Hello, I'm hoping to get some help on a project I'm working on.
I'm building a discord bot that will allow members to connect to Strava, pull their activities and then display information in certain ways (like weekly, monthly, yearly leaderboards for example).
My issue right now is with authenticating with Strava. I've tinkered with the Strava API previously on a Flask project that I was working on last year, but there I used the requests_oauthlib library to handle the sending the request and then getting the access code from the redirect.
I'm trying to get my bot to handle this, but I'm lost . I can have it display the link to the user, but then I haven't figured out how to get the data from the redirect_url aside from having the user copy/paste it. I'd rather not rely on that.
Is there a better way? Any advice/hints would be really helpful. Much appreciated.
What would load_extension be in discord.pay 2.0?
This was super helpful. Ty.
it's the same, but you'll have to await it
so what would be the best way to load extensions? I followed a few videos and used this, but what if I wanted to organize them more. i.e. folder/subfolders/files.py?
for cog_file in settings.COGS_DIR.glob("*.py"):
if cog_file.name != "__init__.py":
await bot.load_extension(f"cogs.{cog_file.name[:-3]}")
for subdir in os.listdir("main_cog_directory"):
# ignore files and folder with a continue, example:
# if subdir = "__init__.py":
# continue
for module in os.listdir(subdir):
await Bot.load_extension(f"main_cog_directory.{subdir}.{module[:-3]}")
``` would be the simplest way
i noticed the second loop is broken lol, it would be "main_cog_directory/"+subdir inside listdir^
thank you! do i need to define the subdir/module via a command then? or with this being a for loop, it will just complete these based on the directory?
os.listdir returns a list, subdir is a member of the list per iteration
same goes for module
you'll have to mention your main cog folder path inside the first listdir
so i have in my settings
BASE_DIR = pathlib.Path(__file__).parent
COGS_DIR = BASE_DIR / "cogs"
i'd just change the second one to be
main_cog_directory = BASE_DIR / "cogs" then technically?
yep that should do
ty!
From what you've said - I'm guessing Strava allows you to use OAuth to allow users to log in via their Strava account,and you can fetch information about their account?
I'm not 100% sure what Strava is so I'm taking a guess here :P
Yup!
Right now, what I'm doing is sending them the link, formatted properly.
The problem I'm having is in getting the response back.
I've been looking through Google trying to see if Discord will let me open up a browser to the link and then using something like BeautifulSoup to read the redirect url after they authorize.
But that's been mostly no go.
one more question. for the docs.
async def ping(ctx):
await ctx.send("pong")
so for commands, it always needs ctx, minimal, to work... right? then anything after ctx, is considered a string or integer based on what i define them as, but they can't be the prefix... right?
Unfortunately you're going to have to get the author to enter in the code into your discord bot manually.
Otherwise you'd need to somehow set up a communication pipeline from your Flask app (handling the redirect) to your discord bot.
I'll warn you this method gets really messy, though
I hate to say this - but your hands are a bit tied here 😦
its not just "string or integer" you can provide a lot of converter including int, including your own converter
Damn. That's what I've been worried about.
I'm right now trying to use the wait_for() command, but my check method hasn't been working properly
It even works with discord objects, like member pings!
What event are you waiting for?
The user submitting the redirect url into the chat.
Are you using some library for this?
wait_for is for discord.py events only
Unless you hack the library into listening for custom dispatches
From my understanding:
def check(msg):
return (
msg.author == ctx.message.author
and msg.channel == ctx.channel
and "https://localhost/exchange_token" in msg.content
)
All this really does is:
-
check that the author of the submitted message (after the discord bot sends out the link for them to auth to) is the original author.
-
Make sure we are still in the right channel
-
Make sure that whatever message was submitted has the portion of the url I know should be there.
Correct?
Yup.
It's been a while since I did any sort of OAuth - but is that link what you get along with the code to exchange for access token?
Looks like
https://localhost/exchange_token?code=some_code_here
Is that correct?
Yup
pretty much
Then yeah, what you said is correct. You'll have to parse out the code yourself
Or use something like urllib, which is part of the stdlib fyi
Awesome.
I'm literally brand new to discord bots and have been hacking together things I have found across a days worth of Googling.
My only problem is that I keep getting a "NoneType object has no attribute "author"" so I'm obviously referencing things incorrectly. Just need to find where.
I really appreciate all the help. Especially if you're in the east coast. It's almost midnight here.
Can you paste the whole traceback? We can get that sorted for ya 😄
CST, only about half past ten. No big deal 😛
I'd like to take a crack at getting it working myself first. I'm almost 100% positive that the issue is in referencing the wrong objects.
But considering how late it is, I'll probably leave it for morning.
Just post the traceback it's likely an easy fix
Always great to tackle it yourself first.
If you need help with that tomorrow feel free to open up a help post in #1035199133436354600 and ping me 😄
(But like y9 mentioned, if you want to get it out of the way, we can help you out now as well, up to you)
Hey robin I haven't really checked out discord.py buttons you know any good tutorials on them?
I'd just recommend the examples
https://github.com/Rapptz/discord.py/blob/master/examples/views/counter.py
The tutorials are pretty bad, frankly. If you go up to the "views" folder in the linked repo you'll find a bunch more examples
can buttons only be used with application commands?
,
Nah they can be sent in response to regular prefix commands as well
The response to the button however has to be an interaction
Though usually you want to tie them in with application commands for the best user experience
At the expense of feeling even sillier:
I can just copy/paste the whole traceback? Is there a specific format or do I just ctrl-c/ctrl-v it?
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.
That's strange. The docs say it has to be Message.
Can you try ctx.author?
I thought it was ctx.author
Could you show the code for that command perhaps, Fallennekho3?
Yes please. Codeblock it here if it's short, or pastebin like before if it's long
That was how I had it first and got the same error.
This has been happening all day with stuff, for example ctx.send won't work, but when I switch it to ctx.channel.send it does, which I found through the docs.
What version of discord.py do you have installed?
2.1.0
That's not good.
Actually, can you copy paste your entire code into a !pastebin? (it will probably be too long for discord)
(The version is fine, I was referring to it being funky)
make sure to take your bot token out before uploading
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Ah, I know why.
You call it ctx but in reality it's a discord.Interaction object
Hey robin, long time no see :3
Just a matter of faulty naming
Hi! Howdy?
yeah he type hinted it incorrectly?
In my check method? Or elsewhere?
Also, holy crap. That was incredibly fast to spot.
!d discord.Interaction @lethal creek discord.Interaction objects differ slightly from commands.Context objects
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.
It's typehinted properly, just named incorrectly
Wassup 🔫
If you'll notice it's a slash command
So u completed rust?
Oh i thought u finishing it alr xd
Goodluck then!
I don't know if I could ever finish a language like Rust, haha
Sorry, got sidetracked lol.
In your function header. Line 70
Same deal on line 38
I really want to make sure I understand, but my brain feels like molasses :
It doesn't really matter what I call it, but with discord bots ctx means I should be using a context object, and those have distinct commands from the interaction objects?
So the issue is that what I have written in places is expecting a context object but is calling interaction attributes, hence why I'm getting my none type error.
So if I just switch something like "ctx.author" to the appropriate attribute for the interaction I should be fine?
Exactly.
For a context object, you use ctx.author
For an interaction object, you use interaction.user
How you have it currently, you have a ctx: discord.Interaction which is really an interaction disguised as a context.
When you try calling methods you normally would on a context, you're actually accessing those methods on an interaction (which of course, don't exist)
Fortunately it's pretty simple and a 1 to 1 mapping between commands.Context and discord.Interaction
Awesome.
I was trying to print out what the output from each of these attributes, but it kept crashing regardless. When in doubt, I try to print out each of my objects/variables to know exactly what it looks like.
Question though: When should I use which?
For example, I imagine if I'm using commands I should be using interactions, since I'm interacting with the bot?
What sort of commands? Text-based or slash commands?
you can just use type annotations for your ide to do autocompletes and warn if you're using wrong member of the class
Text-based commands will use a context
Slash commands will use an interaction
a prefix based command (decorated with bot.command/commands.command ) would use a context
an application based command ( tree.command/app_commands.command ) would use a interaction
I really appreciate all the help, and adding more things to my reading. I definitely need to understand these differences better.
It's not at all trivial IMO, so having someone else tell you can be much easier than digging through documentation for hours
Finding this discord has been a god send, honestly.
Some other advise I have in your code:
- sqlite3 is blocking - you don't want to be using blocking libraries in your code. Switch to something like aiosqlite while your codebase is still small and easy to migrate
- You can use
name = interaction.user.nameinstead ofstr(ctx.user).split("#")[0](I'm assuming this part comes from a youtube tutorial) - You don't need to
int(ctx.user.id),discord_id = ctx.user.idwill do just fine - I would also not recommend creating a new connection for each command. Rather, you want a global connection and get cursors from there as you need it
- Syncing should be done in
setup_hookrather than inon_ready
You can always open a help channel in #1035199133436354600 or ask here and someone will help you out, if you need help with any of those aforementioned improvements
Going to save this and work on it in the morning.
Tip: use the .bookmark command when replying to that message
Very much appreciated @sick birch and @slate swan . You've both been super helpful!
Have a great night (or whatever fits best for your locale)
@bot.command()
async def uwu(interaction: commands.Context) -> None:
😳
what the
which bot can i use to upwork clients?
it's not finding the path specified. 🤔
I need help
Then ask it
To what clients?
sometimes when i load my vscode, i get this error when i try and do pip install...
[Errno 2] No such file or directory i'm just using powershell btw
Full error?
PS E:\!python\Bot Python Template> python pip install requests
C:\Users\Keiraxlicious\AppData\Local\Programs\Python\Python310\python.exe: can't open file 'E:\\!python\\Bot Python Template\\pip': [Errno 2] No such file or directory
don't I have to install them to run it local to test things?
..?
you get an error saying Import "requests" could not be resolved in vs when you go to run the main.py... so u have to install them is what I was taught from videos.
no?
Let me guess, YouTube tutorials?
yup and a skillshare one too
the skillshare one has you add them to a doc for heroku to run them.
Why are you importing it anyway?
If you really need to make requests you should be using aiohttp
cause idk what i'm doing? 🤣
Here is the example in the official discord.py repo:
https://github.com/Rapptz/discord.py/blob/master/examples/
which one shows an example of aiohttp?
!d aiohttp
Hold on
I've already said that,I don't think they even need it anyway
show code
idk yet, depends on what all it can do. like generate images from certain websites like for waifus, or can it grab data from a user# that's registered on tracker.gg/valorant for their rank
or does this allow api integration and if I have an api key for notion, valorant, apex... w/e can it integrate with those? to be frank, idk what and of these packages do, theres too many and if one person says to use requests and u say to use aiohttp... like how am i supposed to know what 1 can do and what 1 can't? just doesn't make sense to me.
use any http client
@slate swan discord.py uses aiohttp internally so it's a dependency: you install discord.py you also install aiohttp, it's recommend to use aiohttp over requests
Both of these libraries are used to make network requests, such as to apis, requests is not async, if you use it in an async script it will block other code from running, aiohttp does the same thing, but async
Httpx is a library that does both but like- no one uses it
This is what blocking means: https://discordpy.readthedocs.io/en/latest/faq.html#what-does-blocking-mean
and the more you use different modules the faster ull understand and remember how each is different
what
Responding to the end part of their question
show code
Is it possible to fetch a button class or a dropdown class from a diff cog ?
you mean import it?
yes and use it ofc
use the import statement and create an instance of the class?
um how ?
from diff_cog import ButtonClass
buttons = ButtonClass()
await send(view = buttons)
easy
it doesnt matter if the cog is in a folder right ?
why is it a cog then just use a simple file
simple file as in ?
any_file_name.py ??? doesn't need to be an extension
i got a diff project in which i need to do it with a cog too so thats why asking
i did have it like this, but still same error.
load_extension takes python import path like string as argument, not the actual path
"path/to/file.py": ❌
"path.to.file": ✅
so you'll have to do the path joining manually
pathlib won't do that
if you replace the exact code i sent with "main_cog_folder" replaced with your cog folder name it should work
I forgot how to do this with bare requests, but how do I retrieve every message from a channel?
You probably know, @slate swan
Like directly with discord API or with discord.py
directly with the API
in discord.py I would just do
[message async for message in channel.history(limit=None)]
but i'm not sure how with just bare requests
!d discord.TextChannel.history
async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.11)") that enables receiving the destination’s message history.
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.
Examples
Usage...
I'm looking for the actual code of that method
so that did fix that error...
now I have...
discord.ext.commands.errors.ExtensionNotFound: Extension 'cog_extensions.cmds.__pycach' could not be loaded.
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
its the pycache folder, add a check the continues if the item is not a .py file lol
how would I request all of them though?
request the first 100
get the creation time of the oldest one of those,
use the creation of the oldest for the "before" argument and request for the next 100, keep repeating...
Hiya, I know discord already has a default /timeout command but I want to be able to add one to my discord.py bot but have no idea what I’m doing. I’ve tried looking on YouTube, stack overflow, Google, etc. and haven’t found one that works and is compatible with slash commands. Can anyone assist me please?
!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 "(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").
!pypi time-str
!d discord.ext.commands.Converter
class discord.ext.commands.Converter(*args, **kwargs)```
The base class of custom converters that require the [`Context`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context "discord.ext.commands.Context") to be passed to be useful.
This allows you to implement converters that function similar to the special cased `discord` classes.
Classes that derive from this should override the [`convert()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Converter.convert "discord.ext.commands.Converter.convert") method to do its conversion logic. This method must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine "(in Python v3.11)").
that should be about it
whats the best way to append user's info? like append their pfp and nickname to files on github or whatever might be obtainable for another bot to grab the info?
Trying to add a lockdown command to my bot, but it doesn't change the permissions of the everyone role. Please help <3
@bot.tree.command(name='lock', description='Locks a channel')
@has_permissions(manage_channels=True)
async def lockdown(interaction: discord.Interaction):
guild = interaction.guild
await interaction.channel.set_permissions(interaction.guild.default_role,send_messages=False)
embed = discord.Embed(title=(f'{interaction.channel.mention} + " ***is now in lockdown.***'), color=0xf6ff00)
await interaction.response.send_message(embed=embed)
also in the embed it says the channel ID instead of the name
how can I turn a tool into a bot with /commands
!d discord.TextChannel.set_permissions
await set_permissions(target, *, overwrite=see - below, reason=None, **permissions)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sets the channel specific permission overwrites for a target in the channel.
The `target` parameter should either be a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") or a [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role") that belongs to guild.
The `overwrite` parameter, if given, must either be `None` or [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/latest/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite"). For convenience, you can pass in keyword arguments denoting [`Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions "discord.Permissions") attributes. If this is done, then you cannot mix the keyword arguments with the `overwrite` parameter.
If the `overwrite` parameter is `None`, then the permission overwrites are deleted.
You must have [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") to do this...
You can't use markdowns or mentions in embed title
If I can't use mentions, how can I just get it to display the channel name as regular text?
In the description?
.name
what exctly are you trying to achieve?
like in what manner should you store the data or where you could store the data?
iirc You can mention in the title now
I'll test that 🧐
yeah pls thanks
so i wanted to make animated alerts on streamelements for specific guild.id's when someone joins the discord the bot's in. so while i was waiting for a response, i've been looking into aiohttp and pil? to be able to do image related stuff?
lets say i have a default 200x200 px image and a default text. just when someone joins it, it overwrites the previous. i just want the data to append the info stored since I can't have it append something locally if it's running on a server... so github was my first idea...
how do i send msg if the erroris nonetype? try and except?
What really 🤯
this is better suited for #python-discussion but yeah sure why not
okay
I see
I didn't even understand, maybe someone else could help 😭
if you want to upload things and access them from somewhere else, you might wanna use a cloud db, that's the easiest imo
by locally do you mean on your computer?
oh...
uhh...
just overwrite the image.png and overwrite a txt or md file stored somewhere... can be local or cloud, or github. just somewhere then i can fetch it w/ c#
but if i'm using like heroku to host my bot, it won't be able to append files on my pc... which is why i mentioned online services
I meant, are u running the bot on your computer?
only for dev purposes. anything that works is running on heroku rn
I see, well yeah then you can use a cloud database as Ash said. I'm not entirely sure how heroku works
I'd personally use a cloud database for what you're doing
a drive database for storing images
and a normal database for storing the text you put in the txt file
heroku basically clears all the edited files by the point of termination, so anything such as using json as a database is not going to work
oh damn
This could be overkill so if you want any other alternative 💀
i have it linked to github so i thought the init's push's could just overwrite what gets saved, but wasn't sure how it would send data from heroku back to github where it initializes the bot from...
i mean, the only clouds i use are googledrive and pcloud.
any suggestions?
I wouldn't want to risk that either, you bot's gonna restart every time
something's pushed if you have the feature enabled ofc
true....
I'd personally use the deta databases since they're truly easy to interact with
they have a databases for Drive and a JSON-based database too (JSON dbs have a storage of 10gb and the drive also has 10gb I suppose)
nosql = cringe
ok bro
yes
ok

databases are cringe 😔
^ use paper

just go back to stone age and use hammers and chisels at that point
just develope a good memory
Just don't do anything and wait for death
or let someone else do the work and u borrow it
"don't do nothing" 😔 why even borrow
sounds like something I'd do
as the boomers say "work smarter not harder"
not working at all better
you do lots of work everyday, so you shouldn't be saying that
embed = discord.Embed(icon = member.display_avatar, title = f"Member Joined", description = f"{member.mention}({member.name}) joined the server.\n\n", color = discord.Colour.random(), timestamp = datetime.datetime.utcnow())```
whats wrong here?
ok, so how does this cloud work? i installed deta package,
then it says
# initialize with a project key
deta = Deta("project key")
# create and use as many Drives as you want!
photos = deta.Drive("photos")
photos.put("my_first_car.png", path="./my_first_car.png")
so would i just do like...
await self.client.photos.put(image_path, member.avatar_url, content_type="image/png")
await self.client.text.put(text_path, member.name, content_type="text/txt")
? aside from the try-except statement handlers.
well first of all you should use their async sdk
lemme grab the link rq
thank you
https://docs.deta.sh/docs/base/async_sdk
here is the async base
and what you're trying to do is right too
The Deta Base Python Async SDK can be used for reading and writing data asynchronously with Deta Base in Python.
thank you!
you're welcome
so quick question, can I only view whats on the drive with code or are there like hyperlinks to the data stored?
anyone down to help me come up with a gameplan to make a transaction bot (examples in screenshots)
the current bot is not it
hoping to make a better more streamlined and error free alternative
it would be server specific
i'd assume a db is needed for data that needs to be persistent
(like the bot not forgetting user a owns team a, and there are these players on team a)
What's the problem
Also the icon arg needs a string of a url
Not asset
you could use the UI too
just login to your account and you'll see a pane on the left that contains all your dbs and drive
assuming the library is an up-to-date discord.py (or dpy fork) I'd look into not using datetime.datetime.utcnow()
!d discord.Guild.bans
async for ... in bans(*, limit=1000, before=..., after=...)```
Retrieves an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.11)") of the users that are banned from the guild as a [`BanEntry`](https://discordpy.readthedocs.io/en/latest/api.html#discord.BanEntry "discord.BanEntry").
You must have [`ban_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.ban_members "discord.Permissions.ban_members") to get this information.
Changed in version 2.0: Due to a breaking change in Discord’s API, this now returns a paginated iterator instead of a list.
Examples
Usage...
banList = await member.guild.bans()```
i used to do this
!d discord.Guild.bans
async for ... in bans(*, limit=1000, before=..., after=...)```
Retrieves an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.11)") of the users that are banned from the guild as a [`BanEntry`](https://discordpy.readthedocs.io/en/latest/api.html#discord.BanEntry "discord.BanEntry").
You must have [`ban_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.ban_members "discord.Permissions.ban_members") to get this information.
Changed in version 2.0: Due to a breaking change in Discord’s API, this now returns a paginated iterator instead of a list.
Examples
Usage...
oof
yeah discord.utils.utcnow() to be used
It's an async generator
isn't there a more streamlined way to do that
banList = [async for banned_user in Guild.bans()]
😔
jus a bump, keep movin though
