#discord-bots

1 messages · Page 221 of 1

smoky sinew
#

snipy

unkempt canyonBOT
#
Huh? No.

No documentation found for the requested symbol.

smoky sinew
#

!d discord.Member.timed_out_until

unkempt canyonBOT
#

An aware datetime object that specifies the date and time in UTC that the member’s time out will expire. This will be set to None if the user is not timed out.

New in version 2.0.

smoky sinew
#

bruh my internet connection is not working i cannot go to docs sadge

glad cradle
smoky sinew
#

why we abandon pyweek

glad cradle
#

because noone is working on it 😔😭

#

I can't do everything in solo

smoky sinew
#

so sad maybe i will just quit team and submit a half-assed 1 hour pygame game to at least have something

glad cradle
#

I'm sorry it went that way, the team was made in a rush and the codebase isn't that great either

vocal snow
#

Rip

slate swan
#

!d discord.Member

unkempt canyonBOT
#

class discord.Member```
Represents a Discord member to a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild").

This implements a lot of the functionality of [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User").

x == y Checks if two members are equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User") instances too.

x != y Checks if two members are not equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User") instances too.

hash(x) Returns the member’s hash.

str(x) Returns the member’s name with the discriminator.
light violet
#
@client.hybrid_command()
@commands.cooldown(1, 10, commands.BucketType.user)
async def dream(ctx,*,prompt):
  url=os.getenv("sd")
  msg = await ctx.send(f"Generating - {prompt} - **By {ctx.author.name}** \n ***Estimated*** <t:{int(time.time())+24}:R>")
  res=requests.get(f"{url}/?dream={prompt.replace(' ','+')}")
  print(res.content)
  await msg.edit(content=f"Generated - {prompt} - **By {ctx.author.name}**",file=discord.File(res.content,filename='image.png'))```
#

why isnt it working , the res.content is in bytes and is an image,but i get this error raise CommandInvokeError(exc) from exc discord.ext.commands.errors.CommandInvokeError: Command raised an exception: ValueError: embedded null byte

#

when i add this line

