#discord-bots

1 messages · Page 144 of 1

naive briar
#

!intents

unkempt canyonBOT
#

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.

vocal snow
#

ctrl+shift+-

slender stirrup
#

can i access message if i store message.id when it deleted

upbeat otter
upbeat otter
#

unless you have that message in cache (if your lib allows that) or you can store every message (not recommended)

amber ether
#

what the hell is a tuple

upbeat otter
#

!resources

unkempt canyonBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

amber ether
#

!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!**')```
unkempt canyonBOT
#

@amber ether :x: Your 3.10 eval job has completed with return code 1.

001 |   File "<string>", line 3
002 | SyntaxError: 'await' outside function
amber ether
#

!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!**')```
unkempt canyonBOT
#

@amber ether :x: Your 3.11 eval job has completed with return code 1.

001 |   File "<string>", line 3
002 | SyntaxError: 'await' outside function
amber ether
#

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???
slate swan
#

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.

simple kettle
#

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

unkempt canyonBOT
#

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))```
simple kettle
#

ah ok

#

thanks

slate swan
#

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

simple kettle
#

is there a way for the discord bot to respond to buttons even if it was restarted?

slate swan
#

If u talk about difficulty i would say average

simple kettle
#

how would i do it?

slate swan
#

Then
in on_ready event
add extra line,
bot.add_view(myclass())

#

@simple kettle check that out

slate swan
simple kettle
slate swan
#

like
class button(discord.ui.View:
#othercodes

naive briar
#

Syntax error

slate swan
#

Then the class will be
button
bot.add_view(button())

slate swan
naive briar
#

And every items in the view must have a custom_id set

slate swan
#

Lol thanks for mentioning that

slate swan
# slate swan 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.

ember nest
#

Why there is 2 of my /say command

slate swan
ember nest
#

Nah

slate swan
#

Then maybe glitch

simple kettle
# slate swan Then the class will be button bot.add_view(button())

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

ember nest
#

How to fix lol

ember nest
#

Btw will u help me fix my reaction problem ? @slate swan

simple kettle
slate swan
#

Maybe u forgot to check

#

!d discord.Button

polar dawn
#

how do i sends out custom emoji through discord bots?

#

the \ method doesnt work tho

slate swan
polar dawn
#

it doesnt work tho

naive briar
#

It does

slate swan
#

The emoji should be or must be in that server where the bot in

slate swan
#

Yes

polar dawn
slate swan
#

:]

weary flume
#

is there a way to give someone a certain role from another server?

slate swan
#

!d discord.Guild.get_role

unkempt canyonBOT
#

get_role(role_id, /)```
Returns a role with the given ID.

Changed in version 2.0: `role_id` parameter is now positional-only.
safe zinc
#

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

tough lance
#

Any way to find number of messages that a user has in a given time?

maiden fable
#

!d discord.TextChannel.history

unkempt canyonBOT
#

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...
simple kettle
#

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

naive briar
#

send_message doesn't return the sent message

simple kettle
#

oh, is there a work around for this

naive briar
#

!d discord.Interaction.edit_original_response

unkempt canyonBOT
#

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.
simple kettle
#

oh nice, thank you

safe zinc
#
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

fading marlin
#

!intents

unkempt canyonBOT
#

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.

fading marlin
#

you gotta enable message content

safe zinc
#

ohh

maiden fable
#

can you please paste the code....?

slate swan
#

@fading marlin

fading marlin
#

yes?

slate swan
# 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

safe zinc
fading marlin
fading marlin
slate swan
safe zinc
#
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?

fading marlin
safe zinc
#

i ran it and it gave a crap ton of errors

#

wait wat

#

lez goooo

#

it worked

fading marlin
slate swan
fading marlin
#

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

short pulsar
#

hm

slate swan
#

however i need my bot to delete both the embeds made it only deletes one

fading marlin
#

because you're not storing the first one

short pulsar
#
@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

fading marlin
#

you're not responding fast enough

#

defer the interaction, purge, and then send a followup

slate swan
short pulsar
#

i literally started like 1 week ago

#

it actually works, just i need a message.

#

it shows up as "the application did not blahblahblah"

