#discord-bots
1 messages · Page 144 of 1
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.
ctrl+shift+-
can i access message if i store message.id when it deleted
you can do nothing with a message id of a message which was deleted
ok thanks
unless you have that message in cache (if your lib allows that) or you can store every message (not recommended)
what the hell is a tuple
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
!e
a = len(shash)
if a == 64:
await ctx.send(f'**Fetching ServerHash {shash}**')
if checkid(shash) == False:
return
await (ctx, shash)
else:
asyncio.sleep(2)
await ctx.send('**Invalid ServerHash Provided!**')```
@amber ether :x: Your 3.10 eval job has completed with return code 1.
001 | File "<string>", line 3
002 | SyntaxError: 'await' outside function
!e
a = len(shash)
if a == 64:
await ctx.send(f'**Fetching ServerHash {shash}**')
if checkid(shash) == False:
return
else:
asyncio.sleep(2)
await ctx.send('**Invalid ServerHash Provided!**')```
@amber ether :x: Your 3.11 eval job has completed with return code 1.
001 | File "<string>", line 3
002 | SyntaxError: 'await' outside function
oH SHIT YES
Alright i fixed everything!
now new problem..
Why is this isnt working?
the
await ctx.send(f'**Fetching ServerHash {shash}**')
if checkid(shash) == False:
return```
Checks the game id then if its used **Once** it can be used but when its used again it will return as
```js
await ctx.send('**Invalid ServerHash Provided!**')```
But its saying Fetching ServerHash {shash} instead of Invalid ServerHash???
Quick question all, https://paste.pythondiscord.com/ukinesomav
In my code, I have a few things I want to remove which is, 18+ area and its respect role id, as well as the text "NOTE: We will bla bla", can I just remove this from the code?
And I also want to add in some extra roles, would this be the same case? Cheers.
Edit: Is it also worth looking into converting to buttons? Seems like its becoming popular for embedded reaction posts.
how come url is not a parameter in this
@discord.ui.button(label="Pay", style=discord.ButtonStyle.success)
how would i add a url to that button
Buttons with URL cannot have callback
Look at the example
https://github.com/Rapptz/discord.py/blob/master/examples/views/link.py#L23-L33
examples/views/link.py lines 23 to 33
class Google(discord.ui.View):
def __init__(self, query: str):
super().__init__()
# we need to quote the query string to make a valid url. Discord will raise an error if it isn't valid.
query = quote_plus(query)
url = f'https://www.google.com/search?q={query}'
# Link buttons cannot be made with the decorator
# Therefore we have to manually create one.
# We add the quoted url to the button, and add the button to the view.
self.add_item(discord.ui.Button(label='Click Here', url=url))```
Check the message counts in on_message evnt
Then use if else statement
If len(message) == your amount here:
#then add the role
Ez as that
is there a way for the discord bot to respond to buttons even if it was restarted?
Converting this thing with buttons = worth ++
If u talk about difficulty i would say average
Yes!
If u use classes
how would i do it?
Then
in on_ready event
add extra line,
bot.add_view(myclass())
@simple kettle check that out
Yeh, its first time doing that so I'll proabbly do that last, I want to achieve the editing changes first before then achieving buttons. 🙂
would the class be a view class?
yep
like
class button(discord.ui.View:
#othercodes
Syntax error
Then the class will be
button
bot.add_view(button())
Bracket
And every items in the view must have a custom_id set
Oh ye forgot to mention that
Lol thanks for mentioning that
Editing changes?
"Quick question all, https://paste.pythondiscord.com/ukinesomav
In my code, I have a few things I want to remove which is, 18+ area and its respect role id, as well as the text "NOTE: We will bla bla", can I just remove this from the code?
And I also want to add in some extra roles, would this be the same case? Cheers."
Yep, so want to make a few changes the actual embed first 🙂 then I can look at buttons later. This was my original question 😄 Don't worry if you don't know, I'm not in a rush.
Ig u have 1 hybrid command and another slash command
Nah
Then maybe glitch
sorry im still just a little confused, i did bot.add_view(PaymentView()) but nothing happens. Im basically making a ticket bot where the bot will have a message with a view in a certain channel and if users press that button it will create a ticket, but i want the button to always work even if the bot restarts
How to fix lol
Can i have the class in dm?
sure
I dmed u already
Maybe u forgot to check
!d discord.Button
it doesnt work tho
It does
The emoji should be or must be in that server where the bot in
Yes
ight thx a lot!
:]
is there a way to give someone a certain role from another server?
!d discord.Guild.get_role
get_role(role_id, /)```
Returns a role with the given ID.
Changed in version 2.0: `role_id` parameter is now positional-only.
hM i need help with building an auto message function for my club's discord bot
can anyone help im clueless about the discord.py library
or a trustworthy course about it?
thx a lot
Any way to find number of messages that a user has in a given time?
!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...
Im trying to edit a message my bot sent
msg = await interaction.response.send_message("A ticket is being created", ephemeral=True)
await msg.edit(f"Channel created sucessfully! {channel.mention}")
but it gives me a errror
send_message doesn't return the sent message
oh, is there a work around for this
!d discord.Interaction.edit_original_response
await edit_original_response(*, content=..., embeds=..., embed=..., attachments=..., view=..., allowed_mentions=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the original interaction response message.
This is a lower level interface to [`InteractionMessage.edit()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionMessage.edit "discord.InteractionMessage.edit") in case you do not want to fetch the message and save an HTTP request.
This method is also the only way to edit the original message if the message sent was ephemeral.
oh nice, thank you
import discord
import os
my_secret = os.environ['token']
client = discord.Client(intents=discord.Intents.default())
@client.event
async def on_ready():
print('Logged in as {0.user}'.format(client))
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('$hello'):
await message.channel.send('Hello')
client.run(my_secret)
when i run this code and type in $hello in my discord server the bot doesn't respond
anyone able to help? thx a lot
!intents
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.
you gotta enable message content
ohh
can you please paste the code....?
@fading marlin
yes?
since 2 people click the button named confirmation it sends a embed on confirmation twice but when i try to delete them it only deletes one of them how do i make it delete both
u meant enable this thing right?
what're you trying to accomplish?
yes, don't forget to enable them in code too
i need the bot to delete 2 embeds generated after a button is clicked
from discord import Intents
import discord
import os
my_secret = os.environ['token']
intents = Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
@client.event
async def on_ready():
print('Logged in as {0.user}'.format(client))
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('$hello'):
await message.channel.send('Hello')
client.run(my_secret)
is this any better?
sure
where are you saving those embeds?
are u reading the code i sent
yes, it's a mess. The second time you click on the button, you're sending a message with an embed, and deleting it immediately
hm
im deleting it after 2 clicks
however i need my bot to delete both the embeds made it only deletes one
because you're not storing the first one
@client.tree.command(name="purge", description="yes")
@commands.has_permissions(manage_messages = True)
async def purge(interaction: discord.Interaction, amount : int):
await interaction.channel.purge(limit=amount+1)
await interaction.response.send_message("Purged messages.")
It's saying the following error.
Traceback (most recent call last):
File "/home/runner/e/venv/lib/python3.8/site-packages/discord/app_commands/tree.py", line 1242, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/runner/e/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/home/runner/e/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 880, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'purge' raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction
whats wrong with it
you're not responding fast enough
defer the interaction, purge, and then send a followup
how do i store it
i have no idea what u just said
i literally started like 1 week ago
it actually works, just i need a message.
it shows up as "the application did not blahblahblah"
!d discord.InteractionResponse.defer - You need to defer the interaction if you need to take over 3 seconds to respond
await defer(*, ephemeral=False, thinking=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Defers the interaction response.
This is typically used when the interaction is acknowledged and a secondary action will be done later.
This is only supported with the following interaction types...
Then respond to it later using followup
@client.tree.command(name="purge", description="yes")
@commands.has_permissions(manage_messages = True)
async def purge(interaction: discord.Interaction, amount : int):
await interaction.channel.purge(limit=amount+1)
await interaction.response.send_message("Purged messages.")
where
spoon feeding time
i think
yes i legit started coding a week ago
😭
@fading marlin
@client.tree.command(name="purge", description="yes")
@commands.has_permissions(manage_messages = True)
async def purge(interaction: discord.Interaction, amount : int):
await interaction.response.defer()
await interaction.channel.purge(limit=amount+1)
await interaction.followup.send("Purged messages.")
omg tysm
im stupid <3
no, your just new lol
bruh commands. has perm don't work on slash
where did lee go
https://discord.com/channels/267624335836053506/1046428542788980819 unfortunately closed, so can't get any further help in the thread, unless a mod can reopen it for me.
Link to my code: https://paste.pythondiscord.com/ukinesomav
A quick run down, I am trying to edit my reaction post embed so its description is updated, remove a few obsolete roles not used anymore while also adding in some new ones. I decided to open a help topic as I assumed it would be better than here and stay open without getting lost.
Unfortunately, editing the code directly hasn't edited the embed, so I assume that is the incorrect way and I need to add in some new code to push the edits, such as the removed emojis, new emojis added, and embed description change?
Not really a good idea to start bots with such a skill level
“Everybody is a genius. But if you judge a fish by its ability to climb a tree, it will live its whole life believing that it is stupid.” - Albert Einstein
🦦
yes therefore climbing trees is stupid

talking about monkeys, one appeared
A wild monkey has appeared
since when could monkeys talk
how can i hard code the bot to send a message to me directly?
oh wait i probially have a simmilar line of code 
yep found it
GUILD_ID = 798726719573065749
CHANNEL_ID = 798726720181633047
location = bot.get_guild(GUILD_ID).get_channel(CHANNEL_ID)
await location.send(embed=embed)
you dont need to get the guild
yeah i didnt mean to copy that line lol
!d discord.ext.commands.Bot.get_channel
get_channel(id, /)```
Returns a channel or thread with the given ID.
Changed in version 2.0: `id` parameter is now positional-only.
just use Bot.load_extension which handles it all, including getting the module object
!d discord.ext.commands.Bot.load_extension
await load_extension(name, *, package=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Loads an extension.
An extension is a python module that contains commands, cogs, or listeners.
An extension must have a global function, `setup` defined as the entry point on what to do when the extension is loaded. This entry point must have a single argument, the `bot`.
Changed in version 2.0: This method is now a [coroutine](https://docs.python.org/3/glossary.html#term-coroutine "(in Python v3.11)").
would that be self.get_channel(id) or ctx.get_channel(id)
thanks
your instance is defined as bot, no?
then you would use that instance to acess that method
hmm? i dont understand
Well, the method given was Bot.get_channel and if you want to use the method, you would need an instance, which in your case if its a cog, i would think it's defined as self.bot
so self.bot.get_channel(id)
yep
and how do i get the id that my bot would use to dm me
it could raise an error, so i would also be cautious by adding a check
!d discord.AppInfo.owner
The application owner.
!d discord.ext.commands.Bot.application
property application```
The client’s application info.
This is retrieved on [`login()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.login "discord.Client.login") and is not updated afterwards. This allows populating the application\_id without requiring a gateway connection.
This is `None` if accessed before [`login()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.login "discord.Client.login") is called.
See also
The [`application_info()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.application_info "discord.Client.application_info") API call
New in version 2.0.
ima print that to see what it outputs
so print(disnake.AppInfo.owner) ? to see its output
discord uses tenor
Send the error
You cant mention users in a embed title
That's not related to discord.py
Neither did i
@client.command()
async def add(ctx, user: discord.User, *, type:str):
guild = client.get_guild(ID)
free = guild.get_role(ID)
paid = guild.get_role(ID)
if type == free:
await ctx.reply("done")
await user.add_roles(free, atomic = True)
elif type == paid:
await user.add_roles(paid, atomic = True)
anyone see whats wrong with this?
ctx.author.mention
np
The mention wont get formatted
i dont think u can
Discord doesnt let you mention anything in a embeds title
just remove the title and put it in description ig
the description would look like the title
The user’s username.
Me after mentioning 1989 in embed title
anyone see a problem with this though?
you're not funny, you're just a clown

You're using Context.author which returns User | Member
U forgot to add the user ur gona slap
async def slap(ctx, user : discord.Member)
then you can use discord.User.name or discord.Member.name, its the same since discord.Member.name derives the attribute from the superclass
I cant stand the level of intelligence in this chat, its insane
🦦
Do i need to repeat myself?
Where?
Show your code
U cant mention ppl in a embed title or title of a field
cant*
Yeah my bad
The user’s username.
ctx.author.name, and you cant mention a user in a field name
Sorry, i tought u used it in a description
You cant mention a user in a title🦦
^
then what is it?
user.name and user.discriminator
no
just use the objects __str__ dunder
!e
import attrs
@attrs.define
class Foo: ...
print(Foo())
@primal token :white_check_mark: Your 3.11 eval job has completed with return code 0.
Foo()
@client.command()
async def add(ctx, user: discord.User, *, arg: str):
guild = client.get_guild(1021915848190984192)
free = guild.get_role(1030885423414788097) #ANNC
paid = guild.get_role(1025510351254605844) #BYPASS
member = guild.get_member(user)
if arg == "free":
print("pass2")
await ctx.reply(f"Added `Free` to {user.mention}")
await member.add_roles(free, atomic = True)
elif arg == "paid":
print("pass2")
await ctx.reply(f"Added `Paid` to {user.mention}")
await member.add_roles(paid, atomic = True)
its not adding roles idk what to do
im trying to make it work between servers
guild.get_member takes a user id, not a user object
you also have a faulty error handler if you get no errors
is it possible to change bot status using a loop ? like every 10 seconds he updates the presence
yes, but not recommended
why not
wow but why people r not getting ratelimited for changing status with list of words
is it bcs they r not calling change_presence always?
like back before people really used changing status with list of words or variables
is your bot small/private
then it's not a problem tbh
but discord will not rate limit me if i update status every 10 seconds?
good to know, thanks
it's wrong and thats what discord does not suggest you to do. if others do it doesn't make it right.
in the end, you do you
changing presence is not a REST API request
its an Gateway event
doesn't matter if your bot is in 100k guilds or no guilds at all
I dont really see the purpose of limiting your gateway events because you want your bots status to change
bot status changing = swag
sure
noone even checks your bot's status other than you yourself;-;
every dev wants fancy shit on his project
by you im not targetting a particular but everyone
Most devs sadly dont know even what theyre doing
I really wouldnt follow what anyone does, be creative and make unique things, that how you will see your bots popularity get bigger
create a bank bot for dabloons = ez verified bot
could you show an example?
print(bot.application.owner.id)
Its vulnerable to attribute errors though
Dont forget about adding "Verified bot developer" in your about me
it will make you cooler😎😳
"open for commissions"
10000$ for a JSON db bot😈
hosted on replit
for txt db bot
😳😳
hosted on my pc
txt? grow up and use pickle
It's sad seeing people do these types of things
i used to do that on private bots i made for 2-3 persons
use the cache as db
u dont need a db for 3 people who got no idea what they r doing
omw to use discord.py's internal cache as my database
Its funny though, i questioned one of them in front of a group of people, the dude was so embarrassed felt great🦦
i mean who need a db
^
but first delete all the useless objects that occupy memory like members guilds etc
i need a database for custom prefix feature that noones going to touch
You can
"intents": 0 😈
Just use ctypes and allocate the memory yourself
-1
who needs a bot, u can become the bot...
you can just use https://github.com/ilynoid/Intercord not a paid ad😳
i tried it once
mess with the python execution thread
logging into my bot account within my terminal
destroy the GIL
thats literally what ive done in the repo above😭
snipy also helped me🦦
corrupt the kernel
login into ur terminal using the bot
use transistors🦖
@commands.command(name='reccomendstatus', description='Reccomend a status for me to add to the bot!')
async def reccomendstatus(self, ctx, *, status : str):
print(self.bot.application.owner.id)```
```Ignoring exception in command reccomendstatus:
Traceback (most recent call last):
File "C:\Users\David Powell\PycharmProjects\WhiskeyBotMain\venv\lib\site-packages\disnake\ext\commands\core.py", line 173, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\David Powell\PycharmProjects\WhiskeyBotMain\cogs\aboutme.py", line 56, in reccomendstatus
print(self.bot.application.owner.id)
AttributeError: 'Bot' object has no attribute 'application'
lmao but it was simply standalone script that recieved and sent messages in a particular channel
was just messing with a friend
hehe
my eval command with sh evaluation is capable
not actually made my me, it was a lightbulb extension
i posted something like 1h ago on git
Thats odd
!d discord.Client.application_info
ssh Bot
await application_info()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves the bot’s application information.
ssh ?
also an await-able
what happened
secure shell
is it this https://github.com/CreedoW/pycord-ssh-client
yes
bro is packing muscle
i was thinking snipy used "ssh" as a bot prefix
thru
bro
repo name: pycord-ssh-client
main name: bot.py
and finally client = commands.Bot
Nice names
You were undecided
bot.py lines 14 to 17
@client.event
async def on_ready():
await client.change_presence(status=discord.Status.dnd, activity=discord.Streaming(name="ssh bot", url="https://roblox.com/"))
print("READY")```
😏
roblox
aaaa
discord gateway 😤😤
:exit:
smart
Wondering if anyone could advice/assist on this?
only if you give me robux
send gamepass
runs to freerobuxgenerator
I'm reading the message
if I'm not wrong, there are probably no rate limits for changing presence or they're not documented anywhere, people do change the presence in like 2-3 minutes
give me a star
Theres a limit for gateway events not specific ones iirc
gimme 10€
what have you done so far?
you want to edit that message to remove something from the embed right?
If your main goal is editing the embed i would recommend editing the embed object stored in embed by mutating the values of a few attrs and just edit the message and add the new state of the embed
A quick run down, I am trying to edit my reaction post embed so its description is updated, remove a few obsolete roles not used anymore while also adding in some new ones. I decided to open a help topic as I assumed it would be better than here and stay open without getting lost.
Unfortunately, editing the code directly hasn't edited the embed, so I assume that is the incorrect way and I need to add in some new code to push the edits, such as the removed emojis, new emojis added, and embed description change?
isn't it an old message
he needs to fetch the message
ratelimits are dynamic, and:
yup
it's not even real
it is but... u know... u cant use it
is using battery saver on 63% weird?
that's why it's not real
Some people always have battery saver on so not really
nah
So simply, I have changed the embed description, the dictionary that holds the current roles, removed the old roles from it and updated with the new roles. but these changes don't reflect on the embed. This is why I assume there may be some new code required to add into push these changes. 🙂
is real
not even transferable
I've never disabled it lmao
u can transfer it to someone else on ropsten
@slate swan you need to:
fetch the message
access the embed with message.embeds (you need message_content intent) and gets the embed that you want to modify
edit the message with the new embed
i always have battery saver off when im not on low battery due to performance issues
i use my phone only for calls and discord sometimes so performance is not really an issue for mw
call me
to remove the reaction you need to use message.clear_reaction
Ok cheers, I'll go mess around now and see if I can get it working 🙂 cheers for the advice and everyone else.
!d discord.Message.embeds
A list of embeds the message has. If Intents.message_content is not enabled this will always be an empty list unless the bot is mentioned or the message is a direct message.
!d discord.Message.clear_reaction
await clear_reaction(emoji)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Clears a specific reaction from 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 [`manage_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") to do this.
New in version 1.3.
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`.
ok

I was in serious mode for some seconds
relatable
imma create the most verbose discord api wrapper 😏
you finna make it strongly typed?😳
im using mypy on strict so im hoping so
the heck
that complaining bitch
bot = this_create_a_bot_object_fr(**kwargs)
uninstall it
so there's a minimal class named
ApplicationCommandInteractionDataResolved
no bro
bot = creats_a_python_object_that_represents_a_discord_bot(token)
not that verbose
You can do better
it's perfect
you don't even needs docs
ClassCreatedWithResolovedFieldOfTheApplicationCommandInteractionPayload
talking about linters, pylance never screams at me, maybe im just too good🥶
self documented🦦
add # pyright: strict ig
where
on the top of file
ig you're code is full of # type: ignore
ive used pyright it wasnt hard tho
🦖
if you know typing nothing's hard
the most annoying part in typing is decorators
ahah
Who uses the strict mode
typing decorators be like ```py
) -> typing.Callable[[typing.Callable[..., typing.Awaitable[typing.Any]]], EventListener]:
just declare a type, ez
i use mypy strict, i love playing with fire
you will get burned
i love tans
import typing
Fun: typing.TypeAlias = typing.Callable[[typing.Callable[..., typing.Awaitable[typing.Any]]], EventListener]
😳
Fun
typealias is 3.9+ ig?
3.10+
yeah can't use, the library is 3.8+
i tried using Typevar but it supports only generics
just use stubs
classic Noid that suggest unsupported features

I would suggest supporting at least Python 3.9 as well
i would suggest not listening to snipy and going for 4.0
😭
This update about to be crazy
typing_extensions?
3.11 looked promising about speed
but it don't feel much of a boost
who uses typing_extensions lol
big L
Unpackage the package
not gonna add a new dependency for a single line
If you add the import under if TYPE_CHECKING: then you don’t need to add as a dependency
im already using attrs cause dataclasses doesn't support kw_only arg in 3.8
I think that’s what discord.py does
Pretty fast non the less
anyone have idea why this doesnt work?
except commands.errors.MemberNotFound:
await ctx.reply(f"Member {member} not found!")
it still prints out the error
Sorry to ping, just a quic q, would I need to define a new function or would this be fine to go inside the current embed function?
How do i calculate how long a slash command took to respond?
datetime.datetime.now()-interaction.created_at
Traceback (most recent call last):
File "E:\PyCharm\projects\spunge\venv\lib\site-packages\discord\app_commands\tree.py", line 1242, in _call
await command._invoke_with_namespace(interaction, namespace)
File "E:\PyCharm\projects\spunge\venv\lib\site-packages\discord\app_commands\commands.py", line 887, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "E:\PyCharm\projects\spunge\venv\lib\site-packages\discord\app_commands\commands.py", line 876, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'monsterinfo' raised an exception: TypeError: can't subtract offset-naive and offset-aware datetimes
discord.utils.utcnow()```
A helper function to return an aware UTC datetime representing the current time.
This should be preferred to [`datetime.datetime.utcnow()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.utcnow "(in Python v3.11)") since it is an aware datetime, compared to the naive datetime in the standard library.
New in version 2.0.
yea
so datetime.datetime.now(discord.utils.utcnow())?
oh lol nvm im dumb
how do i make it timezone aware 😭
discord.utils.utcnow returns a timezone aware datetime
mh, it's up to you, it will work as long as you have access to the Bot object (but don't put it inside an event callback)
disnake 🙂
whats disnake🥸
it's a spaceshuttle
🚀
I want to cry on voice receiver files
Rust?
You talk more about rust than about python, so why not remove you from the pydis staff team
the pydis staff team is secretly the rustdis staff team
No MoRe "Staff at the python discord btw" 😿
I shall delete this server and we can all frame chris😈
no more 19 dollar cards
🙀
In which case you can just do ctx.author
Me
There are some features you get from it without needing to update your python version (which could potentially break your code base)
Like before I used it for Annotated, Self and some other stuff
Also some very important stuff like tuple generics
1v1, sky wars
So you can TypeVarTuple or something like that
And Unpack since *Generic[...] isn't possible
Unless you again, upgrade versions
I actually havent seen the need to use it yet
I was re-writing Rin using tuple generics
It makes my callbacks a lot more type-safe
Rin?
from typing import Any, Generic, TypeVar, Callable, Coroutine
from typing_extensions import TypeVarTuple, Unpack
_CallT = TypeVarTuple("_CallT")
_RetT = TypeVarTuple("_RetT")
Callback = Callable[[Unpack[_CallT]], Coroutine[Any, Any, Any]]
class InboundEvent(Generic[Unpack[_CallT]]):
def on(self, func: Callback[Unpack[_CallT]]) -> Callback[Unpack[_CallT]]:
return func
class User:
...
READY = InboundEvent[User]()
@READY.on
async def foo(user: User, something: str) -> int:
...
``` Yea
In hind sight I could've just used ParamSpec though....
So this type errors with py @READY.on async def foo(user: User, something: str) -> int: ... but with this is doesn't type error ```py
@READY.on
async def foo(user: User) ->int:
...
don't change presence in on_ready.
!d discord.Client
class discord.Client(*, intents, **options)```
Represents a client connection that connects to Discord. This class is used to interact with the Discord WebSocket and API.
async with x Asynchronously initialises the client and automatically cleans up.
New in version 2.0.
A number of options can be passed to the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client").
u can
@glad cradle
doesnt mean you should
does anyone know places to host my bot?
is there anyone here thats really good with dpy
hi
AttributeError: 'Bot' object has no attribute 'slash_command'. Did you mean: 'add_command'?
What version of Discord.py do you have? Also the new version of Discord.py uses a tree and not the Bot object
discord 2.1.0
discord.py 2.1.0
@tree.command
You dont need that other discord package btw
ok
@tree.command(name="redeem", description="redeems key for license")
NameError: name 'tree' is not defined. Did you mean: 'True'?
how would i fix this
@bot.command()
async def balance(ctx):
user_id = ctx.author.id
if find_member(user_id) == None:
insert_user(ctx.author.id)
user_info = find_member(ctx.author.id)
embed=discord.Embed(title=f"{ctx.author.display_name}'s balance", description=f"You have {user_info['coins']}", color=0xFF5733)
embed.set_author(name=ctx.author.display_name,icon_url=ctx.message.author.avatar_url)
await ctx.send(embed=embed)
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Member' object has no attribute 'avatar_url'
I don't understand the error
'Bot' object has no attribute 'slash_command'
Are you using py-cord?
ive tried using
no but ive tried using @uncut zenith.command
oops
didnt mean to @ him
Can you paste your code?
?
@bot.slash_command(name="redeem", description="redeems key for license")
async def redeem(ctx, key):
with open("data/keys.txt", "r") as f:
lines = f.readlines()
with open("data/keys.txt", "w") as f:
for line in lines:
if line.strip("\n") != f"{key}":
f.write(line)
open(f"data/stocks/1month/{ctx.author.id}.txt", "w")
open(f"data/stocks/3month/{ctx.author.id}.txt", "w")
else:
await ctx.respond("Invalid Key")
where the error is running
from optparse import Option
import discord
import json
import requests
import os
import httpx
import base64
import time
import os.path
import string
import random
from discord.ext import commands
from datetime import datetime
from colorama import Fore
and thats my imports
Its just .avatar
without _url?
Yep
can u help?
!d discord.Member.avatar
property avatar```
Equivalent to [`User.avatar`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.avatar "discord.User.avatar")
avatar_url was before d.py 2.0
'Bot' object has no attribute 'slash_command' using d.py but ive tried tree commands they just dont work
You'll have to elaborate on "just don't work"
okie
not defind it says
tysm
Nope sorry
Traceback, please
when i use @uncut zenith.commands
it says name 'tree' is not defined
Are you using bot or client?
bot
bot = commands.Bot(intents=discord.Intents.all(), command_prefix=f"{prefix}")
then it's @bot.tree
so @bot.tree.command?
yes
but how do i make it a slash command
here's an example of a basic slash command that might be worth reading over
ok
AttributeError: module 'discord' has no attribute 'Bot'
💀
i dont work with dpy
Pycord?
idfk im new to making bots im jus trying to fix this for a friend
import discord, json, requests, os, httpx, base64, time, subprocess
from discord.ext import commands, tasks
from colorama import Fore, init
from discord.utils import get
import datetime
from datetime import datetime
from cgitb import text
init(convert=True) myimports
just do this
from discord.ext import commands
bot=commands.Bot(command_prefix=...., intents=discord.Intents.all())
if (datetimenow - message.created_at).total_seconds() >= length_of_seconds:
~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~
TypeError: can't subtract offset-naive and offset-aware datetimes
ok
And if u can't able to execute command here u have to fix intent like
!intents
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.
Like this
message is : message = await channel.fetch_message(channel.last_message_id)
i am not familiar with this error, so I can't help mate sorry 🤧
for some reason it works with py 3.9 but doesn't work with 3.10 and 3.11
ok
how would i do it with pycord
@bot.slash_command(name="help", description="Helps you understand how the commands work.")
AttributeError: 'Bot' object has no attribute 'slash_command'. Did you mean: 'add_command'?
fixed already
AttributeError: 'Bot' object has no attribute 'slash_command'. Did you mean: 'add_command'?
trying to use pycord
but have dpy imports
!pycord
You probably have both discord.py and pycord installed
i have it install but not imported
Yes but it still conflicts because they have the same namespace
ok
Either uninstall pycord (recommended)
Or uninstall discord.py (not recommended)
@app_commands.describe(invite= "")
isnt that how i addd options? for slash command?
No..? This just sets descriptions
Is there an example on how to add an option
Nvm
I got it
I just love the first sentence lmao
Local pycord hater
And for the record, the module name is py-cord not pycord
Imagine running pip uninstall pycord only to see the module was never installed
Imagine pip install py-cord but import pycord doesn't work
Lmao
whats the command to get a user’s profile picture and display it
!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").
What is tid
The error says exactly what the problem is
idk how to fix
!e
"".send()
@naive briar :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: 'str' object has no attribute 'send'
It's just basic Python
so what do i have to write to fix
What are you trying to do
from discord.utils import get
tid = get(interaction.guild.channels, name=f"ticket-{interaction.user.name}")
await tid.send(.....)
This should work
Maybe he is trying to get a ticket channel with the interaction username on it then sending specific message on that ticket
ty
how come only the “litecoin” button is sent, but not the “bitcoin” button
You named both of your functions 'option'
@slate swan
how do i use interaction_check
Wdym how do you use?
It's a check that returns True by default; if it is not true then don't process the command.
forget that, do you how i can delete multpiple embeds generated when a button is clicked multiple times
Do u still want to know?
It is good yo know, because sometimes we don't want other ppl to interact out buttons that we got using cmd
Whats better discord.py or pycord
yeah, its fine for starters
both Library support all latest features
difference is mostly library abstractions
and pycord code quality 👎
Both libraries are hard for starters, py-cord has some wierd things and is overall less supported. People here code mostly in Discord.py. There are also a lot of design flaws in py-cord.
It depends what you mean by "starter" if you have some experienced with other languages it's doable.
ok
^
use d.py
0xFF0000, the format being RRGGBB
255 would be equivalent to 0x0000FF, hence blue
💀 raw embed payload
yea
can someone help me make a bot that prints messages in channels that i choose? (and the message needs to be repeated from time to time)
!d discord.ext.tasks.loop
@discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
for repeating the send^
!d discord.Client.get_channel for getting the channel and sending message using.send
get_channel(id, /)```
Returns a channel or thread with the given ID.
Changed in version 2.0: `id` parameter is now positional-only.
make sure to start the task after the cache is ready
Cooo
@slate swan
Do u know where i can learn python commands?
Like installing packages deleting eyc
Those ik
I want to go deeper 💀
you mean pip commands?
maybe
Btw is pip command can be used in Windows too?
https://pip.pypa.io/en/stable/cli/pip/
this is for pip
ofcourse
Oh shi-
I was on dark of the world then 💀
Thanks brother
i use poetry tho
Poetry?
Built in py command?
I mean like idk
Why the heck me bad at explanation uff
!pypi poetry its a package manager
Btw do u know "cat" commands?
I c
Where do I ask doubts
I use it to create files lol
Ye
not very familiar
cat > file.txt
Run it on terminal = it will create a file as file.txt xd
Kinda cool
here if its discord bot related.
#❓|how-to-get-help for claiming a help channel of your own
i just do touch file.txt
Ig i am still in dark side 💀
Need to follow the light shit
I am backdated
@slate swan imma ask 1 more ques ;-;
surely
From which country are u? Sorry if it goes personal
im from india lol, nothing personal most people guess it from my name itself cause its a hindi word
Guessed it from ur name coool
Some ppl take this thing personal thats why
idm
:]
U can indent in same line or move it outside the cog if u want to use this list everywhere
Xd
Can someone please explain the reason for commands with a group/without
why do you need them and what does it do
confused between no group, optional group, and groups
Slash groups or prefix groups?
slash
slash group, usually i use for to make space in slash commmand 💀
Idk how others use it
looks like bot isn't defined but hard to say without more code
also, you should be creating ClientSessions instead coroutines
Why tf did i misread ses 💀
you could just have a switch case in your sub command ig
idk if u can put a sub in a sub
Uh I uhh will just go
You tell the discord gateway what events you want to subscribe to
So it doesn't flood you with useless information you won't use
!intents
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.
and how i choose the infomations i need?
I imported py from discord import intents but still the same error
Capital I
Classes are PascalCased
yes i did it
Or CamelCased idr
No you have a lowercase i
you don’t import intents
wdym
!intents
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.
you stats your intents when initialising commands.Bot()
Read this embed
!d discord.ui.Button.disabled
property disabled```
Whether the button is disabled or not.
I wish the property was enabled instead of disabled
I mean just inverse it.
Well yea lol
What I meant to say that the API should have named the property the opposite because it just felt right lol
Sorry for nit picking ;-;
It's ok, someone needs to think differently, right @sick birch
Think Different
Think Like Hunter™️
sounds like an advertisement
You know what you are right
average stressed jee kid
is CockroachDB a good cloud database? (for a discord bot)
Ikr "Hunter" tf
Wanna create a Hunter™️db together?
is that a relational database
😂
hunbunDB
No thanks
hunter is shy
@maiden fable Just overwrite the global @slate swan he will disappear.
yes it supports relational SQL
you can use it but i don't really see a point of using it instead of common dbs like pgsql
😔 do i really deserve that?
lmao
It's up to Hunter I'm afraid
how do i make my bot wait for self.sender and self.reciver to click the button and then send a message
!d discord.Client.wait_for
wait_for(event, /, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.11)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.11)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.11)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/latest/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
interaction event
i don't have a host and i'm not self-hosting, guess what shit i'm using lmao
If someone would send the command, why let him or her confirm the invite? He typed in the command and the person to invite.
thats gonna work? for my situation?
Does wait_for really provide a good solution here?
i dont think it does lol
Anyhow, any reason for the confirm button for the sender?
that works for every situation but there can be easier ways
I'd just make it so the interaction can only be confirmed by the receiver.
End the View when pressed.
depends on their code structure, they could store if the sender/reciever has clicked the button or not somewhere and proceed acc to that
Then just allow 2 ID's and append the user to a list. Also easily scalable.
sqlite3 exists 
and there;s pgsql hosts online too ( like railway )
i have self.sender and self.reciver for that?
ah, then I'll look into it
I meant having all the mentioned, including the author, to be in the check.
wdym
new_msg = await channel.fetch_message(my_msg.id)
users = await new_msg.reactions[0].users().flatten()
n = 0
for _ in range(num_of_winners):
users.pop(users.index(self.bot.user))
winner = random.choice(users)
await channel.send(f"Congratulations! {winner.mention} won the prize: {prize}!")
```how can i change this section of code so that i can filter out the bot's id when it randomly selects a user?
To wait just append the member to a list or have a bool that says if he/she joined (hardcoded).
wdym by append
Ancient code 
Well I was thinking if you wanted like 10 participants it's easier to scale but if you want just 2 people a bool is fine.
theres only 2
do u want to see my bot?
flatten isn't a thing anymore, when you are going to check for emoji always specify it not just index at 1st. Thirdly use the filter() function.
If you think it helps solving the issue.
dms
filtered = list(filter(self.bot.user, users))
n = 0
for _ in range(num_of_winners):
filtered.pop(filtered.index(self.bot.user))
winner = random.choice(users)
await channel.send(f"Congratulations! {winner.mention} won the prize: {prize}!")
```i tried this, but got the error
`TypeError: 'ClientUser' object is not callable`
how would i filter out the bot?
dmed u invite
The first arg should be a callable
Like lambda
And it should return bool obj
Or just use list comp
my slash command no appeare 💀 ]
Are you using dpy
I used discord-py-interactions
that library is no longer maintained
dangit
You need to get the list of users that reacted. And yeah I agree switch to dpy.
it worked one week ago and then stopped working that very day
Also reminder that any unmaintained dpy fork, or a library that is using V7, at new year, those are going to be disabled.
@slashbot.command(
name="Username",
description="Get a random Username. ",
scope = 1043711872723070976
)
async def betauser(ctx: interactions.CommandContext):
z = randint(0,len(name_list) - 1)
za = randint(0, len(title_list) - 1)
url = "https://www.mit.edu/~ecprice/wordlist.10000"
page = urlopen(url)
html_bytes = page.read()
html = html_bytes.decode("utf-8")
wordlist = html.split('\n')
name = []
if randint(0,1) == 1:
name.append(wordlist[randint(1, len(wordlist) - 1)])
name.append(wordlist[randint(1, len(wordlist) - 1)])
else:
if randint(0,1) == 1:
name.append(str(name_list[z]))
name.append(wordlist[randint(1, len(wordlist) - 1)])
else:
if randint(0,1) == 1:
name.append(wordlist[randint(1, len(wordlist) - 1)])
name.append(str(name_list[z]))
else:
if randint(0,1) == 1:
name.append(str(name_list[z]))
name.append(str(title_list[za]))
else:
if randint(0,1) == 1:
name.append("The_Legend_of")
else:
name.append("The_Secret_of")
name.append(str(name_list[z]))
print("Generated")
random = randint(0,5)
if random == 1:
usernamec = (name[0] + '_' + name[1] + str(randint(1, 9)))
elif (random == 2):
usernamec = (name[0] + '_' + name[1] + str(randint(10,99)))
elif (random == 3):
usernamec = (name[0] + '_' + name[1] + str(randint(100,999)))
elif (random == 4):
usernamec = (name[0] + '_' + name[1] + str(randint(1000,9999)))
elif (random == 5):
usernamec = (name[0] + '_' + name[1] + str(randint(10000,99999)))
else:
usernamec = (name[0] + '_' + name[1])
await ctx.send('Username: ' +usernamec , mention_author=True)
the relevant part
import discord
import os
import interactions
from keep_alive import keep_alive
from discord import client,Intents
from discord.ext import commands
from lists import name_list, title_list,spamton
from urllib.request import urlopen
from random import randint
import logging
intents = discord.Intents.defa
What the
wgat
If you are still using v8 or lower: this is a reminder that your bot will stop working by the end of the year unless you update. Discord is going to remove v8 and below at the end of the year, which v1.7.3 and below use. Please update and migrate to v2 as soon as possible.
These are the latest versions using v8:
Discord.py 1.7.3
Nextcord: Not affected (Discord.py 1.7.3)
Disnake: 2.2.*
Py-cord: 2.0.0a
You can find the migration guide here: https://discordpy.readthedocs.io/en/stable/migrating.html
ok
Who has the script for a ticket bot for me?
GitHub most likely.
Tfw
Didn't realize 1.7.3 was going to stop working completely
I mean it seems like discord API versions are backwards compatible
So maybe just update the base version URL to something not deprecated? Of course it won't have the new features but all the old features will still work fine
Well they just don't want to keep supporting it, which is fair as v11 is almost out.
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
Don't use f-strings for db queries or stuff like that 
what code editor is that
new_msg = await channel.fetch_message(my_msg.id)
users = await new_msg.reactions[0].users().flatten()
filtered = []
for x in users:
if self.bot.get_user(937219050365386782) not in x: #CHECKS IF THE USER IS NOT THE BOT
filtered.append(x)
for _ in range(int(answers[3])):
filtered.pop(filtered.index(self.bot.user))
winner = random.choice(filtered)
await channel.send(f"Congratulations! {winner.mention} won the prize: {prize}!")
0|Runa | ret = await coro(*args, **kwargs)
0|Runa | File "/home/Runa/bot/cogs/giveaway.py", line 128, in giveaway
0|Runa | if self.bot.get_user(937219050365386782) not in x:
0|Runa | TypeError: argument of type 'Member' is not iterable
can someone help me with this error please? i am trying to create a giveaway that allows multiple winners. it creates a new list of the users who reacted and then removes the bot from the list of winners it can randomly choose from
That's a very inefficient way of filtering things
what would you suggest?
!list-comp
Do you ever find yourself writing something like this?
>>> squares = []
>>> for n in range(5):
... squares.append(n ** 2)
[0, 1, 4, 9, 16]
Using list comprehensions can make this both shorter and more readable. As a list comprehension, the same code would look like this:
>>> [n ** 2 for n in range(5)]
[0, 1, 4, 9, 16]
List comprehensions also get an if clause:
>>> [n ** 2 for n in range(5) if n % 2 == 0]
[0, 4, 16]
For more info, see this pythonforbeginners.com post.
You can check if the user is the bot or not with it
Like
!e
class User:
def __init__(self, uid: int):
self.id = uid
def __repr__(self):
return f"User({self.id})"
users = [User(uid=i) for i in range(10)]
print("Before:", users, end="\n\n")
users = [user for user in users if user.id != 4] # keep every element if its id is not 4
print("After:", users)
@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | Before: [User(0), User(1), User(2), User(3), User(4), User(5), User(6), User(7), User(8), User(9)]
002 |
003 | After: [User(0), User(1), User(2), User(3), User(5), User(6), User(7), User(8), User(9)]
or just use filter
list.remove(bot.get_user(bot_id))
indeed
tbh I'd play with user ids instead of User objects cause thats all you'll need here
Average Hikari user
Oh wait

that worked! thank you so so much
my bot isnt receiving gateway events:```py
async def _receiveevent(self):
await asyncio.sleep(10)
try:
while True:
event = await self.ws.receive()
if event.type in (aiohttp.WSMsgType.CLOSE,aiohttp.WSMsgType.CLOSED,aiohttp.WSMsgType.CLOSING):
await self._handleclose(event)
return
event = event.json()
self.lasts,self.op = event['s'],event['op']
if self.op == 11:
self.logger.debug('received heartbeat ACK')
if self.op == 1:
await self._immediate()
if self.op == 0:
await self._handleevent(event)
except KeyboardInterrupt:
await self.ws.close()
async def _handleevent(self,data):
self.logger.debug('event received')
if data['t'] == 'READY':
await self._ready(data)
else:
self.logger.debug(data)
await self._client.handle(data['t'],data['d'])
use async for event in self.ws instead of that while True loop maybe
you also have a sleep period of 10 seconds, did you wait till that time?
weird question, but how would i make a boldify command, pretty much when i use the command any letter i put turns bold. I don't mean bold as in bold i mean as in the font bold like 𝗔𝗕𝗖
how can i do that?
but the ready event was received
what intents do you have
its not documented because the async for is implemented using dunders
aiohttp/client_ws.py lines 316 to 323
def __aiter__(self) -> "ClientWebSocketResponse":
return self
async def __anext__(self) -> WSMessage:
msg = await self.receive()
if msg.type in (WSMsgType.CLOSE, WSMsgType.CLOSING, WSMsgType.CLOSED):
raise StopAsyncIteration
return msg```
all
you'll have to keep updated the d field of Heartbeats you send to discord with the count of dispatches
i did in the other function
i am using the discord menus extension (https://github.com/Rapptz/discord-ext-menus) and it wont add reactions to my message.
I have traced it down to this below code hanging within the module source code. Why and how can I fix it? Could it be to do with the fact that I am using asyncio tasks incorrectly myself?
in self._client.handle?
in the function that sends heartbeat
but isnt it just the sequence number
the sequence number would be increased per dispatch, and you arent doing that ig
The inner d key is the last sequence number—s—received by the client. If you have not yet received one, send null.
sourc
!d discord.app_commands.AppCommand.name_localizations
The localised names of the application command. Used for display purposes.
What is this used for?
Hello, when I use member.timeout(until=None) on a timed-out member it raises TypeError. The docs say that the until parameter accepts datetime or timedelta objects as a timeout duration, but it also says that passing None will remove the current timeout on the member. Am I missing something here?
Check if the member is actually timed out
I am using an alt and timing the account out immediately before running the command, so yes they are timed out.
Edit: This is fixed, I just needed to pass None instead of until=None.
with member.timeout() you usually do that because until is a positional argument, with member.edit() you can set timed_out_until to None to have the same effect
Whats the best way to tabulate data within discord?
My database entry has 10 attributes, and there could be many entries that show on a query
You could either use PIL to create an image with a table and some text, or go with Discord embeds, or just plain text and use your text formatting skills
That's all I know you could do. However, I'm sure there might be a module out there that would assist you
BIGINT
also u can store datetime objects in sql or use BIGINT and store timestamps why text?
that too why are u creating table for each member also dont think u can have a numerical as a table needs a name
also no sql and f strings together
How can I sync all my commands that are in cogs
Load the cogs and just sync the tree normally
{'t': None, 's': None, 'op': 11, 'd': None} is all i received in heartbeat ack
async def _on_connect_ws(self,identity):
self.logger.debug('connected to wss')
hello = await self.ws.receive()
hello = hello.json()
if hello['op'] == 10:
self.logger.debug('hello received')
if hello['op'] == 9:
await self._connect(self.url)
self.logger.debug(hello)
self.delay = hello['d']['heartbeat_interval']
if identity:
await self._identity()
asyncio.create_task(self._receiveevent())
while True:
data = {
"op":1,
"d":self.lasts
}
await self.ws.send_json(data)
self.logger.debug('sent heartbeat')
await asyncio.sleep(self.delay/1000)
```is how i send heartbeat
and the bot did stay online
whats t and s?
the event
good one
and s?
sequence number...
whats that?
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
cmon ur in discord bot help and u dont know this
ohhh
lol yea
i dont really get what ur tryina fo
*do
whats is Bot.pool?
A lock?
I got a checkmark for my bot in just 30 minutes wtf it took 2 months last time
isnt that like 20 bucks or smth?
That's not twitter bro
Using pycord
@bot.slash_command(guild_ids=[813967937038974997], name='shipping', description='Calculate shipping costs on sugargoo for your specified country & weight')
async def shipping(ctx,
country: Option(
str,
name="country",
description="Country you are shipping to",
autocomplete=countries
),
countries is a list of country names (every country)
Traceback (most recent call last):
File "C:\Users\elich\PycharmProjects\sugargoobot4\venv\lib\site-packages\discord\bot.py", line 856, in callback
return await command.invoke_autocomplete_callback(ctx)
File "C:\Users\elich\PycharmProjects\sugargoobot4\venv\lib\site-packages\discord\commands\core.py", line 996, in invoke_autocomplete_callback
if len(inspect.signature(option.autocomplete).parameters) == 2:
File "C:\Users\elich\AppData\Local\Programs\Python\Python39\lib\inspect.py", line 3118, in signature
return Signature.from_callable(obj, follow_wrapped=follow_wrapped)
File "C:\Users\elich\AppData\Local\Programs\Python\Python39\lib\inspect.py", line 2867, in from_callable
return _signature_from_callable(obj, sigcls=cls,
File "C:\Users\elich\AppData\Local\Programs\Python\Python39\lib\inspect.py", line 2242, in _signature_from_callable
raise TypeError('{!r} is not a callable object'.format(obj))
TypeError: ['Albania', 'Algeria', 'Andorra', 'Angola', 'Anguill... (this goes on but message length limit)] is not a callable object
I get that when I try to use the command
and it doesn't autocomplete
It works fine when I return the exact same list from a coroutine
what is countries
you still don't do that
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
discord.utils.setup_logging()
@bot.event
async def setup_hook() -> None:
print("Syncing bot...")
await bot.tree.sync()
async def main():
for _folder in os.listdir("./commands/bot"):
for _file in os.listdir(f"./commands/bot/{_folder}"):
if _file.endswith(".py"):
await bot.load_extension(f"commands.bot.{_folder}.{_file[:-3]}")
async with bot:
await bot.start(config.tokens.bot)
if __name__ == "__main__":
asyncio.run(main())
edit the message
shouldnt this run setup_hook automatically?
What do you mean?
It is not an event
It's a method of the client class
And commands.Bot is a subclass of Client btw
right
how do i remove an old command? I synced the bot but it still shows the old parameters
To my experience, it disappears automatically after some time, but you may try to make a request to certain API endpoint that removes the command
Maybe that's library-specific tho, I use disnake
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
Cul
Can someone help? My bot isn't online.
import nextcord
from config import TOKEN
import os
import wavelink
bot = commands.Bot(command_prefix='!')
@bot.event
async def on_ready():
print("Bot is up and ready!")
bot.loop.create_task(node.connect())
@bot.event
async def on_wavelink_node_ready(node: wavelink.Node):
print(f"Node {node.identifier} is ready!")
async def node_connect():
await bot.wait_until_ready()
await wavelink.NodePool.create_node(bot=bot, host='node5.lavalink.trgop.gq', port=443, password='htandsm', https=True)
@bot.command()
async def play(ctx: commands.Context, *, search: wavelink.YoutubeTrack):
if not ctx.voice_client:
vc: wavelink.Player = await ctx.author.voice.channel.connect(cls=wavelink.Player)
elif not ctx.author.voice_client:
return await ctx.send("First join a Voicechannel")
else:
vc: wavelink.Player - ctx.voice_client
vc.play(search)
bot.run(TOKEN)```
No but my bot isn't online
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.
from nextcord import Intents
intent=Intents.default()
intent.message_content=True
bot=command.Bot(intent=intent)
Like this?
import nextcord
from config import TOKEN
import os
import wavelink
from nextcord import Intents
intent=Intents.default()
intent.message_content=True
bot=command.Bot(intent=intent)
bot = commands.Bot(command_prefix='!')
@bot.event
async def on_ready():
print("Bot is up and ready!")
bot.loop.create_task(node.connect())
@bot.event
async def on_wavelink_node_ready(node: wavelink.Node):
print(f"Node {node.identifier} is ready!")
async def node_connect():
await bot.wait_until_ready()
await wavelink.NodePool.create_node(bot=bot, host='node5.lavalink.trgop.gq', port=443, password='htandsm', https=True)
@bot.command()
async def play(ctx: commands.Context, *, search: wavelink.YoutubeTrack):
if not ctx.voice_client:
vc: wavelink.Player = await ctx.author.voice.channel.connect(cls=wavelink.Player)
elif not ctx.author.voice_client:
return await ctx.send("First join a Voicechannel")
else:
vc: wavelink.Player - ctx.voice_client
vc.play(search)
bot.run(TOKEN)```
Uhhh
add intent=intent in ur bot variable
like
commands.Bot(command_prefix="!", intent=intent)
Like this?
from nextcord.ext import commands
import nextcord
from config import TOKEN
import os
import wavelink
from nextcord import Intents
intent=Intents.default()
intent.message_content=True
bot = commands.Bot(command_prefix='!',intent=intent)
@bot.event
async def on_ready():
print("Bot is up and ready!")
bot.loop.create_task(node.connect())
@bot.event
async def on_wavelink_node_ready(node: wavelink.Node):
print(f"Node {node.identifier} is ready!")
async def node_connect():
await bot.wait_until_ready()
await wavelink.NodePool.create_node(bot=bot, host='node5.lavalink.trgop.gq', port=443, password='htandsm', https=True)
@bot.command()
async def play(ctx: commands.Context, *, search: wavelink.YoutubeTrack):
if not ctx.voice_client:
vc: wavelink.Player = await ctx.author.voice.channel.connect(cls=wavelink.Player)
elif not ctx.author.voice_client:
return await ctx.send("First join a Voicechannel")
else:
vc: wavelink.Player - ctx.voice_client
vc.play(search)
bot.run(TOKEN)```
Step 1: learn basic python
also in
bot.loop.create_task(node.connect())
But there is no node variable i see 💀
Someone help
I want my slash command user to have certain permissions to use the slash command.
Are u using discord.py?
If yes i can help
!d discord.app_commands.checks.has_permissions
@discord.app_commands.checks.has_permissions(**perms)```
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 has all of the permissions necessary.
Note that this check operates on the permissions given by [`discord.Interaction.permissions`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction.permissions "discord.Interaction.permissions").
The permissions passed in must be exactly like the properties shown under [`discord.Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions "discord.Permissions").
This check raises a special exception, [`MissingPermissions`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.MissingPermissions "discord.app_commands.MissingPermissions") that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CheckFailure "discord.app_commands.CheckFailure").
New in version 2.0...
!d discord.app_commands.default_permissions
@discord.app_commands.default_permissions(**perms)```
A decorator that sets the default permissions needed to execute this command.
When this decorator is used, by default users must have these permissions to execute the command. However, an administrator can change the permissions needed to execute this command using the official client. Therefore, this only serves as a hint.
Setting an empty permissions field, including via calling this with no arguments, will disallow anyone except server administrators from using the command in a guild.
This is sent to Discord server side, and is not a [`check()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check "discord.app_commands.check"). Therefore, error handlers are not called.
Due to a Discord limitation, this decorator does nothing in subcommands and is ignored.
Here is two
@slate swan thanks for your help!
python3 main.py
Traceback (most recent call last):
File "main.py", line 7, in <module>
IP_address = str(sys.argv[1])
IndexError: list index out of range
IP_address = str(sys.argv[1])
i cant type message in terminal
you're running a bot? to stop the Bot press ctrl + c or open a new terminal (with the +) to type cmds
ye ik
but i want to remove that