with open("ok.png","wb") as f:
    f.write(res.content)```
it saves the image successfuly
glad cradle
#

!d discord.File

unkempt canyonBOT
#

class discord.File(fp, filename=None, *, spoiler=..., description=None)```
A parameter object used for [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") for sending file objects.

Note

File objects are single use and are not meant to be reused in multiple [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send")s.
glad cradle
#

!d io.BytesIO

unkempt canyonBOT
#

class io.BytesIO(initial_bytes=b'')```
A binary stream using an in-memory bytes buffer. It inherits [`BufferedIOBase`](https://docs.python.org/3/library/io.html#io.BufferedIOBase "io.BufferedIOBase"). The buffer is discarded when the [`close()`](https://docs.python.org/3/library/io.html#io.IOBase.close "io.IOBase.close") method is called.

The optional argument *initial\_bytes* is a [bytes-like object](https://docs.python.org/3/glossary.html#term-bytes-like-object) that contains initial data.

[`BytesIO`](https://docs.python.org/3/library/io.html#io.BytesIO "io.BytesIO") provides or overrides these methods in addition to those from [`BufferedIOBase`](https://docs.python.org/3/library/io.html#io.BufferedIOBase "io.BufferedIOBase") and [`IOBase`](https://docs.python.org/3/library/io.html#io.IOBase "io.IOBase"):
light violet
light violet
#

ohk

#

thenkjs

#

THENKS*

vale wing
nimble skiff
#

Can someone help me

blazing flint
#

Lol my bot has a .help command and I don’t know why. I never made the command and all of mine are slash commands, except for one built in configuration feature that uses the . prefix.

hushed galleon
#

that comes free with commands.Bot for prefix-based commands, if you want to remove it just pass help_command=None to your bot's constructor

nimble skiff
#

@blazing flint sent u in dms

pale escarp
#
    @commands.has_permissions(administrator=True)
    async def editgroup(self, ctx, group_name):
        server_id = str(ctx.guild.id)
        try:
            group = self.database.getgroup(server_id, group_name)
            if group is None:
                await ctx.send(f"Group '{group_name}' does not exist.")
                return

            # Ask the user whether they want to add or remove members
            await ctx.send(f"What do you want to do with the {group_name} group? Type 'add members' or 'remove members'.")
            action = await self.bot.wait_for('message', check=lambda m: m.author == ctx.author)
            action_str = action.content.strip().lower()

            # Determine which member column to modify based on the action
            if action_str == 'add members':
                member_col = 'members'
            elif action_str == 'remove members':
                member_col = 'members2'  # Change this to the appropriate column name if necessary
            else:
                await ctx.send(f"Invalid action. Please type 'add members' or 'remove members'.")
                return

            # Ask the user for the members to add or remove
            await ctx.send(f"Who do you want to {action_str} from the {group_name} group? (Please separate each user with a space, or reply 'no' to cancel)")
            members = await self.bot.wait_for('message', check=lambda m: m.author == ctx.author)
            members_str = members.content.strip().lower()
            if members_str == 'no':
                await ctx.send("Operation cancelled.")
                return
            else:
                # get the usernames from the mentioned users
                if len(members.mentions) == 0:
                    members_str = ''
                else:
                    members_str = ", ".join([member.name for member in members.mentions])
                new_members = [member.id for member in members.mentions]

            # Modify the appropriate member column in the database
            if member_col in group:
                old_members = [int(member_id) for member_id in group[member_col].split(',') if member_id != '']
            else:
                old_members = []

            if action_str == 'add members':
                updated_members = set(old_members).union(new_members)
            else:
                updated_members = set(old_members) - set(new_members)

            updated_members_str = ','.join(str(member_id) for member_id in updated_members)
            self.database.editgroup(server_id, group_name, member_col, updated_members_str)
            await ctx.send(f"Group '{group_name}' has been updated with {action_str} '{members_str}'.")
        except Exception as e:
            print(e)
            await ctx.send(f"An error occurred while updating the group.")
            traceback.print_exc()```

Instead of adding members to the list, its replacing the whole list.
pale escarp
#

anyone knows how to fix that

blazing flint
full lily
#

whats the story with discord.py now? Does it support slash commands and all of those new fancy features?

blazing flint
full lily
#

alrighty

#

and what about forum channels anddddd

#

I can't really think of anything else right now, but I know it had a lot of holes in terms of what you could do in the library compared to what discord offered

slate swan
#

@blazing flintwait can u tell are we only supposed to use slash commands in bot??

hushed galleon
# full lily I can't really think of anything else right now, but I know it had a lot of hole...

not sure if there's a list of missing features somewhere, but you can look through the changelog to see what they've recently added (forumchannels were added in 2.0)
https://discordpy.readthedocs.io/en/stable/whats_new.html
some missing features i can think of is oauth flow (out of scope for dpy), http-only interactions (though this can be done using internals), and voice receive (i think danny isnt willing to maintain this feature?)

full lily
#

i'm just having a read right now. If there's nothing major missing then that's all the better for me

hushed galleon
#

and fwiw
<#dev-announcements message>

2022/3/05: We just migrated <@&270988689419665409> to disnake!
2022/3/13: We'll be reverting our migration on bot and our bot-core projects to use the latest revisions of Discord.py

maiden fable
slate swan
blazing flint
slate swan
#

a datetime object if they're timed out, or None if they're not timed out

glad cradle
vocal snow
stable current
#
import discord
import random

TOKEN = 'Secret'

client = discord.Client()

@client.event
async def on_ready():
    print('We have logged in as {0.user}'.format(client))


@client.event
async def on_message(message):
    username = str(message.author).split('#')[0]
    user_message = str(message.content)
    channel = str(message.channel.name)
    print(f'{username}: {user_message} ({channel})')


    if message.author == client.user:
        return
    
    if message.channel.name == 'python-projects':
        if user_message.lower() == 'hello':
            await message.channel.send(f'Hello {username}!')
            return
        elif user_message.lower() == 'bye':
            await message.channel.send(f'Bye {username}!')
            return
client.run(TOKEN)
#

Why wont this work

loud mountain
#

Wait you can make a discord bot in python????

#

is there like a basic code somewhere i can copy and build off of?

vocal snow
#

it's recommended you know atleast basic python before starting though

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.

loud mountain
#

what is this? text o get voice support, you should use discord.py[voice] instead of discord.py is that just to allow it to connect to voice channels and speak? if so that is useful, i can create a music bot

vocal snow
#

yes

#

!ytdl

unkempt canyonBOT
#
Our youtube-dl, or equivalents, policy

Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.

For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:

The following restrictions apply to your use of the Service. You are not allowed to:

1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service;  (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;

3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTube’s robots.txt file; (b) with YouTube’s prior written permission; or (c) as permitted by applicable law;

9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
loud mountain
#

great

vocal snow
#

just take note of this when making a music bot ^

loud mountain
#

yep

stable current
vocal snow
#

the same way it's done in the example except you would pass the intents to your discord.Client instead of commands.Bot

blazing flint
#

and then pass it when you create your client/bot object

stable current
#

I started learning python 2 weeks ago

glad cradle
#

O_o

vocal snow
stable current
#

Once I've learned the language fully, I'm going to go into AI and stuff

loud mountain
#

question: is my bot supposed to stay online after i hit close on my script?

#

because it wont go offline

#

but the commands dont work

#

how do i take it offline its creepy

slate swan
vocal snow
#

(ctrl + R)

stable current
slate swan
slate swan
slate swan
#

!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
#

intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix='!', intents=intents)

loud mountain
#

how do i set up slash commands? i currently have a basic one: ```py
import discord

intents = discord.Intents.default()
intents.message_content = True

client = discord.Client(intents=intents)

@client.event
async def on_ready():
print(f'We have logged in as {client.user}')

@client.event
async def on_message(message):
if message.author == client.user:
return

if message.content.startswith('$hello'):
    await message.channel.send('Hello!')

if message.content.startswith('$Who are you?'):
  await message.channel.send('I am a bot, wirtten in python by Faulty! I am a basic bot.')

client.run('Token')```

slate swan
#

it has intents argument

stable current
#
import discord

from discord import Intents
from discord.ext import commands


intents = Intents.default()
intents.message_content = True

bot = commands.Bot(command_prefix="!", intents=intents)
intents = discord.Intents.all()

TOKEN = 'pypypypypypypy'

client = discord.Client()

@client.event
async def on_ready():
    print('We have logged in as {0.user}'.format(client))


@client.event
async def on_message(message):
    username = str(message.author).split('#')[0]
    user_message = str(message.content)
    channel = str(message.channel.name)
    print(f'{username}: {user_message} ({channel})')


    if message.author == client.user:
        return
    
    if message.channel.name == 'python-projects':
        if user_message.lower() == 'hello':
            await message.channel.send(f'Hello {username}!')
            return
        elif user_message.lower() == 'bye':
            await message.channel.send(f'Bye {username}!')
            return
client.run(TOKEN)

I put in the intents, but still doesnt work

slate swan
slate swan
stable current
#

I watched a toturial

#

I need to begin on bot developing somewhere

slate swan
#

you need to create discord.Intents object then enable intents you need and then pass it when creating Client

loud mountain
#

thx

slate swan
#

!paste

#

thats the code u need

#

lmk if theres any more errorz

stable current
#

Is there a way to make a more simplified bot without intents?

slate swan
#

discord requires intents

stable current
#

Any toturials on yt on how to use them?

slate swan
#

also @stable current what type of bot are u coding? Moderation bot?

stable current
slate swan
#

i could send u my code for a moderation bot if u wanta look at it

#

also i recomend using bot.command not client.command

stable current
#

like, an example

slate swan
#

i did look at the paste i sent

#

!d discord.Intents

unkempt canyonBOT
#

class discord.Intents(value=0, **kwargs)```
Wraps up a Discord gateway intent flag.

Similar to [`Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions "discord.Permissions"), the properties provided are two way. You can set and retrieve individual bits using the properties as if they were regular bools.

To construct an object you can pass keyword arguments denoting the flags to enable or disable.

This is used to disable certain gateway features that are unnecessary to run your bot. To make use of this, it is passed to the `intents` keyword argument of [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client").

New in version 1.5.
slate swan
#

explained as i could

stable current
#
import discord

from discord import Intents
from discord.ext import commands



intents = discord.Intents.default()
intents.message_content = True
intents.members = True

client = discord.Client(intents=intents)(all)
client = commands.Bot(command_prefix= "#", intents= intents)


TOKEN = 'pypypyppypypyppypypy'

@client.event
async def on_ready():
    print('We have logged in as {0.user}'.format(client))


@client.event
async def on_message(message):
    username = str(message.author).split('#')[0]
    user_message = str(message.content)
    channel = str(message.channel.name)
    print(f'{username}: {user_message} ({channel})')


    if message.author == client.user:
        return
    
    if message.channel.name == 'python-projects':
        if user_message.lower() == 'hello':
            await message.channel.send(f'Hello {username}!')
            return
        elif user_message.lower() == 'bye':
            await message.channel.send(f'Bye {username}!')
            return
client.run(TOKEN)
#

Like this?

slate swan
#

yes

stable current
slate swan
#

use bot instead of client

stable current
#

FINALLY

slate swan
stable current
#

And it finally worked

slate swan
#

Please have some Basic python knowledge before starting to create a discord bot

#

That's not good for first project

stable current
#

Yeah I know, but I'm very motivated to do it

#

I study python every day, I'm going to go back to the more general stuff now

#

Gotta walk before you can run

#

Anyways, I finally did it and I'm happy and even more motivated to learn the more general stuff, so yeah

stable current
#

@slate swan Do you know how I can use the slash commands with my bot?

hushed galleon
#

^ dont forget about this tag
@stable current that being said, it will become easier to understand as you grasp the fundamentals like data types, functions, and object oriented programming

there's a list of things you should know here: https://gist.github.com/scragly/095b5278a354d46e86f02d643fc3d64b

try to understand a reasonable amount of what you're writing and develop a good reasoning about what your program does

str(message.author) gives me a string in the form "username#tag" and i want the username, so im using .split('#') to split the username/tag into two elements in a list, then indexing the first element with [0] to get the username

btw message.author.name / message.author.display_name serves the same purpose as above, and that's part of the documentation which will become a very important source of information for learning what the library provides
https://discordpy.readthedocs.io/en/stable/api.html#id1
generally official sources are preferable for learning since they tend to have more comprehensive and up-to-date information, including python's own documentation

(not that third-party guides are all bad, however many about discord.py are notorious for demonstrating bad practices)

slate swan
stable current
hushed galleon
stable current
#

I currently have my own commands, but is it required to have slash commands to get the badge

slate swan
#

your choice if u want an easy way or a slightly harder way

stable current
#

I want to do this as a challenge

slate swan
#

you just gotta learn how to make / cmds and ur good

stable current
stable current
#
import discord
from discord.ext import commands

bot = commands.Bot(command_prefix="!", intents= discord.Intents.all())

TOKEN = 'pypypyppypypypypypyp'

@bot.event
async def on_ready():
    print("Bot is running!")
    try:
        synced = await bot.tree.sync()
        print(f"Synced {len(synced)} command(s)")
    except Exception as e:
        print(e)

@bot.command()
async def hello(ctx):
    await ctx.send(f"Hey {ctx.author.mention}! This is a slash command")

bot.run(TOKEN)
#

Why wont it detect synced commands

hexed dagger
slate swan
unkempt canyonBOT
#

await timeout(until, /, *, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Applies a time out to a member until the specified date time or for the given [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta "(in Python v3.11)").

You must have [`moderate_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.moderate_members "discord.Permissions.moderate_members") to do this.

This raises the same exceptions as [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.edit "discord.Member.edit").
slate swan
#

did you read the link i gave you?

hexed dagger
#

So I was using interaction.user.timeout(

#

How do I mute for 20s with that

slate swan
#

you need to create a timedelta object with 20 seconds

#

!d datetime.timedelta

unkempt canyonBOT
#

class datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)```
All arguments are optional and default to `0`. Arguments may be integers or floats, and may be positive or negative.

Only *days*, *seconds* and *microseconds* are stored internally. Arguments are converted to those units...
hexed dagger
#

Alr lemme try

slate swan
#

!e ```py
from datetime import timedelta

until = timedelta(seconds=20)

print(until)

unkempt canyonBOT
#

@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.

0:00:20
slate swan
#

now when you have the object

#

you need to pass it into timeout method

#

!d discord.Member.timeout

unkempt canyonBOT
#

await timeout(until, /, *, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Applies a time out to a member until the specified date time or for the given [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta "(in Python v3.11)").

You must have [`moderate_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.moderate_members "discord.Permissions.moderate_members") to do this.

This raises the same exceptions as [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.edit "discord.Member.edit").
slate swan
#

until arg

smoky sinew
hexed dagger
#

@slate swan

#

Ur previous thing worked thx

hexed dagger
#

Hi

#

My discord button is not changing color

#

When it is clicked

#

Here's the code

random obsidian
#

how can i obtain message author user id?

copper ibex
random obsidian
#

no no
from bot

#

for example
i send this message and want from bot to take this message author id

copper ibex
# hexed dagger

You're spelling button wrong you say "buttoon" unless you have to do that that's what I see

random obsidian
#

!d discord.Message.author

unkempt canyonBOT
hexed dagger
#

I am stupid

copper ibex
copper ibex
random obsidian
hexed dagger
#

Thanks

copper ibex
hexed dagger
smoky sinew
unkempt canyonBOT
random obsidian
random obsidian
smoky sinew
#

if you ONLY have the user ID, then get or fetch the user first using Client.get_user

random obsidian
#

aha

#

thanks ❤️

random obsidian
#
@bot.tree.command(name="getid",description="Get User Id!")
@app_commands.describe()
async def getid(interaction:discord.Interaction):
  userid = interaction.user.id
  username = discord.Member.display_name(userid)
  print(str(username))
```@smoky sinew
smoky sinew
#

just print(interaction.user.display_name)

#

and remove lines 4 and 5

#

you need an instance of discord.Member to use display_name

random obsidian
#

aw

#

it working!
thanks ❤️

gaunt spear
#

how can i run 2 files in my bot?

blazing flint
gaunt spear
smoky sinew
#

it would be python3 requirements.txt && python3 main.py

#

does that even work in the first place though

slate swan
#

holy shit im an idiot

smoky sinew
#

ok

slate swan
#

and I don't think you can run two files like that at the same time

#

you should run them separately if you want

smoky sinew
#

cat /dev/urandom | python3

#

there is a potential chance that in a few million years this will remove all files on your computer

idle lantern
#

any tips for where should i start learning about discord bots made with python?

slate swan
#

can someone send a like verification that i can run in it that lets me join servers for them

idle lantern
#

oh thanks

slate swan
#

i open the app and it opens terminal

#

what do i do next

#

im not watching a 5 hour video for it to tell me

#

please help

smoky sinew
#

it's not really related to a discord bot so much as a webserver

slate swan
#

how do you add cooldowns to discord ui buttons? i want to set it to once a minute with some indicator that the buttons are ready again. maybe change them to red? then revert back the colours?

#

or maybe a queue method so it doesn't error?

golden portal
golden portal
#

now that i think about it you dont have to spawn a task at all, just do it inside the button callback 🤔

blazing flint
#

I am defining a message variable so I can edit it later. For some reason, I can only use message.edit if the message is not an interaction.response. How can I edit an interaction.response object?

slate swan
golden portal
#

i suppose yea in the interaction_check

golden portal
blazing flint
golden portal
blazing flint
#

K

#

@golden portal I get an error when I do this saying the interaction has already been responded to before. I am trying to edit the response I already sent

#

Is it just not possible to add a view to a response?

golden portal
blazing flint
#

ok

raw quail
#

I created a bot that created a channel and created several threads in the channel to automatically transmit certain data every month on a specified date. but, if the message is not updated for a certain period of time in the thread, the ID of the channel remains the same as before, but the message cannot be sent using the bot anymore. as shown below, the message that there is no channel id appears. so it says 'send' can't be done. is the only way to solve this is to send it to a channel rather than a thread?

'NoneType' object has no attribute 'send'
hushed galleon
#

if you just want to send a message to the channel and do nothing else, use Client.get_partial_messageable(thread_id) instead, or if you do need the actual Thread object, use Guild.fetch_channel(thread_id) as a fallback if get_thread doesn't work

raw quail
vital glacier
#

problem is, if i try to get 'for t in tags' in jsk py, it works properly like it should

pliant gorge
#

Can you make a bot that captures all the names in someone’s server

vital glacier
#

put them all in a list and then send/print that list

pliant gorge
#

Yeah but it isn’t my server

vocal snow
#

the bot needs to be in whichever server you want to get the member list from

#

!d discord.Guild.members

unkempt canyonBOT
vocal snow
#

you can obtain the discord.Guild object via bot.get_guild or an event parameter depending on where you're trying to access it

mighty sun
vocal snow
mighty sun
#

Yes, because I have to, right? To have several messages?

vocal snow
#

no

#

you call it once

#

!d discord.ext.commands.Bot.process_commands

unkempt canyonBOT
#

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

This function processes the commands that have been registered to the bot and other groups. Without this coroutine, none of the commands will be triggered.

By default, this coroutine is called inside the [`on_message()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_message "discord.on_message") event. If you choose to override the [`on_message()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_message "discord.on_message") event, then you should invoke this coroutine as well.

This is built using other low level tools, and is equivalent to a call to [`get_context()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.get_context "discord.ext.commands.Bot.get_context") followed by a call to [`invoke()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.invoke "discord.ext.commands.Bot.invoke").

This also checks if the message’s author is a bot and doesn’t call [`get_context()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.get_context "discord.ext.commands.Bot.get_context") or [`invoke()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.invoke "discord.ext.commands.Bot.invoke") if so.

Changed in version 2.0: `message` parameter is now positional-only.
vocal snow
#

see what it does ^

#

if you call it more than once, it'll process the commands more than once too

mighty sun
#

I edited it's fine thanks 😄😍

blissful badge
#

hi hoping to maybe get some help

working on getting this preview working for an embed command....code below

    @commands.command()
    async def embed(self, ctx):
        def check(message):
            return message.author == ctx.author and message.channel == ctx.channel

        await ctx.send('Waiting for a title')
        title = await self.bot.wait_for('message', check=check)
  
        await ctx.send('Waiting for a description')
        desc = await self.bot.wait_for('message', check=check)

        await ctx.send('Please provide me with the image (directly paste or attach image, no need for link) for this post, if no image is needed just say none.')
        news_image = await self.bot.wait_for("message", check=lambda m: all([
            m.author == ctx.author,
            m.channel == ctx.channel,
            len(m.attachments) == 1 or "none" in m.content.lower()
            ]))

        if news_image.attachments:
            embed.set_image(url=news_image.attachments[0].url)

        embed = discord.Embed(title=title.content, description=desc.content, color=0x1ABC9C)
        embed.set_thumbnail(url="https://imgur.com/MJnM3LU.png")

        await ctx.send('What channel should I send this in? Please provide me with the channel ID.\n- #news: 569635458183856149\n- #general: 803341100618219540\n- #patch-notes: 585952222853201941')
        dest = await self.bot.wait_for('message', check=check)

        await ctx.send('Who should I tag? Please provide me with the role ID.\n- news: 620025828079697920\n- gen: 803343410794594385\n- patch: 620025894559547412')
        role_message = await self.bot.wait_for('message', check=check)

        await ctx.send('What is the tag preview?')
        tag_preview = await self.bot.wait_for('message', check=check)

        channel = self.bot.get_channel(1065685023853920258)
        class ConfirmationView(discord.ui.View):
            @discord.ui.button(label="Confirm", style=discord.ButtonStyle.success)
            async def confirm(self, interaction: discord.Interaction, button: discord.ui.Button) -> None:
                await channel.send(1065685023853920258)

            @discord.ui.button(label="Deny", style=discord.ButtonStyle.danger)
            async def deny(self, interaction: discord.Interaction, button: discord.ui.Button) -> None:
                await interaction.response.send_message("Cancelled.", ephemeral=True)
    
        channel = self.bot.get_channel(int(dest.content))
        await channel.send(embed=embed)
        await channel.send(f"<@&{role_message.content}> - {tag_preview.content}")

goal is for it to send a preview into the command issued channel that can be approved or denied before being sent off

#

it just sends the embed to its final destination and skips the preview rn

slate swan
#

guys how fix this error nextcord.errors.InteractionResponded: This interaction has already been responded to before

amber kettle
#

Oh

glad cradle
slate swan
#

oo

#

so how close the other responded message

glad cradle
#

!d nextcord.Interaction.send

unkempt canyonBOT
#

await send(content=None, *, embed=..., embeds=..., file=..., files=..., view=..., tts=False, delete_after=None, allowed_mentions=..., flags=None, ephemeral=None, suppress_embeds=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

This is a shorthand function for helping in sending messages in response to an interaction. If the interaction has not been responded to, [`InteractionResponse.send_message()`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.InteractionResponse.send_message "nextcord.InteractionResponse.send_message") is used. If the response [`is_done()`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.InteractionResponse.is_done "nextcord.InteractionResponse.is_done") then the message is sent via [`Interaction.followup`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.Interaction.followup "nextcord.Interaction.followup") using [`Webhook.send`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.Webhook.send "nextcord.Webhook.send") instead.
slate swan
glad cradle
#
await inter.send(...)
slate swan
#

await interaction.response.send_modal(modal)

glad cradle
#

this will respond to the interaction if it wasn't responded before, otherwise it'll use the followup to send the message

slate swan
#

so it will not work like that

glad cradle
#

you can send modal only on interaction responses

slate swan
#

ik so i added response

glad cradle
#

yeah then it should be the first thing that you send

slate swan
#

ah i can't do that

glad cradle
#

blame discord for this

slate swan
#

there are any way to solve that?

glad cradle
#

mm let me check

#

no, but you could use a message with buttons and when a button is clicked you'll send the modal

vale wing
#

@glad cradle you are helper now 😳

buoyant knot
#

im trying to make my bot join a specific vc and play a specific file when a command is said, however it joins vc and doesnt play anything
i added the print debug message there, it seems like it gets stuck on vc = await channel.connect()

vale wing
#

Do you have ffmpeg executable

buoyant knot
#

oh

vale wing
#

Yeh

buoyant knot
#

i forgot about that, my bad

vale wing
raw quail
#
async def test(self, ctx):
    t = randint(180, 300)
    old_links = []
    with open("old_links.txt", "r", encoding="utf-8") as file:
        old_links = file.read().splitlines()

    while True:
        try:
            channel = self.bot.get_channel(channel_id)
            err_message = self.bot.get_channel(err_discord)
            base_url = ''
            async with aiohttp.ClientSession() as sess:
                async with sess.get(base_url, headers={'user-agent': user_agent}) as res:
                    text = await res.text()
                    soup = bs(text, 'lxml')

                    title = soup.find
                    link = soup.find

                    if link not in old_links:
                        embed=discord.Embed(title=title, url=link)
                        embed.set_author(name="News")
                        await channel.send(embed=embed)
                        old_links.append(link)
                        with open("old_links.txt", "w", encoding="utf-8") as file:
                            file.write("\n".join(old_links))
                    else:
                        pass      
        except Exception as e:
            await err_message.send("❗ News an error please check ❗", delete_after=60)

        await asyncio.sleep(t)

I created a function that sends a message when a new post is uploaded. but as the number of sites increases, links are not saved in old_links.txt, so duplicate messages are sent every time when the bot is rebooted.

i tried to use the cached_messages function by referring to the docs to solve this but i can't figure it out as a beginner, it's too difficult for me to do alone. could please help me to give some advices. is discord.py a function that detects old messages in the channel?

vale wing
#

Pretty sure wrong callback function signature

slate swan
buoyant knot
#

the code/bot gets stuck before reaching the vc.play line

vale wing
#

You should subclass the view instead of assigning callback function

#

And yeah one of your callbacks is sync for some reason

vale wing
slate swan
#

sorry what this error mean `nextcord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction

The above exception was the direct cause of the following exception:

nextcord.errors.ApplicationInvokeError: Command raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction`

vale wing
#

You can't clarify it gets stuck there cause code ends there 🧐

buoyant knot
#

i will, but like- it doesnt even reach the print before the .play

vale wing
#

Ah

#

Then print channel before connect

#

And you should be getting error actually

#

You might have improper error handler

vale wing
slate swan
#

i see

slate swan
vale wing
#

Actually personally I hate callbacks so I did a neat thing that allows you to get which button was pressed without them, check this out https://github.com/Exenifix/disnake-bot-template-postgres/blob/master/utils/views.py it's for disnake but similar principle in dpy

GitHub

A template for speeding up development of discord bots using disnake and postgresql - disnake-bot-template-postgres/views.py at master · Exenifix/disnake-bot-template-postgres

vale wing
#

And it's interaction.response.defer()

#

Not interaction.deferReply

vale wing
#

import it

slate swan
#

how it import it

vale wing
#

by importing

slate swan
vale wing
#
import asyncio```
slate swan
#

lol ok

slate swan
#

it do nothing

#

it say nextcord.errors.InteractionResponded: This interaction has already been responded to before

naive briar
#

Or just you don't even know what it does

slate swan
slate swan
vale wing
slate swan
#

Yeah then its .response.send_modal()

#

of modal?

vale wing
#

Nah where you defer

slate swan
#
  async def buttom3_callback(self):
            
            embed=discord.Embed(title=f"Fall Form",description=f"**You Doing Amazing!** You Did All The Steps Now Just Full The Page And the **Cross Chat** Will be **Done!**",color=0xff7d00)
            await message1.edit("**CrossServer Chat StartUp**", embed=embed,view=None)
            interaction.response.defer()
            await asyncio.sleep(3)
            modal = Crosschat()
            await interaction.response.send_modal(modal)```
vale wing
#

You probably already responded to interaction

naive briar
#

You didn't even await defer 🧐

vale wing
#

Yes that's first of all

slate swan
vale wing
#

Deferring basically makes discord wait until you respond

slate swan
#

i see

#

but i want close the response

vale wing
#

Without deferring you have to respond within 3 seconds

slate swan
#

well followup does not have send_modal

slate swan
#

Too easy solution

vale wing
#

Who would even need to send modal in followup

slate swan
vale wing
#

🧐

#

Only way to send a modal with followup is to add a button to followup and then send modal in response to button interaction

slate swan
#

yes pls

#

Ok i will make button 1 sec brb

slate swan
tawdry karma
tawdry karma
slate swan
#

yes But still how.

tawdry karma
#

How would you usually 💀

#

Oh

slate swan
#

how trigger it when i click the button.

tawdry karma
#

interaction.response.send_modal(modal)

slate swan
tawdry karma
slate swan
naive briar
#

No

#

If you haven't responded before

slate swan
#

i have button4_callback but the idea not here, the idea that how we gonna call modal without interaction

tawdry karma
slate swan
slate swan
naive briar
#

Why

slate swan
tawdry karma
slate swan
#

message1 = await interaction.send("**CrossServer Chat StartUp**", embed=embed, view=myview, ephemeral=True)

naive briar
#

The interaction of the slash command and the button are different

slate swan
slate swan
tawdry karma
slate swan
#

no you not see

naive briar
#

Send the code then

slate swan
#

let em try again

slate swan
# naive briar Send the code then

this should be the call back async def buttom4_callback(self): await asyncio.sleep(3) modal = Crosschat() interaction.response.send_modal(modal)

naive briar
#

Await the send_modal

slate swan
#

like what is say

slate swan
slate swan
naive briar
#

That doesn't exist

tawdry karma
#

no sorry

naive briar
#

!traceback

unkempt canyonBOT
#
Traceback

Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.

A full traceback could look like:

Traceback (most recent call last):
  File "my_file.py", line 5, in <module>
    add_three("6")
  File "my_file.py", line 2, in add_three
    a = num + 3
        ~~~~^~~
TypeError: can only concatenate str (not "int") to str

If the traceback is long, use our pastebin.

slate swan
#
  File "C:\Users\Ibrah\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ui\view.py", line 396, in _scheduled_task
    await interaction.response.defer()
  File "C:\Users\Ibrah\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\interactions.py", line 699, in defer
    await adapter.create_interaction_response(
  File "C:\Users\Ibrah\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\webhook\async_.py", line 204, in request
    raise NotFound(response, data)
nextcord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction
tawdry karma
#

... the problem is with defer()

slate swan
#

? wait

slate swan
tawdry karma
#

nvm

naive briar
#

Did you do something with the response before calling the defer

slate swan
naive briar
#

Weird

slate swan
#

ikr

tawdry karma
#

Can you show us the command?

slate swan
#

all the command?

#
@bot.slash_command(name='crossserverschat', description="Chat Between Servers")
async def crosserverschat(interaction: discord.Interaction, option: Literal['add', 'remove']):
    if option == "add":
        buttom1 = Button(label="Let's Go!", style=ButtonStyle.blurple)
        buttom2 = Button(label="Got It!", style=ButtonStyle.blurple)
        buttom3 = Button(label="Got It!", style=ButtonStyle.blurple)
        buttom4 = Button(label="Fall Form!", style=ButtonStyle.blurple)
        embed=discord.Embed(title=f"Introduction",description=f"Hello And Welcome In **CrossServer Chat** Service! \u200bYou Could Chat Other Servers With This Server \u200bI Hope You Enjoy Our Service, **Let's Start!**",color=0xff7d00)
        myview = View(timeout=500)
        myview.add_item(buttom1)
        message1 = await interaction.send("**CrossServer Chat StartUp**", embed=embed, view=myview, ephemeral=True)
        async def buttom1_callback(self):
            embed=discord.Embed(title=f"Step 1",description=f"You Frist Need Enable SomeThing Called **Developer Mode** \u200bBy Going **Settings\\Advanced\\Developer Mode**",color=0xff7d00)
            embed.set_image(url='https://cdn.discordapp.com/attachments/1054074031642521681/1091603482013876245/image.png')
            myview = View(timeout=500)
            myview.add_item(buttom2)
            await message1.edit("**CrossServer Chat StartUp**", embed=embed, view=myview)
        async def buttom2_callback(self):
            embed=discord.Embed(title=f"Step 2",description=f"**Great Job!**, Now You Need Right Click The Server that You Want **Cross Chat** With and Go Down Until You Find Something Called **Copy ID** Click at It!",color=0xff7d00)
            embed.set_image(url='https://cdn.discordapp.com/attachments/1054074031642521681/1091616490576412713/image.png')
            myview = View(timeout=500)
            myview.add_item(buttom3)
            await message1.edit("**CrossServer Chat StartUp**", embed=embed, view=myview)
        async def buttom3_callback(self):
            myview = View(timeout=500)
            myview.add_item(buttom4)
            embed=discord.Embed(title=f"Fall Form",description=f"**You Doing Amazing!** You Did All The Steps Now Just Full The Page And the **Cross Chat** Will be **Done!**",color=0xff7d00)
            await message1.edit("**CrossServer Chat StartUp**", embed=embed,view=myview)
        async def buttom4_callback(self):
            await asyncio.sleep(3)
            modal = Crosschat()
            interaction.response.send_modal(modal)
        buttom1.callback = buttom1_callback
        buttom2.callback = buttom2_callback
        buttom3.callback = buttom3_callback
        buttom4.callback = buttom4_callback```
#

@tawdry karma got any idea how fix it?

tawdry karma
#

reading

naive briar
#

And why is there a self argument in the button callbacks

#

Shouldn't it be interaction

slate swan
tawdry karma
#

That's what I am thinking

slate swan
#

hm

tawdry karma
#

waaaitt

slate swan
#

i was got an error of something and i look at google and it say put "self" and i put it lol

tawdry karma
#

In your code

tawdry karma
#

Oh yea

#

Yea I think it taking self works because it takes the interaction before it

slate swan
#

yep.

tawdry karma
#

This is harrdd

slate swan
#

but we need put interaction

#

i replace self with interaction

#

and wow nextcord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction

#

python werid dead

tawdry karma
#

fr

slate swan
#

any way to solve this problem?

tawdry karma
#

I know there is since I faced the same problem and did it

slate swan
#

and what was the solve of this error?

tawdry karma
#

I don't know thinkmon

naive briar
#

The code is too confusing

#

I don't even what button does what

tawdry karma
#

Make sure you put await before your interaction response. Always

tawdry karma
slate swan
tawdry karma
#

I'm not on pc

slate swan
#

check life files

tawdry karma
#

alr

slate swan
#

guys guess what

tawdry karma
#

Elon musk died?

slate swan
#

i don't even put await

slate swan
rotund creek
slate swan
#

ye just check rn

tawdry karma
#

Ok then try code after putting await

slate swan
#

sure

#

but pc will crash

rotund creek
#

You think it's a good idea to host discord bots for people for $2

slate swan
slate swan
rotund creek
#

@slate swan nice banner

slate swan
#

nextcord.errors.ApplicationInvokeError: Command raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction

slate swan
slate swan
# tawdry karma Ok then try code after putting await
  File "C:\Users\Ibrah\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\application_command.py", line 848, in invoke_callback_with_hooks
    await self(interaction, *args, **kwargs)
  File "c:\Users\Ibrah\Desktop\Code\Python\main.py", line 1493, in crosserverschat
    message1 = await interaction.send("**CrossServer Chat StartUp**", embed=embed, view=myview, ephemeral=True)``` bruh
slate swan
#

faxs

tawdry karma
slate swan
# tawdry karma Is that all?

`Ignoring exception in command <nextcord.application_command.SlashApplicationCommand object at 0x00000120F3B61480>:
Traceback (most recent call last):
File "C:\Users\Ibrah\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\application_command.py", line 848, in invoke_callback_with_hooks
await self(interaction, *args, **kwargs)
File "c:\Users\Ibrah\Desktop\Code\Python\main.py", line 1493, in crosserverschat
message1 = await interaction.send("CrossServer Chat StartUp", embed=embed, view=myview, ephemeral=True)
File "C:\Users\Ibrah\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\interactions.py", line 564, in send
return await self.response.send_message(
File "C:\Users\Ibrah\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\interactions.py", line 893, in send_message
await adapter.create_interaction_response(
File "C:\Users\Ibrah\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\webhook\async_.py", line 204, in request
raise NotFound(response, data)
nextcord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction

The above exception was the direct cause of the following exception:`

tawdry karma
#

jsjsidinf

#

alr brb

slate swan
#

:0

tawdry karma
#

Or pennies

rotund creek
#

So I should do 50c

vale wing
#

Unless you containerise

glad cradle
glad cradle
slate swan
#

nvm

vale wing
#

But then I remembered the date

#

Next.js affected my braincells a lot

vocal snow
#

js tends to have that effect

tawdry karma
rotund creek
rotund creek
raw quail
#
async def cer(self, ctx):
    while True:
        try:
            channel = self.bot.get_channel(channel_id)
            err_message = self.bot.get_channel(err_channel)
            title = "test title"
            end = 'duplicate'

            async for msg in channel.history(limit=1):
                if title not in msg.content:
                    await channel.send(title, delete_after=5)
                elif title in msg.content:
                    await channel.send(end, delete_after=5)
                else:
                    pass

                

        except Exception as e:
            embed=discord.Embed(title="❗ error ❗", color=0xff0000)
            embed.add_field(name=e, value="", inline=False)
            await err_message.send(embed=embed, delete_after=1)

        await asyncio.sleep(3)

i'm trying to implement a feature that doesn't send messages that are duplicates of the last message in the channel. the bot powers up with no error code, but nothing happens when i type a command. is there any mistakes i made?

vale wing
#

!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").
raw quail
#

ohhh thank you i will check up

tawdry karma
#

20000/50=4000

native lance
#

An year ago or so, I heard that discord is forcing slash commands

#

so why do some bots still work the same way as before

#

like, I can still use a bot like this
k!info
Why

#

what was that fuss about

native lance
#

I mean, normal commands were supposed to stop working werent they?

naive briar
#

No

native lance
#

so what was that about discord forcing slash commands

naive briar
#

They just make accessing messages' content a privileged intent

native lance
#

what does it mean

native lance
#

If i do
pip install discord.py will it automatically install discord.py 2 (I mean the version where slash commands are present)

meager chasm
#

!dashmpip

unkempt canyonBOT
#
Install packages with `python -m pip`

When trying to install a package via pip, it's recommended to invoke pip as a module: python -m pip install your_package.

Why would we use python -m pip instead of pip?
Invoking pip as a module ensures you know which pip you're using. This is helpful if you have multiple Python versions. You always know which Python version you're installing packages to.

Note
The exact python command you invoke can vary. It may be python3 or py, ensure it's correct for your system.

meager chasm
#

So py -m pip install -U discord.py

rotund creek
#

I kinda wanna start a affordable hosting service

raw quail
#
class Testings(commands.Cog):
    def __init__(self, bot):
        self.bot = bot


    @tasks.loop(seconds=3)
    async def cer(self, ctx):
        try:
            channel = self.bot.get_channel(channel_id)
            err_message = self.bot.get_channel(err_channel)
            title = "test title"
            end = 'duplicate'

            async for msg in ctx.channel.history(limit=1):
                if title not in msg.content:
                    await channel.send(title, delete_after=10)
                else:
                    pass

                

        except Exception as e:
            embed=discord.Embed(title="❗ error ❗", color=0xff0000)
            embed.add_field(name=e, value="", inline=False)
            await err_message.send(embed=embed, delete_after=1)
            
            
    @commands.command()
    async def test(self, ctx):
        task1 = self.bot.loop.create_task(self.cer(ctx))

        await task1





    async def setup(bot):
        await bot.add_cog(Testings(bot))

i tried to make the code with task.loop but its not working infinity loop. could you guys please check the code and advice for me?

slate swan
#

thats not how you use tasks.loop

#

you should use .start() on you task

#

not with loop.create_task()

#

also task doesn't get ctx as an argument, it doesn't get any

#

in your command do self.cer.start()

#

and you can stop it using self.cer.cancel() or self.cer.stop()

#

hi

blissful badge
#

Hi needing some help with an embed command. I have made a ton of headway thanks to people (mudkip) here.

I am working on my final feature for this command which sends a preview of the embed into the channel that the command was issued in so the author can respond "yes" or "no" and if its yes it will post it to its destination channel, and if not it will stop the command entirely.

I am having an issue where it posts the preview embed but then based on yes or no responses it doesn't do anything....any ideas?

    @commands.command()
    async def embed(self, ctx):
        def check(message):
            return message.author == ctx.author and message.channel == ctx.channel

        await ctx.send('Waiting for a title')
        title = await self.bot.wait_for('message', check=check)
  
        await ctx.send('Waiting for a description')
        desc = await self.bot.wait_for('message', check=check)

        await ctx.send('Please provide me with the image (directly paste or attach image, no need for link) for this post, if no image is needed just say none.')
        news_image = await self.bot.wait_for("message", check=lambda m: all([
            m.author == ctx.author,
            m.channel == ctx.channel,
            len(m.attachments) == 1 or "none" in m.content.lower()
            ]))

        if news_image.attachments:
            embed.set_image(url=news_image.attachments[0].url)

        embed = discord.Embed(title=title.content, description=desc.content, color=0x1ABC9C)
        embed.set_thumbnail(url="https://imgur.com/MJnM3LU.png")

        await ctx.send('What channel should I send this in? Please provide me with the channel ID.\n- #news: 569635458183856149\n- #general-news: 803341100618219540\n- #patch-notes: 585952222853201941')
        dest = await self.bot.wait_for('message', check=check)

        await ctx.send('Who should I tag? Please provide me with the role ID.\n- news: 620025828079697920\n- gennews: 803343410794594385\n- patchnotes: 620025894559547412')
        role_message = await self.bot.wait_for('message', check=check)

        await ctx.send('What is the tag preview?')
        tag_preview = await self.bot.wait_for('message', check=check)

        await ctx.send('Does this look correct? Please say yes or no.')
        channel = self.bot.get_channel(1065685023853920258)
        await channel.send(embed=embed)
        await self.bot.wait_for('message', check=check) 
        if "yes" in ctx.message.content.lower():
            channel = self.bot.get_channel(int(dest.content))
            await channel.send(embed=embed)
            await channel.send(f"<@&{role_message.content}> - {tag_preview.content}")
        if "no" in ctx.message.content.lower():
            await channel.send('The embed has been cancelled, please try again.')

the issue code in question is the last bit which begins with "await ctx.send('Does this look correct?')"

tawdry karma
#

But that is a bit expensive

#

I feel that it is hard to start a hosting service and be succesful with it

rotund creek
#

i dont wanna be successfull from the start

tawdry karma
#

You could try get members to sign up first and then if you reach a certain member count then you launch

rotund creek
#

i can just do like $3 per month

#

but idk if anyone will trust a new business

tawdry karma
#

That is also a fair point

raw quail
tawdry karma
#

This has moved from discord bot discussion to a different topic so we should change channels

raw quail
#
import discord
import asyncio
from discord.ext.commands import Bot, has_permissions, MissingPermissions, Cog
from discord.ext import tasks, commands

class Testings(commands.Cog):
    def __init__(self, bot: commands.bot):
        self.bot = bot
        self.cer.start()

    @tasks.loop(seconds=5, count=None, reconnect=True)
    async def cer(self):
        await self.bot.wait_until_ready()
        channel = self.bot.get_channel(channel_id)
        try:
            title = "test title"
            end = 'duplicate'
            async for msg in channel.history(limit=1):
                if title not in msg.content:
                    await channel.send(title, delete_after=10)
                else:
                    await channel.send(end, delete_after=10)

                    

        except Exception as e:
            embed=discord.Embed(title="❗ error ❗", color=0xff0000)
            embed.add_field(name=e, value="", inline=False)
            await channel.send(embed=embed, delete_after=1)

async def setup(bot):
    await bot.add_cog(Testings(bot))

when i use @tasks.loop and channel.history it's not working without any error codes. or it's just happening on my PC??

slate swan
raw quail
slate swan
raw quail
#

ohh

slate swan
#

are you sure the task is running at all

#

oh also

raw quail
#
intents = discord.Intents.all()
intents.message_content = True
slate swan
#

waiting until bot is ready in a task will dead lock

#

so your task won't go after that line

#

you should do this instead :

#

register a before_loop for your task using @name.before_loop (async function)
wait until ready in there

raw quail
#
    @tasks.loop(seconds=5, count=None, reconnect=True)
    async def cer(self):
        await self.bot.wait_until_ready()
        channel = self.bot.get_channel(channel_id)
        try:
            title = "test title"
            end = 'duplicate'
            async for msg in channel.history(limit=1):
                print('check')
                if title not in msg.content:
                    await channel.send(title, delete_after=10)
                else:
                    await channel.send(end, delete_after=10)

i tried to put print('check') before async for msg in channel.history(limit=1): and it's working but after async for msg in channel.history(limit=1): this line, it's not printing..

slate swan
#

thats wierd

raw quail
#

yes ser

vale wing
slate swan
vale wing
#

Cause for VPS hosting you need a whole data center 😳

raw quail
#
    @cer.before_loop
    async def check(self):
        print('check')
        await self.bot.wait_until_ready()

it's working good

vale wing
#

What was your error again?

vale wing
raw quail
vale wing
#

Your problem was that you were assigning callbacks to individual components instead of subclassing. You need to either subclass View and define callbacks as its methods or use my callbacks-free implementation

raw quail
vale wing
#

And I am pretty sure there's almost same example on docs

raw quail
vale wing
# vale wing Your problem was that you were assigning callbacks to individual components inst...

Subclassing way

# command
view = YourView()
await inter.send(view=view)

# view class
class YourView(discord.ui.View):
    @discord.ui.button(label="Cheese")
    async def cheese(self, inter, btn):  # signature might be different, I just don't know dpy
        await inter.send("You picked cheese!")

    @discord.ui.button(label="Pickle")
    async def pickle(self, inter, btn):
        await inter.send("You picked pickle!")

And with callbacks-free method

view = GenericView([
  GenericButton(label="Cheese"),
  GenericButton(label="Pickle")
])
await inter.send(view=view)
msg_inter, choice = await view.get_result()
await msg_inter.send(f"You picked {choice.lower()}!")
#

It's partially pseudocode

cloud dawn
raw quail
#

i was trying to use history function to a thread not a channel

#

if i wanna use channel.history function, i should use while True:. if use @tasks.loop, it's not working with a thread

naive briar
#

What 🧐

ebon island
#

What is currently the best wrapper for Discord in Python?

#

I hear discord.py is revived, how is it compared to say Disnake? I am considering leaving Disnake because I was using WaveLink previously with Discord-Disnake but that is no longer maintained and Mafic seems a little limited at the present moment in terms of available functionality

uneven apex
#
NoneType: None
#

i am getting this error while creating a private category using my discord.py bot

#
    try:    
        guild = ctx.guild
        cat = await guild.create_category(name=category_name)
    except:
        await ctx.send('`ERROR: Unable to create category`')
        return
    
    everyone_role = discord.utils.get(guild.roles, id=1070556590505209897)
    applicant_role = discord.utils.get(guild.roles, name="applicant")
    admin_role = discord.utils.get(guild.roles, name='league admin')
    admin_overwrite = rep_overwrite()

    try:
        await cat.set_permissions(applicant_role, read_messages=False)
        await cat.set_permissions(admin_role, overwrite=admin_overwrite)
        await cat.set_permissions(everyone_role, read_messages=False)
    except Exception as e:
        print(e)
        await ctx.send('error')
        return```
#

this is the code block which is generating this error

raw quail
#

is there any ways to find the title text of embed with channel.history ??

naive briar
#

Yes?

#

!d discord.Embed.title

unkempt canyonBOT
#

The title of the embed. This can be set during initialisation. Can only be up to 256 characters.

raw quail
# naive briar !d discord.Embed.title

i am trying to make a bot for detect old Embed message in text channel. but i think it's not possible to find text of title of old Embed message with channel.history function.

hushed galleon
raw quail
#

Ohhhhh

#

Thank you so much sir!!

smoky sinew
#
async for message in channel.history(limit=50):
    for embed in message.embeds:
        print(embed.title)
#

or just do this

elder kettle
#

can anyone help

upbeat ice
#

probably

smoky sinew
#

perhaps

slate swan
#

possibly

potent spear
#

it depends

proven venture
#

does anybody know why i get the error 'Embed' object has no attribute '_json'

#

i am trying to create an embed responding to a message, somehow all my other embeds work

#

has anybody experienced this error?

thin raft
#

!code

unkempt canyonBOT
#
Formatting code on discord

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

For long code samples, you can use our pastebin.

slate swan
#
import discord
from discord_slash import SlashCommand, SlashContext
from discord_slash.utils.manage_commands import create_option
import aiohttp

bot = discord.Client(intents=discord.Intents.default())
slash = SlashCommand(bot, sync_commands=True)

async def fetch_image_url(session, url):
    async with session.get(url) as response:
        data = await response.json()
        return data['data']['url']

@slash.slash(name="sadcat",
             description="Generates a sad cat meme with the provided text.",
             options=[
                 create_option(
                     name="text",
                     description="The text to include in the meme.",
                     option_type=3,
                     required=True
                 )
             ])
async def _sadcat(ctx: SlashContext, text: str):
    url = f"https://api.popcat.xyz/sadcat?text={text}"

    async with aiohttp.ClientSession() as session:
        image_url = await fetch_image_url(session, url)
        embed = discord.Embed()
        embed.set_image(url=image_url)
        await ctx.send(embed=embed)

bot.run('TOKEN')
#

there @slate swan

glad cradle
#

bruh

#

discord_slash

hushed galleon
#

^ @slate swan ive linked an example, guide, and docs here, assuming you're using discord.py 2.0

smoky sinew
#

also don't just code someone's bot for them, that won't teach them anything

placid skiff
#

Someone knows how to solve this error?

smoky sinew
glad cradle
placid skiff
smoky sinew
#

yes

placid skiff
#

they doesn't even have it xD

glad cradle
placid skiff
#

they have parameters in the command function, but not as CommandOption parameter

placid skiff
glad cradle
#

ahah

placid skiff
#

Time to remove them xD

glad cradle
#

discord.py or whatever you're using is parsing function's docstrings and using them as descriptions

smoky sinew
#

disnake

glad cradle
#

disnake my beloved

unkempt canyonBOT
smoky sinew
#

read what the bot said

merry cliff
#

!paste

unkempt canyonBOT
#
Pasting large amounts of code

If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

smoky sinew
#

your issue is that you are doing embeds=embed1 though

proven venture
smoky sinew
#

embeds is supposed to be a list

#

not an embed

#

you need to do embed=embed1

proven venture
#

embed was replaced by embeds I guess

smoky sinew
#

no it was not

#

maybe in interactions

#

try embeds=[embed1]

proven venture
#

going through all possible errors

smoky sinew
#

what is your new code

#

why are you using interactions anyway

proven venture
proven venture
smoky sinew
#

yes

proven venture
#

I will but since I wrote the whole code in interactions I have no motivation changing it to dc py 2.0

proven venture
tough mirage
#
PS C:\Users\Madth\Documents\Projects\discord slash> & C:/Users/Madth/AppData/Local/Programs/Python/Python311/python.exe "c:/Users/Madth/Documents/Projects/discord slash/discord.py"
Traceback (most recent call last):
  File "c:\Users\Madth\Documents\Projects\discord slash\discord.py", line 1, in <module>
    import discord
  File "c:\Users\Madth\Documents\Projects\discord slash\discord.py", line 5, in <module>
    from discord.ext import commands, tasks
ModuleNotFoundError: No module named 'discord.ext'; 'discord' is not a package```

never got this error before, discord is fully installed, if I try to run pip install I get, Requirement already satisfied.
tough mirage
#

oh, thanks

tough mirage
#

I have discord-py-slash-command installed but keep getting error,

Traceback (most recent call last):
 File "c:\Users\Madth\Documents\Projects\discord slash\main.py", line 9, in <module>
   from discord_slash import SlashCommand
ModuleNotFoundError: No module named 'discord_slash'```
smoky sinew
#

see this

glad cradle
slate swan
smoky sinew
wild spoke
#

can someone help with jsons?

#

or("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

I get this whenever im trying to load

try:
        with open('allowed_users.json', 'r') as f:
            allowed_users = json.load(f)
except FileNotFoundError:
    allowed_users = []         
``` (i guess?)
#

file only has []

naive briar
#

You sure?

slate swan
#
options = [discord.ui.SelectOption(label=channel.name, value=channel.id) for channel in channels]
select = Select(options=options, placeholder='Select channel(s)', min_values=1, max_values=len(channels))
Traceback (most recent call last):
  File "C:\Users\**\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 842, in _do_call
    return await self._callback(interaction, **params)  # type: ignore
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\**\Desktop\**\main.py", line 624, in end
    await interaction.response.send_message(interaction.user.mention, embed=embed, view=select)
  File "C:\Users\**\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\interactions.py", line 763, in send_message
    params = interaction_message_response_params(
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\**\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\webhook\async_.py", line 578, in interaction_message_response_params
    data['components'] = view.to_components()
                         ^^^^^^^^^^^^^^^^^^
AttributeError: 'Select' object has no attribute 'to_components'
#

any fix?

smoky sinew
#

why not just use a ChannelSelect

slate swan
# smoky sinew why not just use a ChannelSelect
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'end' raised an exception: AttributeError: 'ChannelSelect' object has no attribute 'to_components'```
```py
options = [discord.SelectOption(label=channel.name, value=channel.id) for channel in channels]
select = ChannelSelect(channel_types=options, placeholder='Select channel(s)', min_values=1, max_values=len(channels))```
smoky sinew
#

view is supposed to be a View object, not a select

slate swan
#

thought that was only for buttons

smoky sinew
#

but yeah

#

<@&831776746206265384>

slate swan
# smoky sinew i mean, you tried passing the select to the view argument
In data.components.0.components.0.channel_types.0: Value "1090332444667949166" is not a valid enum value.
In data.components.0.components.0.channel_types.1: Value "1090333038459756647" is not a valid enum value.
In data.components.0.components.0.channel_types.2: Value "1090348367160295558" is not a valid enum value.
In data.components.0.components.0.channel_types.3: Value "1090377583880835172" is not a valid enum value.
In data.components.0.components.0.channel_types.4: Value "1090395131993149510" is not a valid enum value.
In data.components.0.components.0.channel_types.5: Value "1090419907075784754" is not a valid enum value.
In data.components.0.components.0.channel_types.6: Value "1090420244260069457" is not a valid enum value.
In data.components.0.components.0.channel_types.7: Value "1090420258180964413" is not a valid enum value.
In data.components.0.components.0.channel_types.8: Value "1090420275117559818" is not a valid enum value.
In data.components.0.components.0.channel_types.9: Value "1090420288623235154" is not a valid enum value.
In data.components.0.components.0.channel_types.10: Value "1090420302732865566" is not a valid enum value.
In data.components.0.components.0.channel_types.11: Value "1090420834763538603" is not a valid enum value.
In data.components.0.components.0.channel_types.12: Value "1090420894079385770" is not a valid enum value.
wise jewel
#

!pban 1091186253883506799 scam

unkempt canyonBOT
#

:incoming_envelope: :ok_hand: applied ban to @young geode permanently.

wise jewel
smoky sinew
#

actually i'm not sure if you can select the options using ChannelSelect, you might only be able to select the types

#

e.g. text, voice, stage

#

so that might not be what you want

slate swan
# smoky sinew channel_types is not for the options

what I want is to list all textchannels (channel is an instance of discord.TextChannel) and iterate over them and put them in the select menu. The user can select as many as len(channels) but a min of 1

grand hazel
#

how to use the permission join server for you in a diacord bot?

grand hazel
#

how to use it to make people that accepted the permission join a server that i want

smoky sinew
#

and remove your loop

slate swan
grand hazel
slate swan
#

idk if thats against rules here lmao

grand hazel
slate swan
#

or just ask gpt

naive briar
#

Anything but chatgpt

grand hazel
grand hazel
slate swan
naive briar
#

How did you come to the point where you need ChatGPT to organize your code

slate swan
grand hazel
#

"ai's gonna rule the world" 💀

slate swan
grand hazel
#

okay wait

slate swan
#

idk try that

grand hazel
#

same result lol

smoky sinew
#

@grand hazel

#

once you've authenticated the user, send a PUT request to /guilds/<guild>/members/<member>

slate swan
smoky sinew
#

because you have no callback?

#

what did you expect to happen

#

there is no such event as "select_option"

grand hazel
slate swan
smoky sinew
slate swan
smoky sinew
#

no such event

grand hazel
slate swan
#

how do I create a callback for it?

smoky sinew
#

just create a new class extending View and use the select decorator

ebon island
#

What package is currently the best for Discord in Python?

I hear discord.py is revived, how is it compared to say Disnake?

I am considering leaving Disnake because I was using WaveLink previously with Discord-Disnake but that is no longer maintained and Mafic seems a little limited at the present moment in terms of available functionality so I definitely want one that works well with some sort of LavaLink wrapper, preferably one that is full featured, any info/thoughts definitely appreciated 🙂

smoky sinew
#

or hikari 😁

ebon island
#

How is dpy after the restart? I have only just started hearing about Hikari, how is support and is there a good Lavalink wrapper for it?

fading marlin
#

aren't lavalink wrappers completely independent from the library you're using?

ebon island
#

Yes, but not all are compatible with the given library

#

Wavelink for example is not compatible with Disnake

#

which is why I'm looking for potential alternatives to Disnake

fading marlin
#

dpy is quite complete 🤷

ebon island
#

hmm, alright, I guess in the coming days I'll make the change over to dpy and see how it goes

slate swan
#

any suggestions for oauth2 and flask? I just wanna get each users twitch connections, add it to a db and then send a req to decapi to get each usernames twitch_id. its for a sqlalchemy db ;.;

shrewd apex
#

fastapi

supple cradle
#

Hello 👋 I am currently working on a Discord bot because I haven't worked on one in a while now and thought it would be fun. I am currently trying to implement cogs into my bot but whenever I try to use a command that is from a file inside the cogs folder it says that there is no such command...

#

Any help would be appreciated

#

Please ping me if you know how to assist me

vocal snow
supple cradle
#

I opened up a new file and did the same thing and now its working

#

so idk whats up with that old file

#
import discord
from discord.ext import commands
from discord import app_commands
from colorama import Back, Fore, Style
import time
import platform

class Client(commands.Bot):
    def __init__(self):
        super().__init__(command_prefix=commands.when_mentioned_or('s!'), intents=discord.Intents().all())

        self.cogslist = ["cogs.startup"]

    async def setup_hook(self):
      for ext in self.cogslist:
        await self.load_extension(ext)

    async def on_ready(self):
        prfx = (Back.BLACK + Fore.GREEN + time.strftime("%H:%M:%S UTC", time.gmtime()) + Back.RESET + Fore.WHITE + Style.BRIGHT)

        print(prfx + " Logged in as " + Fore.YELLOW + self.user.name)
        print(prfx + " Bot ID " + Fore.YELLOW + str(self.user.id))
        print(prfx + " Discord Version " + Fore.YELLOW + discord.__version__)
        print(prfx + " Python Version " + Fore.YELLOW + str(platform.python_version()))


client = Client()
client.run('TOKEN')
#
import discord
from discord.ext import commands
import os
import asyncio

client = commands.Bot(command_prefix = "!", intents=discord.Intents.all())
client.remove_command('help')

async def load_extensions():
        for f in os.listdir("./cogs"):
                if f.endswith(".py"):
                        await client.load_extension("cogs." + f[:-3])
        
async def main():
    async with client:
        await load_extensions()
        await client.start('TOKEN')

asyncio.run(main())
#

I also tried this way as well

#

both didn't work in that file and now I am in a new one and I am using the second version of the code

vocal snow
supple cradle
#
import discord
import os
from discord.ext import commands


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

        @commands.Cog.listener()
        async def on_ready(self):
            print('Bot is up and running!')

        @commands.command(name="Test", description="Sends a test response.")
        async def test(self, ctx):
            await ctx.send('Working!')

async def setup(client):
    await client.add_cog(startupCog(client))
vocal snow
#

Are the normal prefix commands working?

supple cradle
#

nothing from the cog is working

vocal snow
#

And you aren't getting any errors?

supple cradle
#

Nope

#

only error I am getting is when I type a command

#

it says that the command doesn't exist

vale wing
#

@supple cradle could you please show your files hierarchy

supple cradle
#

The order?

vale wing
#

File structure, like this

#

(i am losing braincells with next.js don't pay attention)

supple cradle
#

Like this?

vale wing
#

Yeah you should open specifically Saturn-Bot folder in VSC, most likely your extensions path is just not resolved correctly due to wrong workdir

supple cradle
#

Got it open

vale wing
#

No I mean when running a script your project root folder should be Saturn-Bot

#

Now try running it

supple cradle
#

Alright

#

Trying it now

vale wing
vale wing
#

I mean command line command

#

Should be like your/path> py main.py

supple cradle
#

oh ok

#

let me send a ss

#

May look long but my mac name is the alphabet lol

#

I'll change it for better reading

supple cradle
glad cradle
vale wing
#

😳

shrewd apex
supple cradle
vale wing
#

Are you on mac or linux

supple cradle
#

Mac

vale wing
#

Now please screenshot file hierarchy again

vale wing
supple cradle
vale wing
#

Yeah

supple cradle
#

ok

vale wing
#

Your root folder still isn't Saturn-Bot

supple cradle
#

still doesnt work that way

vale wing
supple cradle
#

still not work

slate swan
#

I liked that yellow name Sadeg

glad cradle
#

he could also use absolute paths for the cogs, can't he?

glad cradle
slate swan
drifting arrow
#

What am I doing wrong?
I have a button:

@discord.ui.button(label="Add note", style=discord.ButtonStyle.green, row=0)
    async def add_note(self, interaction: discord.Interaction, button: discord.ui.Button):
        note_ui = Note()
        note_ui.bmid = self.original_ids.bmid
        print(self.original_ids)
        print(self.original_ids.bmid)
        print(note_ui.bmid)
        await interaction.response.send_modal(Note())

And that button calls a modal:

class Note(discord.ui.Modal, title='Gnomeslayers note maker.'):
    def __init__(self):
        super().__init__()

    bmid = 0
    note = discord.ui.TextInput(
        label='Note for this users profile',
        style=discord.TextStyle.long,
        placeholder='Type the note here.',
        required=True,
    )

Why is the bmid not updating? It works for my buttons? D:

glad cradle
#

wrong indentation levels

drifting arrow
#

no.

#

That's just how it pastes

#

nvm figured it out LOL

#

i think.

#

Yep.

#

I didn't realize I was submitting the base class and not the variable await interaction.response.send_modal(Note()) needed to be await interaction.response.send_modal(note_ui)

viral stump
#

My bot's FFMPEG is not working for some reason, is there a bug right now?

slate swan
viral stump
#

bot was working perfectly but for some reason it doesnt play any ffmpeg file now. i havent touched anything

slate swan
viral stump
slate swan
#

oh ive never seen someone usd it in that way... always in a music bot that plays off youtube

viral stump
#

but weird one is there is not any error or something, bot joins vc and just stands like that

deft quartz
#

I have a select menu where i have 46 options in 6 different categories. Is there any way to do this? I know the select menu has a limit of 25 and the rows have a limit of 5 so i cannot do that with the categories either

viral stump
unkempt canyonBOT
#

Hey @viral stump!

You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.

viral stump
#

bot is coming but not doing anything

vocal snow
viral stump
vocal snow
#

but you aren't importing it in your main code

viral stump
#

check 264

vocal snow
#

oh i see

#
    def after_play(e):
        # We have to hook into asyncio here as voice_client.play
        # runs the Callable it's given without await'ing it
        # Basically this just calls `kick_member_and_disconnect`
        asyncio.run_coroutine_threadsafe(kick_member_and_disconnect(), bot.loop)
#

you should handle the error in this callback instead of ignoring it

#

e parameter is Optional[Exception]

slate swan
#

yo. could i possibly get some help with an error pls

viral stump
slate swan
#

initially got this error - 'Bot' object has no attribute 'tree' so i made a tree with app_commands from discord.py but now this error occurred ImportError: cannot import name 'AppCommandOptionType' from 'discord.enums'

#

pls help i'm legit stuck with this for about 2 days now 😭

vocal snow
#

also make sure discord.py is up to date; python -m pip install -U discord.py

slate swan
slate swan
vocal snow
slate swan
# vocal snow can you show the full traceback?

c:/Users/DINESH/Downloads/ambarfinal/super/main.py
Traceback (most recent call last):
File "c:\Users\DINESH\Downloads\ambarfinal\super\main.py", line 5, in <module>
from discord import app_commands
File "C:\Users\DINESH\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands_init_.py", line 12, in <module>
from .commands import *
File "C:\Users\DINESH\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 51, in <module>
from ..enums import AppCommandOptionType, AppCommandType, ChannelType, Locale
ImportError: cannot import name 'AppCommandOptionType' from 'discord.enums' (C:\Users\DINESH\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\enums.py)

slate swan
vocal snow
slate swan
#

one sec, will check 🤧

#

nope, still won't work

#

uninstalled py-cord too

#

would u suggesting downgrading to a lower version?

vocal snow
#

no

#

run pip list and send the output here

slate swan
#

alright. one sec

unkempt canyonBOT
#

Hey @slate swan!

You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.

strong knoll
#

Hey guys, How to get ID of someone in discord.py I am trying to do ban command via ID

slate swan
#

mb

vocal snow
#

looks like you have discord and discord.py installed which might be conflicting

#

you should uninstall the first one

vocal snow
vocal snow
#

which user?

strong knoll
slate swan
strong knoll
vocal snow
#

Are you mentioning the user in a command?

strong knoll
#

No

vocal snow
#

Or accepting their ID as a parameter?

strong knoll
vocal snow
#

so are you asking how you can get a user id from the discord app?

strong knoll
#

.ban (user id)

slate swan
#

no way i'm still getting the same error 😭

#

i uninstalled discord module too

vocal snow
vocal snow
#

and run your code

slate swan
strong knoll
#

ah nvm

vocal snow
#

You need to be more specific with your question;
Are you trying to figure out how to add a user id parameter to the command? Or how to ban a user from their ID?

slate swan
#

anyways getting back to my error

strong knoll
#

I have something like that:
async def ban(ctx, member_id: int, *, reason=None):
print(member_id)
member = member_id
if member_id is not None:
await member.ban(reason=reason)
embed = discord.Embed(title="Ban", description="Sucessful Ban")
embed.add_field(name="User", value=f"Member: {member} Id: {member_id}")
embed.add_field(name="Reason", value=reason)
await ctx.send(embed)
await client.get_channel(1073532895731400777).send(embed)
else:
await ctx.send("Something went wrong.")

#

I try using

#

.ban (user id) (reason)

#

and it didn't work

vocal snow
#

that's not how python works

strong knoll
vocal snow
#

member = member_id doesn't automatically convert a user id to a Member object

slate swan
vocal snow
#

you need to use ctx.guild.get_member / fetch_member to retrieve the corresponding Member object

#

generally you can just typehint the parameter to discord.Member

#

or discord.User

#

async def ban(ctx, member: discord.Member, *, reason: str | None = None):
    ...
strong knoll
vocal snow
#

that is the code

vocal snow
slate swan
#

😭

vocal snow
slate swan
#

yes

#

same error yet again

vocal snow
#

and does it give you an ImportError now?

slate swan
#

i uninstalled py-cord, nextcord, discord, discord.py

#

all of it

vocal snow
slate swan
#

one sec

vocal snow
#

if it's the same error even after uninstall the library then it looks like you have a misconfigured environment

slate swan
#

Traceback (most recent call last):
File "c:\Users\DINESH\Downloads\ambarfinal\super\main.py", line 5, in <module>
from discord import app_commands
File "C:\Users\DINESH\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands_init_.py", line 12, in <module>
from .commands import *
File "C:\Users\DINESH\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 51, in <module>
from ..enums import AppCommandOptionType, AppCommandType, ChannelType, Locale
ImportError: cannot import name 'AppCommandOptionType' from 'discord.enums' (C:\Users\DINESH\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\enums.py)

vocal snow
#

what does py -V give you?

slate swan
#

Python 3.11.2

vocal snow
#

and py -m pip show discord.py?

slate swan
#

2.2.0a4685+g82b12ba4

#

there are no active conda environments either

vocal snow
#

what does py -m pip list give you?

slate swan
#

even after uninstalling pip show discord.py show's the version 😭

slate swan
#

Uninstall didcordpy-interactions

vocal snow
slate swan
slate swan
vocal snow
slate swan
#

thanks a bunch,

vocal snow
#

you also might want to consider using venvs in the future

slate swan
#

i should've done that fr

#

Yeah that's a lot of modules

#

funnily i set it up in a codespace and it worked 😭

#

tysm tho guys

#

at least got this issue fixed for once

#

will use conda in the future

robust fulcrum
#

Guys i want that my discord.py takes input from user for 20 seconds and stops after 20 seconds and if user send input , it should not stop taking input
How can I do that?

vale wing
robust fulcrum
vale wing
#

How

robust fulcrum
#

I mean text input

vale wing
#

Wait for user to send message / send modal

robust fulcrum
#

Send message

vale wing
#

!d discord.ext.commands.Bot.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**...
robust fulcrum
#

It will stop after taking input?

naive briar
#

It stops after it gets an event that passed the check

robust fulcrum
#

I want to do like bot takes input for 20 seconds if user send hi then it will again take input and till user don't send hello it should take input, how to do that?

naive briar
#

Or timing out

shrewd apex
#

use a modal over event any day

robust fulcrum
naive briar
#

Did you look at its docs

#

Because it would immediately answer that question

robust fulcrum
#

Ok I'll see

slate swan
#

but as asher said using a modal is a better way to get input from user

#

Can someone please dm me? I'm having an issue with my bot where the unlock command overwrites private channels

potent spear
potent spear
slate swan
potent spear
#

make sure everything the bot asks (first message in a thread) is answered

slate swan
#

my question met all the requirements the bot had put in the thread

#

alright ill try again

#

guys how get ID of server owner not the server that i do a command a server that i enter there ID

#

any one know?

potent spear
slate swan
potent spear
#

so you just want the owner's user ID of the guild where a command was used?

#

if so, and you're using a "normal command"
it's ctx.guild.owner.id

slate swan
potent spear
#

rephrase your question and explain the use case

slate swan
potent spear
#

aight

#

your bot is in that server, right? else you can't access it

slate swan
potent spear
#

you first get the guild object by using get_guild()
then you just use .owner on that guild object to get the owner's member/user object

potent spear
#

proof?

slate swan
#

aH?

#

serverIDofOther = bot.get_guild(self.name.value)

#

what i do next