naive briar
#

!d discord.InteractionResponse.defer - You need to defer the interaction if you need to take over 3 seconds to respond

unkempt canyonBOT
#

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...
naive briar
#

Then respond to it later using followup

short pulsar
#
@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

shrewd apex
#

spoon feeding time pithink i think

short pulsar
#

😭

slate swan
shrewd apex
#
@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.")
slate swan
#

no, your just new lol

shrewd apex
#

bruh commands. has perm don't work on slash

short pulsar
#

no im stupid in maths

#

and social studies <3

#

and 100 in computer studies <3

slate swan
#

where did lee go

short pulsar
#

uhm

#

he got milk

#

my bot just crashed 😭

slate swan
#

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?

primal token
primal token
# short pulsar im stupid <3

“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

#

🦦

slate swan
#

yes therefore climbing trees is stupid

primal token
#

😡

sick birch
primal token
#

talking about monkeys, one appeared

short pulsar
#

🐒

#

pic of me omg

sick birch
#

A wild monkey has appeared

primal token
#

since when could monkeys talk

flint isle
#

how can i hard code the bot to send a message to me directly?

#

oh wait i probially have a simmilar line of code facepalm

#

yep found it

GUILD_ID = 798726719573065749
    CHANNEL_ID = 798726720181633047
    location = bot.get_guild(GUILD_ID).get_channel(CHANNEL_ID)
    await location.send(embed=embed)
primal token
#

you dont need to get the guild

flint isle
#

yeah i didnt mean to copy that line lol

primal token
#

!d discord.ext.commands.Bot.get_channel

unkempt canyonBOT
cinder tulip
#

yet here i am back again, this time the problem are the cogs

#

main.py:

import music

#COGS
cogs = [music]

for i in range (len(cogs)):
  cogs [i].setup()

music.py:

class music(commands.Cog):
  def __init__(self, client):
    self.client = client

#COMMANDS

def setup(client):
  client.add_cog(music(client))
primal token
#

just use Bot.load_extension which handles it all, including getting the module object

#

!d discord.ext.commands.Bot.load_extension

unkempt canyonBOT
#

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)").
flint isle
primal token
flint isle
#

but yes

primal token
#

then you would use that instance to acess that method

flint isle
#

hmm? i dont understand

primal token
#

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

flint isle
#

so self.bot.get_channel(id)

primal token
#

yep

flint isle
#

and how do i get the id that my bot would use to dm me

primal token
#

it could raise an error, so i would also be cautious by adding a check

primal token
unkempt canyonBOT
primal token
#

!d discord.ext.commands.Bot.application

unkempt canyonBOT
#

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.
flint isle
#

ima print that to see what it outputs
so print(disnake.AppInfo.owner) ? to see its output

naive briar
#

That's not a gif

primal token
#

discord uses tenor

naive briar
#

Send the error

primal token
#

You cant mention users in a embed title

#

Neither did i

weary flume
#
@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

primal token
weary flume
#

np

primal token
#

The mention wont get formatted

weary flume
#

i dont think u can

primal token
#

Discord doesnt let you mention anything in a embeds title

weary flume
#

just remove the title and put it in description ig

#

the description would look like the title

primal token
#

It wont ping the user but it would mention them

unkempt canyonBOT
sick birch
weary flume
primal token
#

real funny

sick birch
#

You're welcome

#

The funny man has arrived

primal token
#

you're not funny, you're just a clown

sick birch
primal token
#

You're using Context.author which returns User | Member

grand willow
#

U forgot to add the user ur gona slap

async def slap(ctx, user : discord.Member)
primal token
#

then you can use discord.User.name or discord.Member.name, its the same since discord.Member.name derives the attribute from the superclass

grand willow
#

than just {user.mention}

#

Np

primal token
#

I cant stand the level of intelligence in this chat, its insane

#

🦦

#

Do i need to repeat myself?

grand willow
#

Where?

primal token
#

Show your code

grand willow
#

U cant mention ppl in a embed title or title of a field

primal token
#

cant*

grand willow
#

Yeah my bad

primal token
#

show your codepithink

#

Catgal take my spot, I'm wasting my time trying to helpducky_party

naive briar
unkempt canyonBOT
primal token
#

ctx.author.name, and you cant mention a user in a field name

grand willow
#

Sorry, i tought u used it in a description

primal token
#

You cant mention a user in a title🦦

primal token
#

then what is it?

grand willow
#

user.name and user.discriminator

primal token
#

no

#

just use the objects __str__ dunder

#

!e

import attrs

@attrs.define
class Foo: ...

print(Foo())
unkempt canyonBOT
#

@primal token :white_check_mark: Your 3.11 eval job has completed with return code 0.

Foo()
weary flume
#
@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

slate swan
#

guild.get_member takes a user id, not a user object

#

you also have a faulty error handler if you get no errors

bitter jewel
#

is it possible to change bot status using a loop ? like every 10 seconds he updates the presence

slate swan
#

yes, but not recommended

bitter jewel
#

why not

slate swan
#

ratelimits

#

you will get ratelimited by the discord API

bitter jewel
#

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

honest shoal
#

is your bot small/private

bitter jewel
#

yes

#

is private

honest shoal
#

then it's not a problem tbh

bitter jewel
#

but discord will not rate limit me if i update status every 10 seconds?

honest shoal
#

no

#

you can make upto 50 requests per second

bitter jewel
#

good to know, thanks

slate swan
slate swan
#

its an Gateway event

#

doesn't matter if your bot is in 100k guilds or no guilds at all

primal token
#

I dont really see the purpose of limiting your gateway events because you want your bots status to change

bitter jewel
#

bot status changing = swag

primal token
#

sure

slate swan
#

noone even checks your bot's status other than you yourself;-;

bitter jewel
#

every dev wants fancy shit on his project

slate swan
#

by you im not targetting a particular but everyone

primal token
#

Most devs sadly dont know even what theyre doing

bitter jewel
#

who does

#

im creating shit just bcs i got so much time

primal token
#

I really wouldnt follow what anyone does, be creative and make unique things, that how you will see your bots popularity get bigger

bitter jewel
#

create a bank bot for dabloons = ez verified bot

flint isle
primal token
primal token
#

it will make you cooler😎😳

slate swan
#

"open for commissions"

primal token
slate swan
#

hosted on replit

bitter jewel
#

for txt db bot

primal token
#

😳😳

bitter jewel
#

hosted on my pc

slate swan
#

txt? grow up and use pickle

primal token
#

It's sad seeing people do these types of things

bitter jewel
#

i used to do that on private bots i made for 2-3 persons

glad cradle
#

use the cache as db

bitter jewel
#

u dont need a db for 3 people who got no idea what they r doing

slate swan
#

omw to use discord.py's internal cache as my database

primal token
#

Its funny though, i questioned one of them in front of a group of people, the dude was so embarrassed felt great🦦

bitter jewel
#

i mean who need a db

primal token
#

^

glad cradle
bitter jewel
#

just login on bot account and count the things by urself

#

ur a whole db

slate swan
primal token
#

Just use ctypes and allocate the memory yourself

primal token
bitter jewel
#

who needs a bot, u can become the bot...

primal token
slate swan
glad cradle
slate swan
#

logging into my bot account within my terminal

primal token
primal token
#

snipy also helped me🦦

glad cradle
bitter jewel
primal token
flint isle
# primal token ```py print(bot.application.owner.id) ``` Its vulnerable to attribute errors tho...

    @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'
slate swan
#

was just messing with a friend

primal token
#

hehe

slate swan
#

not actually made my me, it was a lightbulb extension

bitter jewel
primal token
#

!d discord.Client.application_info

glad cradle
unkempt canyonBOT
#

await application_info()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Retrieves the bot’s application information.
bitter jewel
#

ssh ?

slate swan
#

also an await-able

bitter jewel
#

what happened

slate swan
bitter jewel
#

i know

#

ohh

glad cradle
bitter jewel
#

yes

primal token
#

bro is packing muscle

bitter jewel
#

i was thinking snipy used "ssh" as a bot prefix

fading marlin
#

thru

glad cradle
#

bro
repo name: pycord-ssh-client
main name: bot.py
and finally client = commands.Bot

Nice names

bitter jewel
#

smart

#

i dont let people know my next move

glad cradle
#

You were undecided

unkempt canyonBOT
#

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")```
primal token
#

😏

slate swan
#

roblox

glad cradle
#

aaaa

glad cradle
slate swan
#

:exit:

bitter jewel
#

smart

primal token
#

Snipy play roblox with me

slate swan
glad cradle
bitter jewel
#

send gamepass

primal token
glad cradle
honest shoal
bitter jewel
primal token
glad cradle
glad cradle
#

you want to edit that message to remove something from the embed right?

primal token
#

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

slate swan
#

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?

bitter jewel
#

im millionaire on it

glad cradle
#

he needs to fetch the message

primal token
honest shoal
bitter jewel
slate swan
honest shoal
primal token
bitter jewel
#

nah

slate swan
#

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. 🙂

bitter jewel
#

is real

honest shoal
#

not even transferable

fading marlin
bitter jewel
#

u can transfer it to someone else on ropsten

glad cradle
#

@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

primal token
#

i always have battery saver off when im not on low battery due to performance issues

slate swan
#

i use my phone only for calls and discord sometimes so performance is not really an issue for mw

primal token
#

call me

glad cradle
slate swan
glad cradle
#

!d discord.Message.embeds

unkempt canyonBOT
glad cradle
#

!d discord.Message.clear_reaction

unkempt canyonBOT
#

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`.
glad cradle
primal token
glad cradle
#

I was in serious mode for some seconds

primal token
#

relatable

slate swan
#

imma create the most verbose discord api wrapper 😏

primal token
slate swan
#

im using mypy on strict so im hoping so

primal token
#

the heck

slate swan
#

that complaining bitch

glad cradle
primal token
slate swan
primal token
glad cradle
#

You can do better

slate swan
#

ClassCreatedWithResolovedFieldOfTheApplicationCommandInteractionPayload

primal token
#

talking about linters, pylance never screams at me, maybe im just too good🥶

primal token
primal token
slate swan
#

on the top of file

glad cradle
primal token
#

ive used pyright it wasnt hard tho

primal token
slate swan
#

if you know typing nothing's hard

primal token
slate swan
#

the most annoying part in typing is decorators

glad cradle
primal token
#

😔

#

it's just crying because it cant trace types that's all

glad cradle
#

Who uses the strict mode

slate swan
#

typing decorators be like ```py
) -> typing.Callable[[typing.Callable[..., typing.Awaitable[typing.Any]]], EventListener]:

primal token
#

just declare a type, ez

slate swan
glad cradle
slate swan
#

i love tans

primal token
#
import typing

Fun: typing.TypeAlias = typing.Callable[[typing.Callable[..., typing.Awaitable[typing.Any]]], EventListener]

😳

glad cradle
#

Fun

slate swan
#

typealias is 3.9+ ig?

primal token
#

3.10+

slate swan
#

yeah can't use, the library is 3.8+

#

i tried using Typevar but it supports only generics

primal token
#

just use stubs

glad cradle
#

classic Noid that suggest unsupported features

primal token
#

😔

#

sad how he's 100% right

glad cradle
slate swan
#

i can just stop 3.8 and 3.9 support

#

3.10 is already stable

glad cradle
#

I would suggest supporting at least Python 3.9 as well

primal token
#

i would suggest not listening to snipy and going for 4.0

glad cradle
#

😭

slate swan
#

tbh with the momentum im working

#

I won't complete it before 4.0

primal token
#

This update about to be crazy

torn sail
slate swan
#

3.11 looked promising about speed
but it don't feel much of a boost

slate swan
#

ty you're a lifesaver

primal token
#

who uses typing_extensions lol

slate swan
#

big L

primal token
#

Unpackage the package

slate swan
#

not gonna add a new dependency for a single line

torn sail
slate swan
#

im already using attrs cause dataclasses doesn't support kw_only arg in 3.8

primal token
#

Pretty fast non the less

polar dawn
#

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

slate swan
civic sparrow
#

How do i calculate how long a slash command took to respond?

slate swan
#

datetime.datetime.now()-interaction.created_at

civic sparrow
# slate swan 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
slate swan
#

.now shall be an timezone aware

#

discord.utils.utcnow ig

#

!d discord.utils.utcnow

unkempt canyonBOT
#

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.
slate swan
#

yea

civic sparrow
#

so datetime.datetime.now(discord.utils.utcnow())?

#

oh lol nvm im dumb

#

how do i make it timezone aware 😭

slate swan
#

discord.utils.utcnow returns a timezone aware datetime

glad cradle
glad cradle
primal token
glad cradle
#

it's a spaceshuttle

primal token
#

🚀

glad cradle
#

I want to cry on voice receiver files

sick birch
primal token
# sick birch Rust?

You talk more about rust than about python, so why not remove you from the pydis staff teampithink

sick birch
#

the pydis staff team is secretly the rustdis staff team

primal token
#

No MoRe "Staff at the python discord btw" 😿

primal token
sick birch
#

no more 19 dollar cards

primal token
#

🙀

sick birch
#

It's ctx.message

#

not message

severe rampart
#

In which case you can just do ctx.author

pliant gulch
#

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

primal token
pliant gulch
#

So you can TypeVarTuple or something like that

#

And Unpack since *Generic[...] isn't possible

#

Unless you again, upgrade versions

primal token
#

I actually havent seen the need to use it yet

pliant gulch
#

I was re-writing Rin using tuple generics

#

It makes my callbacks a lot more type-safe

primal token
#

Rin?

pliant gulch
# pliant gulch It makes my callbacks a lot more type-safe
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....

pliant gulch
slate swan
#

PepeLaugh don't change presence in on_ready.

naive briar
#

!d discord.Client

unkempt canyonBOT
#

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").
slate swan
#

@glad cradle

slate swan
weary flume
#

does anyone know places to host my bot?

slate swan
#

paid?

#

.

zenith holly
#

is there anyone here thats really good with dpy

glad cradle
hollow gazelle
#

AttributeError: 'Bot' object has no attribute 'slash_command'. Did you mean: 'add_command'?

primal token
#

What version of Discord.py do you have? Also the new version of Discord.py uses a tree and not the Bot object

hollow gazelle
#

@tree.command

primal token
hollow gazelle
#

@tree.command(name="redeem", description="redeems key for license")
NameError: name 'tree' is not defined. Did you mean: 'True'?

hollow gazelle
slate swan
#
@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

hollow gazelle
#

'Bot' object has no attribute 'slash_command'

sick birch
hollow gazelle
#

ive tried using

hollow gazelle
#

oops

#

didnt mean to @ him

sick birch
#

Can you paste your code?

hollow gazelle
#
@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

slate swan
grand willow
#

Yep

hollow gazelle
slate swan
#

it worked ty

#

stack overflow peeps got me confused ig

grand willow
#

!d discord.Member.avatar

unkempt canyonBOT
#

property avatar```
Equivalent to [`User.avatar`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.avatar "discord.User.avatar")
grand willow
hollow gazelle
#

'Bot' object has no attribute 'slash_command' using d.py but ive tried tree commands they just dont work

sick birch
slate swan
hollow gazelle
slate swan
#

tysm

grand willow
sick birch
hollow gazelle
#

it says name 'tree' is not defined

sick birch
hollow gazelle
#

bot = commands.Bot(intents=discord.Intents.all(), command_prefix=f"{prefix}")

sick birch
hollow gazelle
sick birch
#

yes

hollow gazelle
#

ok

#

module 'discord' has no attribute 'ApplicationContext'

hollow gazelle
sick birch
#

here's an example of a basic slash command that might be worth reading over

hollow gazelle
#

ok

hollow gazelle
#

AttributeError: module 'discord' has no attribute 'Bot'

slate swan
#

💀

hollow gazelle
#

i dont work with dpy

slate swan
hollow gazelle
#

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

slate swan
#

just do this

from discord.ext import commands


bot=commands.Bot(command_prefix=...., intents=discord.Intents.all())
oak oar
#
 if (datetimenow - message.created_at).total_seconds() >= length_of_seconds:
        ~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~
TypeError: can't subtract offset-naive and offset-aware datetimes
hollow gazelle
#

ok

slate swan
#

!intents

unkempt canyonBOT
#

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.

slate swan
#

Like this

oak oar
slate swan
oak oar
#

for some reason it works with py 3.9 but doesn't work with 3.10 and 3.11

hollow gazelle
hollow gazelle
#

@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'?

hollow gazelle
#

AttributeError: 'Bot' object has no attribute 'slash_command'. Did you mean: 'add_command'?

#

trying to use pycord

#

but have dpy imports

#

!pycord

sick birch
hollow gazelle
sick birch
#

Yes but it still conflicts because they have the same namespace

hollow gazelle
#

ok

sick birch
#

Either uninstall pycord (recommended)
Or uninstall discord.py (not recommended)

hollow gazelle
#

@app_commands.describe(invite= "")

#

isnt that how i addd options? for slash command?

upbeat gust
hollow gazelle
#

Someone told me that’s how

hollow gazelle
#

Nvm

#

I got it

maiden fable
sick birch
maiden fable
#

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

sick birch
#

Imagine pip install py-cord but import pycord doesn't work

maiden fable
#

Lmao

slate swan
#

whats the command to get a user’s profile picture and display it

naive briar
#

!d discord.User.avatar

unkempt canyonBOT
#

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").
slate swan
#

💀💀

naive briar
#

What is tid

slate swan
naive briar
#

The error says exactly what the problem is

slate swan
naive briar
#

!e

"".send()
unkempt canyonBOT
#

@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'
naive briar
#

It's just basic Python

slate swan
naive briar
#

What are you trying to do

slate swan
# slate swan
from discord.utils import get


tid = get(interaction.guild.channels, name=f"ticket-{interaction.user.name}")
await tid.send(.....)
#

This should work

slate swan
slate swan
#

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

cloud dawn
#

It's a check that returns True by default; if it is not true then don't process the command.

slate swan
slate swan
#

It is good yo know, because sometimes we don't want other ppl to interact out buttons that we got using cmd

sand falcon
cloud dawn
sand falcon
#

is it better for starters

slate swan
#

yeah, its fine for starters
both Library support all latest features
difference is mostly library abstractions
and pycord code quality 👎

cloud dawn
#

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.

sand falcon
#

ok

graceful turtle
#

what is the red color code, apparently this is blue

hushed galleon
#

0xFF0000, the format being RRGGBB

#

255 would be equivalent to 0x0000FF, hence blue

slate swan
#

💀 raw embed payload

alpine cove
safe zinc
#

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)

slate swan
#

!d discord.ext.tasks.loop

unkempt canyonBOT
#

@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").
slate swan
#

for repeating the send^

#

!d discord.Client.get_channel for getting the channel and sending message using.send

unkempt canyonBOT
#

get_channel(id, /)```
Returns a channel or thread with the given ID.

Changed in version 2.0: `id` parameter is now positional-only.
slate swan
#

make sure to start the task after the cache is ready

slate swan
#

@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?

slate swan
#

Btw is pip command can be used in Windows too?

slate swan
slate swan
#

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

unkempt canyonBOT
slate swan
#

Btw do u know "cat" commands?

slate swan
rigid moss
#

Where do I ask doubts

slate swan
slate swan
#

concatenate?

slate swan
#

not very familiar

#

cat > file.txt

#

Run it on terminal = it will create a file as file.txt xd

#

Kinda cool

slate swan
slate swan
slate swan
#

Need to follow the light shit

#

I am backdated

#

@slate swan imma ask 1 more ques ;-;

#

surely

slate swan
#

im from india lol, nothing personal most people guess it from my name itself cause its a hindi word

slate swan
#

idm

slate swan
#

U can indent in same line or move it outside the cog if u want to use this list everywhere

#

Xd

full valley
#

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

slate swan
full valley
#

slash

slate swan
#

slash group, usually i use for to make space in slash commmand 💀

#

Idk how others use it

vocal snow
#

looks like bot isn't defined but hard to say without more code

#

also, you should be creating ClientSessions instead coroutines

maiden fable
#

Why tf did i misread ses 💀

full valley
#

you could just have a switch case in your sub command ig

#

idk if u can put a sub in a sub

maiden fable
#

Uh I uhh will just go

slate swan
#

hey someone can tell me what's intents means?

sick birch
#

So it doesn't flood you with useless information you won't use

#

!intents

unkempt canyonBOT
#

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.

slate swan
#

and how i choose the infomations i need?

#

I imported py from discord import intents but still the same error

sick birch
#

Classes are PascalCased

slate swan
#

yes i did it

sick birch
#

Or CamelCased idr

sick birch
slate swan
full valley
#

you don’t import intents

slate swan
#

wdym

sick birch
unkempt canyonBOT
#

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.

full valley
#

you stats your intents when initialising commands.Bot()

sick birch
#

Read this embed

full valley
#

Huh am I stupid

#

yikes

glad cradle
#

!d discord.ui.Button.disabled

unkempt canyonBOT
maiden fable
#

I wish the property was enabled instead of disabled

cloud dawn
maiden fable
#

Well yea lol

cloud dawn
#

Or make your own view

#

Possibilities are infinite.

maiden fable
#

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 ;-;

cloud dawn
#

It's ok, someone needs to think differently, right @sick birch

maiden fable
#

Think Different
Think Like Hunter™️

shrewd apex
maiden fable
#

You know what you are right

shrewd apex
#

average stressed jee kid

glad cradle
#

is CockroachDB a good cloud database? (for a discord bot)

maiden fable
#

nice.... name

#

Who comes up with these names anyway

cloud dawn
#

Ikr "Hunter" tf

maiden fable
slate swan
cloud dawn
slate swan
maiden fable
#

No thanks

slate swan
#

hunter is shy

cloud dawn
#

@maiden fable Just overwrite the global @slate swan he will disappear.

glad cradle
slate swan
slate swan
maiden fable
#

lmao

cloud dawn
#

It's up to Hunter I'm afraid

slate swan
#

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

unkempt canyonBOT
#

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**...
slate swan
#

interaction event

glad cradle
cloud dawn
#

If someone would send the command, why let him or her confirm the invite? He typed in the command and the person to invite.

slate swan
#

thats gonna work? for my situation?

cloud dawn
slate swan
#

i dont think it does lol

cloud dawn
slate swan
cloud dawn
#

I'd just make it so the interaction can only be confirmed by the receiver.

#

End the View when pressed.

slate swan
#

nah both people need to click confirm

#

for the bot to continue

slate swan
cloud dawn
slate swan
#

and there;s pgsql hosts online too ( like railway )

slate swan
glad cradle
cloud dawn
austere vale
#
    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?
cloud dawn
# slate swan wdym

To wait just append the member to a list or have a bool that says if he/she joined (hardcoded).

cloud dawn
# slate swan wdym by append

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.

slate swan
#

do u want to see my bot?

cloud dawn
cloud dawn
slate swan
#

dms

austere vale
slate swan
naive briar
#

Like lambda

#

And it should return bool obj

#

Or just use list comp

dense merlin
#

my slash command no appeare 💀 ]

naive briar
#

Are you using dpy

dense merlin
#

I used discord-py-interactions

slate swan
#

that library is no longer maintained

dense merlin
#

dangit

cloud dawn
dense merlin
#

it worked one week ago and then stopped working that very day

slate swan
#

wait no they just changed their name it should still work

#

show your code

cloud dawn
#

Also reminder that any unmaintained dpy fork, or a library that is using V7, at new year, those are going to be disabled.

dense merlin
#
@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
naive briar
#

What the

dense merlin
#

wgat

cloud dawn
#

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

dense merlin
#

yes ik

#

but slash no work

dense merlin
#

ok

mellow verge
#

Who has the script for a ticket bot for me?

cloud dawn
#

GitHub most likely.

sick birch
#

Tfw

cloud dawn
#

I dunno chief.

sick birch
#

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

cloud dawn
cloud dawn
faint mural
#

Don't use f-strings for db queries or stuff like that BHVKannaPanic

slate swan
#

what code editor is that

austere vale
#
    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

naive briar
#

That's a very inefficient way of filtering things

austere vale
#

what would you suggest?

naive briar
#

!list-comp

unkempt canyonBOT
#

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.

naive briar
#

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)
unkempt canyonBOT
#

@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)]
maiden fable
#

or just use filter

slate swan
#

list.remove(bot.get_user(bot_id))

naive briar
#

🤷

#

Anything you prefer

maiden fable
#

indeed

slate swan
#

tbh I'd play with user ids instead of User objects cause thats all you'll need here

maiden fable
#

Average Hikari user

naive briar
#

Oh wait

slate swan
#

Objects are overrated 😔

#

i mean models

naive briar
austere vale
near wolf
#

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'])

slate swan
#

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?

somber sky
#

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 𝗔𝗕𝗖

near wolf
slate swan
#

what intents do you have

unkempt canyonBOT
#

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```
near wolf
slate swan
#

you'll have to keep updated the d field of Heartbeats you send to discord with the count of dispatches

near wolf
#

and the heartbeat ACK is received

lyric sandal
#

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?

near wolf
#

but isnt it just the sequence number

slate swan
#

The inner d key is the last sequence number—s—received by the client. If you have not yet received one, send null.

vague cliff
#

sourc

abstract kindle
#

!d discord.app_commands.AppCommand.name_localizations

unkempt canyonBOT
abstract kindle
#

What is this used for?

slate swan
#

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.

slate swan
flat pier
full valley
#

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

dapper cobalt
#

That's all I know you could do. However, I'm sure there might be a module out there that would assist you

shrewd apex
#

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

full valley
#

How can I sync all my commands that are in cogs

naive briar
#

Load the cogs and just sync the tree normally

near wolf
#
    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
near wolf
alpine cove
near wolf
#

sequence number...

alpine cove
#

whats that?

near wolf
alpine cove
#

thx

#

couldnt find it

near wolf
#

cmon ur in discord bot help and u dont know this

alpine cove
#

ohhh

alpine cove
#

i dont really get what ur tryina fo

#

*do

#

whats is Bot.pool?

#

A lock?

vale wing
#

I got a checkmark for my bot in just 30 minutes wtf it took 2 months last time

alpine cove
vale wing
#

That's not twitter bro

raw lance
#

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

glad cradle
#

what is countries

faint mural
#

you still don't do that

ocean dragon
#
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())
narrow wadi
#

edit the message

ocean dragon
naive briar
#

What do you mean?

ocean dragon
#

when I run it, it doesn't call setup_hook

#

is this only for Client class?

naive briar
#

It is not an event

#

It's a method of the client class

#

And commands.Bot is a subclass of Client btw

ocean dragon
#

right

#

how do i remove an old command? I synced the bot but it still shows the old parameters

vale wing
#

Maybe that's library-specific tho, I use disnake

slate swan
#

Cul

mellow verge
#

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)```
slate swan
#

Any error? @mellow verge

#

!music

#

!yt

mellow verge
slate swan
#

@mellow verge need to set intents

#

!intents

unkempt canyonBOT
#

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.

mellow verge
#

Uhmmm

#

im new with python so what do i need to do

slate swan
#

from nextcord import Intents

intent=Intents.default()
intent.message_content=True
bot=command.Bot(intent=intent)

mellow verge
#

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)```
slate swan
#

Yes

#

No @mellow verge

mellow verge
#

Uhhh

slate swan
#

add intent=intent in ur bot variable

#

like
commands.Bot(command_prefix="!", intent=intent)

mellow verge
#

Wait

#

can you maybe edit my code because i dont know what to do

slate swan
#

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)```
naive briar
#

Step 1: learn basic python

slate swan
#

also in
bot.loop.create_task(node.connect())
But there is no node variable i see 💀

slate swan
#

Well imma not disturb

slate swan
#

Someone help

#

I want my slash command user to have certain permissions to use the slash command.

slate swan
#

If yes i can help

#

!d discord.app_commands.checks.has_permissions

unkempt canyonBOT
#

@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...
slate swan
#

!d discord.app_commands.default_permissions

unkempt canyonBOT
#

@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.
slate swan
#

Here is two

slate swan
#

@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
mighty yarrow
mighty yarrow
#

i cant type message in terminal

glad cradle
mighty yarrow
#

but i want to remove that