#discord-bots

1 messages · Page 286 of 1

slate swan
#

yeah so you do channel.set_permissions(default_role, overwrite) while in the docs its channel.set_permissions(default_role, overwrite=overwrite)

#

lets rename the docs example so it uses default_role too

#

see difference now

harsh orbit
#

Only I should add =overwrite?

slate swan
#

yes, cause its keyword-only

harsh orbit
#

Finally Io understand wdym by keyward only

#

Thz

slate swan
#

if you look at the docs the overwrite argument is after the * meaning its keyword-only

harsh orbit
#

Yup

bleak atlas
#

How do I make a timestamp in an embed footer, so it's like "Today at XX:XXPM" "Yesterday at XX:XX PM" etc

naive briar
#

Format a string 🤷

turbid condor
#

You might need to do a bit of searching in datetime module for that

#

Cuz i don't think discord.py has that format style in docs

harsh orbit
#

How I can make my bot detect a message after type a command like when I type the command $hellp there are a user should send if he send it the bot will make something
Like I want something like on message but start after command + I want check message startwitth + endwith

slate swan
#

takes a datetime object

naive briar
turbid condor
slate swan
turbid condor
#

I can't understand what are you even trying to say after $hellp

harsh orbit
#

I want something like on_message but it from spisific user + the bot start detect message after command

#

I hope you understand me

harsh orbit
turbid condor
#

like if i write !hellp how are you?
you want to extract the how are you part?

harsh orbit
#

Look

#

Example

#

I typed $hello

turbid condor
#

Ok

harsh orbit
#

There are a specific user should reply with a specific message if that happend the bot will make an action+ that thing happen only one time

#

Not should reply
Only send

#

And I can check it by
Startwitth
Endwith

#

Hope you understand

turbid condor
#

Like a verification system?

harsh orbit
#

What

turbid condor
#

Nvm i still don't get the specific user part

harsh orbit
#

I typed $hello Now the bot wait catlover to reply with hi I'm good if that heppend there is action will hapen

turbid condor
#

Like there will be a specific person that will reply?

harsh orbit
#

Yup

#

So?

turbid condor
#

Welp you can use for bot.wait_for and define a check that will see if the person who replied to the $hello keyword has that id or not

turbid condor
harsh orbit
#

Not argument

#

But how I check it it's from user

#

Than I want

cloud dawn
#

Add a user arg with the correct typehint

#

I'd use member

slate swan
#

!d discord.Client.wait_for Define a check that returns a bool depending on whether the message fits certain criteria

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). 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) 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) 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
#

If it times out you'll have to catch the TimeoutError yourself and do whatever with it

naive briar
cloud dawn
harsh orbit
onyx elk
#

can someone help me make application commands?? in discord.py obviously

onyx elk
#

thanks

turbid condor
#

This contains almost everything u need to know in order to create slash commands

bleak atlas
#

The timestamp now works, but now I want to make it support to reply to a reply, right now it doesn't work:

@commands.Cog.listener()
    async def on_message(self, message):
        if message.channel.id == 1141711874098991166 and not message.reference:
            if message.author == self.client.user:
                return

            if message.attachments:
                attachment = message.attachments[0]
                embed = disnake.Embed(color=0x1da1f2)
                embed.set_image(url=attachment.url)
            else:
                embed = disnake.Embed(color=0x1da1f2)

            if message.content:
                embed.description = f"> {message.content}"

            embed.set_author(name=f"@{message.author.display_name}", icon_url=message.author.avatar.url)
            
            embed.timestamp = message.created_at

            target_channel = self.client.get_channel(1141711874098991166)
            if target_channel:
                sent_embed = await target_channel.send(embed=embed)
                await message.delete()
                while True:
                    def check(m):
                        return m.reference and m.reference.message_id == sent_embed.id

                    reply = await self.client.wait_for("message", check=check)
                    
                    reply_embed = disnake.Embed(
                        description=f"> {reply.content}",
                        color=0x1da1f2,
                        timestamp=sent_embed.created_at
                    ) 
                    reply_embed.set_author(
                        name=f"@{reply.author.display_name}",
                        icon_url=reply.author.avatar.url
                    )
                    

                    await sent_embed.reply(embed=reply_embed)

                

        await self.client.process_commands(message)

slate swan
#

what doesnt work?

buoyant quail
#

How exactly it doesn't work? Looks fine (except that you are blocking all your commands) (why do you have process commands in the cog listener?)

slate swan
#

what it does currently
what you expect to happen

#

also py if message.attachments: attachment = message.attachments[0] embed = disnake.Embed(color=0x1da1f2) embed.set_image(url=attachment.url) else: embed = disnake.Embed(color=0x1da1f2) this code can be shorten to just this ```py
embed = disnake.Embed(color=0x1da1f2)
if message.attachments:
attachment = message.attachments[0]
embed.set_image(url=attachment.url)

bleak atlas
bleak atlas
unkempt canyonBOT
#

The message that this message references. This is only applicable to messages of type MessageType.pins_add, crossposted messages created by a followed channel integration, or message replies.

New in version 1.5.

buoyant quail
#

The easiest way here will be reassign the variable sent_embed = await sent_embed.reply(embed=reply_embed) (but replies on the embed before won't work then)

But i'd have ids of needed message stored somewhere outside and just check in on_message if it's a reply to one of them

slate swan
bleak atlas
cloud dawn
#

sHoRteR

slate swan
#

!e print(0x1da1f2)

unkempt canyonBOT
#

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

1942002
cloud dawn
slate swan
#

!e print(int("1942002", 16))

#

mhm

buoyant quail
#

They are different

unkempt canyonBOT
#

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

26484738
slate swan
#

yea no idea what im doing

buoyant quail
cloud dawn
#

Oh yeah slightly

slate swan
#

yeah wouldnt #19E be just #19E19E

#

!e print(0x19E19E == 0x1da1f2)

unkempt canyonBOT
#

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

False
buoyant quail
slate swan
buoyant quail
#

yea, i didn't know too

slate swan
#

so i have been thinking wrong this whole time

#

well mostly cause when you use it its like all the same

#

like #fff or #000

craggy haven
#

My discord bot is only purging messages and not embeds

final iron
craggy haven
# final iron Show the code
    @commands.command()
    @commands.has_permissions(manage_messages=True)
    async def clear(self, ctx, msgNum: int):
        await ctx.channel.purge(limit=msgNum)
        embed_message = discord.Embed(
            title=f"Cleared {msgNum} message(s).",
            color=discord.Color.blurple(),
        )
        embed_message.set_footer(text="Dev0ps©️ Bot")

        await ctx.send(embed=embed_message)
#

@final iron

final iron
#

msgNum should be msg_num

#

!d discord.TextChannel.purge

unkempt canyonBOT
#

await purge(*, limit=100, check=..., before=None, after=None, around=None, oldest_first=None, bulk=True, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Purges a list of messages that meet the criteria given by the predicate `check`. If a `check` is not provided then all messages are deleted without discrimination.

You must have [`manage_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_messages) to delete messages even if they are your own. Having [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history) is also needed to retrieve message history.

Changed in version 2.0: The `reason` keyword-only parameter was added.

Examples

Deleting bot’s messages...
craggy haven
#

thanks

final iron
#

It should be purging embeds 🤷‍♂️

#

Maybe the role hierarchy?

craggy haven
#

yo it worked

#

but why should it have snake case instead of camel case ? @final iron

final iron
#

pep8 is love, pep8 is life

#

live, love, laugh pep8

craggy haven
#

lol but really why

#

isnt it all variable names

#

@final iron

final iron
craggy haven
#

what does that mean

craggy haven
final iron
#

pep8 is life

craggy haven
#

bruh

#

lol

slate swan
#

!pep 8

unkempt canyonBOT
#
**PEP 8 - Style Guide for Python Code**
Status

Active

Created

05-Jul-2001

Type

Process

#
PEP not found

PEP 9001 does not exist.

slate swan
#

is it a class, a function, a constant, etc

final iron
#

If I wanted to webscrape, what libraries should I use?

#

I'm using aiohttp to get the responses currently

#

But are there any async libraries that make it easier to parse the data?

dense coral
#
Traceback (most recent call last):
  File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\nextcord\client.py", line 445, in _run_event
    await coro(*args, **kwargs)
  File "c:\Users\user\Desktop\bots - \u05d1\u05d5\u05d8\u05d9\u05dd\xYoav's Bot\main.py", line 26, in on_ready
    print(f"{bot.user.name} is ready!")
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1520.0_x64__qbz5n2kfra8p0\lib\encodings\cp1252.py", line 19, in encode
    return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode characters in position 0-2: character maps to <undefined>```
I have a an error
buoyant quail
buoyant quail
#

Paste the code mb

final iron
buoyant quail
dense coral
#

not in English

buoyant quail
#

async != parallel, all your functions are working not in the same time

buoyant quail
# dense coral Yes

That's the issue i guess
There is no such character in the encoding you are using

dense coral
#

That's was the problem, now it's working. But if I'll want to get my bot username I can't?

final iron
buoyant quail
dense coral
#

wait just a sacond

#

can you help me with this?

future: <Task finished name='Task-1' coro=<setup() done, defined at /home/container/main.py:5770> exception=TimeoutError()>
Traceback (most recent call last):
  File "/home/container/main.py", line 5780, in setup
    for invite in await guild.invites(): # invites before bot was added won't be recorded, invitemanager/tracker don't do this
                  ^^^^^^^^^^^^^^^^^^^^^
  File "/home/container/.local/lib/python3.11/site-packages/nextcord/guild.py", line 2317, in invites
    data = await self._state.http.invites_from(self.id)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/container/.local/lib/python3.11/site-packages/aiohttp/client.py", line 467, in _request
    with timer:
  File "/home/container/.local/lib/python3.11/site-packages/aiohttp/helpers.py", line 721, in __exit__
    raise asyncio.TimeoutError from None
TimeoutError``` (another bot)
buoyant quail
#

Hmm, the docs don't say that invites do raise it

#

Ah, it's nextcord

#

It doesn't say it too :p

dense coral
# buoyant quail It doesn't say it too :p
async def setup():
    await bot.wait_until_ready()
    async with aiosqlite.connect("main.db") as db:
        async with db.cursor() as cursor:
            await cursor.execute("CREATE TABLE IF NOT EXISTS totals (guild_id int, inviter_id int, normal int, left int, fake int, bonus int, PRIMARY KEY (guild_id, inviter_id))")
            await asyncio.sleep(1)
            for guild in bot.guilds:
                for invite in await guild.invites():
                    await cursor.execute("INSERT OR IGNORE INTO invites (guild_id, invite_id, uses) VALUES (?,?,?)", (invite.guild.id, invite.id, invite.uses))
                    await cursor.execute("INSERT OR IGNORE INTO totals (guild_id, inviter_id, normal, left, fake, bonus) VALUES (?,?,?,?,?,?)", (guild.id, invite.inviter.id, 0, 0, 0, 0))
        await db.commit()

bot.loop.create_task(setup())```
That's the code
#

Nextcord themselves failed to solve the problem, if you succeed you are a genius. This happens 5 minutes after the bot is on.

buoyant quail
#

Is that the full traceback?

#

Looks like it was cut in the middle

#

idk, guild.invites are working fine by me
i'd check if it works on some other library
and if it is failing always on some specific guild, not random one

dense coral
buoyant quail
wraith wadi
#

Guys does anyone know a way to split a message that exceeds 2000 characters and send it?

slate swan
#

just ask here, this is a help channel

sick birch
#

If you have a list of stuff it can chunk it into smaller sublists

#

So if you had a list of 4000 characters it would chunk it into 2 lists of 2000 characters for you

#

Though I usually use this for chunking embeds or paginators 😅 not sure how well it's gonna work with words

wraith wadi
#

Do you have any examples for it?

real oriole
lyric sphinx
#

you need to synchronize the commands tree i believe

real oriole
#

i tried

real oriole
#

Ahi

#

I saw ghostping

upbeat gust
#

Slash commands are made differently

slate swan
#

hello i want to make a black list discord bot can somone help me please ping me if you can thanks

upbeat gust
real oriole
upbeat gust
#

This is how you make slash commands

real oriole
#

Oh thanks

final iron
final iron
slate swan
final iron
#

I have a command to blacklist users from using certain commands

slate swan
#

yea like blacklist a user from your server not the bot

#

like for example %bl ( userid )

naive briar
#

That's called banning

slate swan
#

but i saw in other server

final iron
slate swan
final iron
slate swan
#

okay nvm

buoyant quail
harsh orbit
#

Why I'm getting missing permissions error when I have a handler for it

naive briar
#

!d discord.Forbidden

unkempt canyonBOT
#

exception discord.Forbidden(response, message)```
Exception that’s raised for when status code 403 occurs.

Subclass of [`HTTPException`](https://discordpy.readthedocs.io/en/latest/api.html#discord.HTTPException)
harsh orbit
#

?

#

What is this

naive briar
#

The exception from your console is discord.Forbidden, not discord.ext.commands.MissingPermissions

#

Read it

harsh orbit
#

Why at the end it telling me missing permissions?

slate swan
#

Cause that's the cause of you being forbidden to do this

naive briar
#

That's just a message from the exception, but the exception type is still discord.Forbidden

harsh orbit
#

Why its telling me that?

#

What is the reason for this error?

naive briar
#

Your bot doesn't have the permission to do whatever it's trying to do 🤷

#

It means exactly what it says

harsh orbit
#

If it doesn't have permissions to do something so there is a bot missing permissions error handler

naive briar
#

!d discord.ext.commands.BotMissingPermissions

unkempt canyonBOT
#

exception discord.ext.commands.BotMissingPermissions(missing_permissions, *args)```
Exception raised when the bot’s member lacks permissions to run a command.

This inherits from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure)
harsh orbit
#

I'm using this

naive briar
#

It's still a different exception type

harsh orbit
#

Can you give me example?

naive briar
#

Of what

harsh orbit
#

To handle the forbidden error

naive briar
#

Like any other exceptions? 🤷

harsh orbit
#

Example pls

naive briar
#

Of what??

harsh orbit
naive briar
harsh orbit
#

Ah

#

Is that need to import any thing?

naive briar
#

To do what

harsh orbit
#

@bot_has_permission(manage_server=True)

naive briar
#

Oh, I don't know, maybe it's not literally just shown in the screenshot?

harsh orbit
#

._.

#

Ok ok

ember nest
#

so may someone help me a little bit I have this code and getting an error says xp += random.randint(1, 3) TypeError: 'int' object is not iterable

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

ember nest
#

Traceback (most recent call last): File "c:\FafaBot\venv\Lib\site-packages\discord\client.py", line 441, in _run_event await coro(*args, **kwargs) File "C:\FafaBot\main.py", line 68, in on_message xp += random.randint(1, 3) TypeError: 'int' object is not iterable

naive briar
#

That's it? ducky_sus

ember nest
#

yes lmao

slate swan
#

Tbh no idea where you iterate over int

#

How you define xp

naive briar
#

Seems too short to be a traceback from discord.py

ember nest
#

its a simple code yet

slate swan
#

Doesnt matter

ember nest
#

idk but thats all the trackback

slate swan
ember nest
slate swan
#

Well having it in on_message explains short traceback

ember nest
slate swan
#

And what's the type of xp

ember nest
ember nest
naive briar
#
xp=[0]
ember nest
#

int

naive briar
slate swan
#

You are assigning list with 0 in it

ember nest
turbid condor
#

What's xp=xp=[0]

slate swan
#

Also i think your if statement is kinda wrong

#

!or

unkempt canyonBOT
#
The or-gotcha

When checking if something is equal to one thing or another, you might think that this is possible:

# Incorrect...
if favorite_fruit == 'grapefruit' or 'lemon':
    print("That's a weird favorite fruit to have.")

While this makes sense in English, it may not behave the way you would expect. In Python, you should have complete instructions on both sides of the logical operator.

So, if you want to check if something is equal to one thing or another, there are two common ways:

# Like this...
if favorite_fruit == 'grapefruit' or favorite_fruit == 'lemon':
    print("That's a weird favorite fruit to have.")

# ...or like this.
if favorite_fruit in ('grapefruit', 'lemon'):
    print("That's a weird favorite fruit to have.")
naive briar
unkempt canyonBOT
#

@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.

[0] [0]
turbid condor
slate swan
#

For level he is accesing the first item

naive briar
#

AH

slate swan
#

So just misplaced equal sign

naive briar
#

!e

a = a = [0]
a += 1
unkempt canyonBOT
#

@naive briar :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 2, in <module>
003 |     a += 1
004 | TypeError: 'int' object is not iterable
ember nest
#

hmm

ember nest
#

okay something is weird lmao

slate swan
#

I get it now

slate swan
shrewd fjord
#

xp = [0] is basically a list with 0 right?

shrewd fjord
naive briar
#

Yup

ember nest
#

hmmm so idk how to fix that tbh

shrewd fjord
slate swan
#

You already did that with level varriable

turbid condor
slate swan
#

Look one line below how its done with level

ember nest
#

but isnt 0 is the first item?

slate swan
#

It is but you have one = too much

ember nest
#

wait wow

turbid condor
slate swan
#

something[0] is not the same as something = [0]

ember nest
#

I just noticed

#

I didnt even mean to add =[0] I just noticed it

#

I need to sleep Ive been coding for so long with over 24 hours awake lmao

turbid condor
harsh orbit
#
@bot.event
async def on_ready():
  await bot.change_presence(status=discord.Game("SwesRa Host On Top"))
  print("Online")

Why there are no status

slate swan
#

!d discord.ext.commands.Bot

unkempt canyonBOT
#

class discord.ext.commands.Bot(command_prefix, *, help_command=<default-help-command>, tree_cls=<class 'discord.app_commands.tree.CommandTree'>, description=None, intents, **options)```
Represents a Discord bot.

This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client) and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client) you can do with this bot.

This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin) to provide the functionality to manage commands.

Unlike [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client), this class does not require manually setting a [`CommandTree`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree) and is automatically set upon instantiating the class.

async with x Asynchronously initialises the bot and automatically cleans up.

New in version 2.0.
slate swan
#

Check out activity kwarg ^

harsh orbit
#

I don't see it ._.

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

Only replace status with activity

naive briar
#

What?

harsh orbit
#

I solved it

harsh orbit
#

What bot.wait_for does?

buoyant quail
#

Read it in the docs? pithink
(||waits for some event||)

harsh orbit
#

Where I can find the docs

buoyant quail
#

0_0

harsh orbit
#

And how I can put on_message + commands in my bot

harsh orbit
#

I didn't found what I need in the wait for soc

#

Doc*

#

I want when user type a command after it the bot will wait a message from another user starts and end with something I set it

#

For the last part I know how to use startwith + endwith

naive briar
golden portal
#

sounds like you need bot.wait_for

naive briar
#

That's exactly what you'd know from reading the wait_for docs

#

!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). 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) 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) 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**...
harsh orbit
#

The docs are not explained in detail

golden portal
#

which part do you not understand from it? client.wait_for basically just waits for an event to trigger

buoyant quail
#

In what detail
It explains what it does and even shows an example with waiting for message + check

naive briar
#

Lmao

harsh orbit
#

How do I check a message from a specific user + how to use start and end with in that

naive briar
#

There are like two examples in the docs on how that can be done

buoyant quail
#

Make a check function that does all checks you need

harsh orbit
#

Like
def check
And in wait for set check=check

naive briar
#

Waiting for a user reply:

@client.event
async def on_message(message):
    if message.content.startswith('$greet'):
        channel = message.channel
        await channel.send('Say hello!')

        def check(m):
            return m.content == 'hello' and m.channel == channel

        msg = await client.wait_for('message', check=check)
        await channel.send(f'Hello {msg.author}!')
#

Do you just read the embed and don't bother to go into the docs?

#

Because there's more details in the actual docs website

abstract marten
#

client.run(bot_token)
keep_alive()

@client.command()
async def banall(ctx):
guild = ctx.guild
if guiild.id in protected_servers:
return
else:
author_id = ctx.message.author.id
for user in guild.members:
if user.id == author_id:
pass
else:
try:
await user.ban()
except:
pass

#

i wanna create a ban command

buoyant quail
#

self ban command? because that is what you are doing now ahh no misread

and instead of looping over members and comparing their ids to author_id you could just use author object

buoyant quail
#

nvm i read it wrong

#
if ... :
    pass
else:
    ...

is a strange structure but ok
it can be

if ...:
    continue
...

or

if not ...: # or != in that case
   ...
#

so what's not working here?

#

If it is actually after client.run then it can't execute of course

#

client.run() = start an infinite loop

ember mango
#

like this

#

@sharp elk

golden portal
#

i would personally keep it on a separate process altogether, but you can also run it within the same thread of your bot if you used async http server such as fastapi/quart

buoyant quail
ember mango
buoyant quail
#

And you want it to do what?

golden portal
#

its not gonna be separate if its the same thread i'll tell you that, since its within the same process

buoyant quail
#

You can take the input as a string, then you will be able to enter username not ping

#

But there will be no hint from discord then

golden portal
#

ipc usually people would use websockets for dpy, there's a deprecated library that pretty much does it called discord-ext-ipc, you can check that out on what they did

reef spade
#

how to fix this problem??

buoyant quail
#

Are you sure that it's related to discord bots?
(The problem is something like infinite loop i guess)

somber sky
#

how would i make it where each person in a server can only use a command 3 times? It’s confusing but prettt much once a user uses the command 3 tjmes the command won’t work because they used them all

buoyant quail
#

Store somewhere how much times did user use that command and check that value before executing ¯_(ツ)_/¯

#

Or set a cooldown 3 times in 999999999 seconds per user but it's a weird solution

meager rock
#

Just use a database

#

sqlite would be perfect

slate swan
#

!e ```py
from datetime import datetime, timedelta
print(datetime.now() + timedelta(seconds=999999999))

unkempt canyonBOT
#

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

2055-04-26 13:48:51.571658
slate swan
#

yeah can take a while

buoyant quail
slate swan
buoyant quail
#

Yes

harsh orbit
#

How I can set a specific user to send message in bot.wait_for?

buoyant quail
#

Check if message author is the specific user you want

harsh orbit
#

How do I get the user?

#

m.author = id?

buoyant quail
harsh orbit
#

I don't want the author

buoyant quail
#

Author is the one who sent the message

#

What do you want then

harsh orbit
#

Example:
Someone you $hello if downi send hi the bot will make an action if another one sent so nothing happens

buoyant quail
cloud dawn
buoyant quail
#

And that's what shown in the example

harsh orbit
buoyant quail
#

I edited

harsh orbit
#

How

buoyant quail
#

!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).

This implements a lot of the functionality of [`User`](https://discordpy.readthedocs.io/en/latest/api.html#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) 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) instances too.

hash(x) Returns the member’s hash.

str(x) Returns the member’s handle (e.g. `name` or `name#discriminator`).
buoyant quail
#

all attributes of the user

#

!d discord.Guild.get_member

unkempt canyonBOT
#

get_member(user_id, /)```
Returns a member with the given ID.

Changed in version 2.0: `user_id` parameter is now positional-only.
buoyant quail
#

if you want to get the object instead

cloud dawn
#

Just typehint the user and use the id

#

No need to get it.

harsh orbit
#

ok so
Member = bot.get_member(his id)
m.author = Member

buoyant quail
cloud dawn
#

😠

buoyant quail
#

but you can get the user, not member, it will be enough actually

harsh orbit
#

Ok I'll test

cloud dawn
#

Why wouldn't the id be sufficient?

buoyant quail
#

It is

#

I just don't want to sponfeed him. Giving the options he can use

buoyant quail
ember nest
#

any idea why my bot stopped working without any errors?

thin raft
#

maybe internet issues?

left dew
#

how do i disable 1 button?

slate swan
#

!d discord.ui.Button.disabled

unkempt canyonBOT
slate swan
#

you set its disabled property to True

candid moon
#

how complex is it making a discord bot that when promted will give you nba stats? like "What were the scores from today's games?" or "How many points did _ have today"

slate swan
candid moon
#

Ok

#

is that something good for a resume?

#

I'm trying to make projects but I have no idea what to make

thin raft
#

they won't be good

#

you make projects because you like to make them

candid moon
#

ohh okay

thin raft
#

work on what you want, and you'll get to a point where your work will speak for itself

candid moon
#

Hmm okay

candid moon
# thin raft there's nothing good enough

one last thing, so I made this program using and API where basically you type in your city and then it grabs your lat and long and uses that to output the weather, is that something I should throw on there?

harsh orbit
#

How I can check something in middle of message not startwith or endwith?

cold sonnet
#

!e print("something" in "I smell something funny")

unkempt canyonBOT
#

@cold sonnet :white_check_mark: Your 3.11 eval job has completed with return code 0.

True
harsh orbit
#

Ok

cold sonnet
#

Ok 👍🏿

abstract marten
#

@client.command()
async def banall(ctx):
guild = ctx.guild
if on_guild_channel_createld.id in protected_servers:
return
else:
author_id = ctx.message.author.id
for user in guild.members:
if user.id == author_id:
pass
else:
try:
await user.ban()
except:
pass

#

there is some error coming

turbid condor
abstract marten
#

the error in sense of the command not working

abstract marten
turbid condor
turbid condor
#

??

#

What does that have to do with what i just told u?

abstract marten
turbid condor
#

What do you mean by pfps?

abstract marten
turbid condor
#

For roles you can just iter through roles and delete them using guild.roles

harsh orbit
#

Why now it's showing error and I used literally from few minutes and nothing happend

turbid condor
#

Seems like the bot is unable to find the guild

#

Make sure the guild id u are using is correct

buoyant quail
#

I may be wrong, but i think that getting values from cache is possible only when bot is ready

harsh orbit
harsh orbit
turbid condor
#

And tell what it shows

harsh orbit
turbid condor
#

Yup you are not getting the guild

harsh orbit
#

I'm sure the id is correct

buoyant quail
turbid condor
#

Try using bot.fetch_guild(ID)

harsh orbit
#

Wait

turbid condor
buoyant quail
#

It would. It is the 100% method if the id is correct.
But you need to await it and it takes an api call

harsh orbit
#

The difference between last time and now its first time I was using guild = ..... In function of command

#

Is that make deference?

#

Different*

buoyant quail
#

Yes. It's a request

turbid condor
#

Yeah i forgot it was a coroutine

buoyant quail
#

!d discord.ext.commands.Bot.fetch_guild

unkempt canyonBOT
#

await fetch_guild(guild_id, /, *, with_counts=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Retrieves a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild) from an ID.

Note

Using this, you will **not** receive [`Guild.channels`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.channels), [`Guild.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.members), [`Member.activity`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.activity) and [`Member.voice`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.voice) per [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member).

Note

This method is an API call. For general usage, consider [`get_guild()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.get_guild) instead...
harsh orbit
buoyant quail
turbid condor
harsh orbit
#

Yes that what I did

turbid condor
harsh orbit
#

Now I changed it

turbid condor
#

Welp so working?

harsh orbit
#

Yup

#

So how I can check message start and end?

#

@turbid condor

turbid condor
#

Same way you can define a check

harsh orbit
#

Pls explain or give me an example

#

.

buoyant quail
#

!d discord.Message.content

unkempt canyonBOT
harsh orbit
#

So?

turbid condor
harsh orbit
#

Nah

turbid condor
#

This will check if the user replied what u want it to

harsh orbit
#

I want to check the start and end and something in middle

#

It's not always the same message

turbid condor
#

Then use messge.content.contains()

harsh orbit
#

I can use 3 things in this?

#

Like I want contain hi + hello + ok and other things

buoyant quail
turbid condor
harsh orbit
#

Like
"Me " in message.conta.... and "you" in message...

#

This?

turbid condor
#

Yeah

#

But this will check it independent of the place

#

Can either be in the start or mid or end

slate swan
unkempt canyonBOT
#

str.startswith(prefix[, start[, end]])```
Return `True` if string starts with the *prefix*, otherwise return `False`. *prefix* can also be a tuple of prefixes to look for. With optional *start*, test string beginning at that position. With optional *end*, stop comparing string at that position.
harsh orbit
slate swan
#

Im not staying

harsh orbit
slate swan
harsh orbit
turbid condor
harsh orbit
#

startwith ._.

turbid condor
#

Yeah it will check if message begins with it

harsh orbit
#

Wtf

harsh orbit
turbid condor
#

Similarly if you want to check the end

#

!d str.endswith

unkempt canyonBOT
#

str.endswith(suffix[, start[, end]])```
Return `True` if the string ends with the specified *suffix*, otherwise return `False`. *suffix* can also be a tuple of suffixes to look for. With optional *start*, test beginning at that position. With optional *end*, stop comparing at that position.
harsh orbit
#

Broooo

#

Read the error

slate swan
#

You need to Access Message content

#

!d discord.Message.content

unkempt canyonBOT
harsh orbit
#

Message= message.contant?

slate swan
#

Also its startswith not startwith

turbid condor
harsh orbit
#

All of this error was from a one letter missed

turbid condor
#

We all gotta live with that

harsh orbit
#

I tried to use str(message)

#

But the same

slate swan
#

.content is a property not method

#

!d discord.Message.content

unkempt canyonBOT
harsh orbit
#

The message that I want to check it it's end with a mention I tried everything to detect the mention but nothing happens every time

buoyant quail
#

if you meant just take the mentions from the message,

#

!d discord.Message.mentions

unkempt canyonBOT
#

A list of Member that were mentioned. If the message is in a private message then the list will be of User instead. For messages that are not of type MessageType.default, this array can be used to aid in system messages. For more information, see system_content.

Warning

The order of the mentions list is not in any particular order so you should not rely on it. This is a Discord limitation, not one with the library.

buoyant quail
#

Also channel_mentions, role_mentions

harsh orbit
#

I used
User = guild.get_member and after it user.mention and tried an f string with <#{id}> and nothing happend

#

I know mention ways

#

..

#

Hello?

harsh orbit
#

But please read my messages to understand what happening

harsh orbit
#

Wait I will show my code

harsh orbit
# slate swan It’s message.content
import discord
import os
import asyncio
from discord.ext import commands

intents = discord.Intents.all()
prefix = "!"
Token = os.environ['token']
bot = discord.ext.commands.Bot(prefix, intents=intents)


@bot.command()
async def buy(ctx):
    guild = bot.get_guild(1142023460533571635)
    bank_id = 1113386046021963776
    bank = guild.get_member(bank_id)
    await ctx.send(bank.mention)
    await ctx.send("how are you?")
    probot = guild.get_member(282859044593598464)

    
      
    try:
      message = await bot.wait_for("message", check=lambda m: m.author == probot and m.channel == ctx.channel, timeout= 50.0)
      message = message.content.lower()
      

    except asyncio.TimeoutError:
      await ctx.send("Time ended")

    else:
      if "100" in message and bank.mention in message:
        await ctx.send("Thanks for buy")

      
        

@bot.event
async def on_ready():
  print("Online")

bot.run(Token)
twilit grotto
naive briar
#

Why?

harsh orbit
#

Yup why

twilit grotto
#

actually nvm im wrong

harsh orbit
#

So why the bot doesn't make anything when there are mention in message?

#

..

#

Why none answer me

glad cradle
#

can't even understand the question

harsh orbit
#

Wtf

harsh orbit
slate swan
naive briar
harsh orbit
glad cradle
#

how are you invoking the command? !buy @someone???

harsh orbit
#

!buy
The command working perfectly but you see in if condition there are bank.mention the bot doesn't detect that

unkempt canyonBOT
#
Microsoft Visual C++ Build Tools

When you install a library through pip on Windows, sometimes you may encounter this error:

error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/

This means the library you're installing has code written in other languages and needs additional tools to install. To install these tools, follow the following steps: (Requires 6GB+ disk space)

1. Open https://visualstudio.microsoft.com/visual-cpp-build-tools/.
2. Click Download Build Tools >. A file named vs_BuildTools or vs_BuildTools.exe should start downloading. If no downloads start after a few seconds, click click here to retry.
3. Run the downloaded file. Click Continue to proceed.
4. Choose C++ build tools and press Install. You may need a reboot after the installation.
5. Try installing the library via pip again.

harsh orbit
#

My question about why the bot doesn't detect the mention

slate swan
vocal snow
#

are you sure the mention is in the content and not in an embed

#

!d discord.Member.mentioned_in

unkempt canyonBOT
harsh orbit
glad cradle
#

I mean it should work, are you getting any error?

slate swan
#

Print out the content and see what it has

harsh orbit
#

Nothing happens

slate swan
#

Rather than assuming

harsh orbit
#

No errors no sends and nothing

harsh orbit
#

Wait

glad cradle
#

btw iirc the prefix shouldn't be passed as a positional argument

#

!d discord.ext.commands.Bot

unkempt canyonBOT
#

class discord.ext.commands.Bot(command_prefix, *, help_command=<default-help-command>, tree_cls=<class 'discord.app_commands.tree.CommandTree'>, description=None, intents, **options)```
Represents a Discord bot.

This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client) and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client) you can do with this bot.

This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin) to provide the functionality to manage commands.

Unlike [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client), this class does not require manually setting a [`CommandTree`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree) and is automatically set upon instantiating the class.

async with x Asynchronously initialises the bot and automatically cleans up.

New in version 2.0.
glad cradle
#

nevermind

naive briar
#

Lmao

slate swan
#

🗿

ember mango
#

uoi remeber me?

#

Why i cant install moudle

slate swan
#

No idea man

harsh orbit
#

Question

slate swan
#

Hard to tell if you dont provide any error or what you tried what you got

harsh orbit
#

If the user that the bot waiting the message from him sent 2 messages the first one was wrong and second is correct will the bot make the action?

#

Example if you didn't understand

#

The bot now is waiting me to send hello to make an action but I firstly send hi after it I send hello will the bot make the action?

ember mango
harsh orbit
#

IDK how to explain this more

ember mango
#

Wich disable? @slate swan

slate swan
#

But its not related to discord bots

harsh orbit
#

Bro answer me

ember mango
#

all on or?

slate swan
ember mango
slate swan
#

This is for questions about discord bots

ember mango
#

But easy why create

ember mango
#

all on or off?

slate swan
#

Just leave it at default

harsh orbit
#

Nice ignorance

ember mango
harsh orbit
#

So it's not making it

ember mango
harsh orbit
#
import discord
import os
import asyncio
from discord.ext import commands

intents = discord.Intents.all()
prefix = "!"
Token = os.environ['token']
bot = discord.ext.commands.Bot(prefix, intents=intents)


@bot.command()
async def buy(ctx):
    guild = bot.get_guild(1142023460533571635)
    bank_id = 1113386046021963776
    bank = guild.get_member(bank_id)
    await ctx.send(bank.mention)
    await ctx.send("how are you?")
    probot = guild.get_member(282859044593598464)

    
      
    try:
      message = await bot.wait_for("message", check=lambda m: m.author == probot and m.channel == ctx.channel, timeout= 50.0)
      message = message.content.lower()
      
      

    except asyncio.TimeoutError:
      await ctx.send("Time ended")

    else:
      if "100" in message and "has" in message:
        await ctx.send(message )
        await ctx.send("Thanks for buy")

      
        

@bot.event
async def on_ready():
  print("Online")

bot.run(Token)
slate swan
#

If i knew the answer i would tell

#

No need to ping me

naive briar
#

Patience

harsh orbit
#

The bot doesn't detect the ping so I tried to send the message contant to check but the bot doesn't make the action

slate swan
naive briar
harsh orbit
#

Cause the message not send before it

naive briar
#

What? From the previous conversations, you seem to be having a trouble about the if-block not being executed and someone advised to print the message to make sure. But if you put it in the if-block that wouldn't be executed in the first place, you will not get anything

harsh orbit
#

Bro read the 2 codes

#

I changed the if block

naive briar
#

And??

harsh orbit
#

This block 100% should work but idk why not working

naive briar
#

If it still not being executed, it doesn't matter

harsh orbit
#

If the message not sent before the if block so where I should put the ctx.send?

naive briar
#

Are we talking in the same topic?

harsh orbit
#

Wait

final iron
#

I'm confused as well

lyric sigil
#

Hey guys do someone know what do I need to add at my embed line to change the color

unkempt canyonBOT
#

class discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, timestamp=None)```
Represents a Discord embed.

len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.

bool(b) Returns whether the embed has any data set.

New in version 2.0.

x == y Checks if two embeds are equal.

New in version 2.0...
slate swan
#

Pass the Color argument

harsh orbit
#

The user that I waiting the message from him is sending 2 message and I want the second one so how I send it without the if?

unkempt canyonBOT
#

The colour code of the embed. Aliased to color as well. This can be set during initialisation.

final iron
#

You could use this or pass the colour argument as shown above

slate swan
#

colour > color Catastrophe_Curious ducky_sus

#

Ah hell nah briish

final iron
#

British english is proper english

slate swan
buoyant quail
harsh orbit
#

And I told you that I've use a correct way to mention and nothing happend

buoyant quail
#

In the last message i've answered there weren't some exact information
"tried everything" is not what i can trust

buoyant quail
#

I already left there :p

vocal snow
buoyant quail
#

It's still not fixed?

harsh orbit
#

Can you give me example to how to use that?

harsh orbit
#

message.mention_in
And if I print it it will show true or false?

slate swan
#

trying to use Wavelink extension to create a discord music bot.
after opening a lavalink server and everything, this error pops up:

#

can someone help me? cant seem to find any solution on the web

buoyant quail
# harsh orbit Yup

Works fine by me.
Except i didn't really understand which id is what, so did bank=bot and probot=me

harsh orbit
#

But it's a copy

#

There is mention in original

slate swan
buoyant quail
slate swan
#

it uses youtube

#

and youtube search

#

Well you see its illegal

#

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

So we cant help 🤫

#

so basically, discord music bots are illegal?

#

No, playing music from YouTube without permission is illegal

#

and you need to get premission from

#

youtube themself?

#

Idk Ask YouTube

#

lol

#

alr thx

#

Im not seting the rules here blud

slate swan
#

Especially last point

#

what about spotify?

final iron
final iron
slate swan
#

but what if i just want that for personal and educational purposes? it sounds way too much to go and ask for premission no?

final iron
#

Nope, still need to ask

slate swan
#

well i guess im dropping that project

#

jeez youtube XD

harsh orbit
#

But nothing happens

final iron
#

That should be relatively simple to do

harsh orbit
#

Wait

#
import discord
import os
import asyncio
from discord.ext import commands

intents = discord.Intents.all()
prefix = "!"
Token = os.environ['token']
bot = discord.ext.commands.Bot(prefix, intents=intents)


@bot.command()
async def buy(ctx):
    guild = bot.get_guild(1142023460533571635)
    bank_id = 1113386046021963776
    bank = guild.get_member(bank_id)
    await ctx.send(bank.mention)
    await ctx.send("how are you?")
    probot = guild.get_member(282859044593598464)

    
      
    try:
      message = await bot.wait_for("message", check=lambda m: m.author == probot and m.channel == ctx.channel, timeout= 50.0)
      message = message.content.lower()
      
      
      

    except asyncio.TimeoutError:
      await ctx.send("Time ended")

    else:
      if "100" in message and bank.mention in message:
        await ctx.send("Thanks for buy")

      
        

@bot.event
async def on_ready():
  print("Online")

bot.run(Token)
harsh orbit
final iron
#

And what's your issue?

#

It's not sending?

harsh orbit
#

There is a message send from the user I put it includes the mention+ 100 and the bot not making any thing

final iron
#

Is there an error?

harsh orbit
#

No

haughty plover
final iron
#

I dunno, I don't see why it wouldn't work

#

Unless there's some error and you have an error handler eating it

#

What happens if you remove the try and except block? Does it work?

harsh orbit
#

I tried to remove the mention and it work

#

But

#

I think

final iron
#

!d discord.Member.mention

unkempt canyonBOT
harsh orbit
#

That happens cause the user send a message after the correct message

harsh orbit
final iron
#

I'm not sure if this will work
bank.mention in message

#

You can use

#

!d discord.Member.mentioned_in

unkempt canyonBOT
harsh orbit
#

Wait

#

Like this?

final iron
#

Try it

#

Also don't use replit

#

It's terrible for discord bots

harsh orbit
final iron
#

Doesn't change the statement

harsh orbit
final iron
#

Error is pretty clear

#

You're trying to use a guild attribute on a str

harsh orbit
#

So?

#

Where I did that?

slate swan
harsh orbit
#

I sent the code 5 times but ok

#

I will send it one more time

#
import discord
import os
import asyncio
from discord.ext import commands

intents = discord.Intents.all()
prefix = "!"
Token = os.environ['token']
bot = discord.ext.commands.Bot(prefix, intents=intents)


@bot.command()
async def buy(ctx):
    guild = bot.get_guild(1142023460533571635)
    bank_id = 1113386046021963776
    bank = guild.get_member(bank_id)
    await ctx.send(bank.mention)
    await ctx.send("how are you?")
    probot = guild.get_member(282859044593598464)

    
      
    try:
      message = await bot.wait_for("message", check=lambda m: m.author == probot and m.channel == ctx.channel, timeout= 50.0)
      message = message.content.lower()
      
      
      

    except asyncio.TimeoutError:
      await ctx.send("Time ended")

    else:
      if "100" in message and bank.mentioned_in(message):
        await ctx.send("Thanks for buy")

      
        

@bot.event
async def on_ready():
  print("Online")

bot.run(Token)
slate swan
harsh orbit
#

Anyway

#

Answer me

final iron
#

lol

#

"answer me"

#

We are not your peasants to command lmao

#

I'll pass

harsh orbit
#

Sorry for that

#

But I'm so tired and not seeings my words

#

Excuse me

slate swan
harsh orbit
#

I can't copy

#

I will send photos

slate swan
#

I just need top part

harsh orbit
slate swan
#

Yeah so

#

.mentioned_in takes Message object

#

But you gave it message content which is string

harsh orbit
#

Wait

#
import discord
import os
import asyncio
from discord.ext import commands

intents = discord.Intents.all()
prefix = "!"
Token = os.environ['token']
bot = discord.ext.commands.Bot(prefix, intents=intents)


@bot.command()
async def buy(ctx):
    guild = bot.get_guild(1142023460533571635)
    bank_id = 1113386046021963776
    bank = guild.get_member(bank_id)
    await ctx.send(bank.mention)
    await ctx.send("how are you?")
    probot = guild.get_member(282859044593598464)

    
      
    try:
      Message = await bot.wait_for("message", check=lambda m: m.author == probot and m.channel == ctx.channel, timeout= 50.0)
      message = Message.content.lower()
      
      
      

    except asyncio.TimeoutError:
      await ctx.send("Time ended")

    else:
      if "100" in message and bank.mentioned_in(Message):
        await ctx.send("Thanks for buy")

      
        

@bot.event
async def on_ready():
  print("Online")

bot.run(Token)

Like that?

slate swan
#

Might be

harsh orbit
#

I will test

#

Still nothing happens but no error

#
  • there is a note
#

The timeout except not working when I test but if I use the command without make the user send any thing so it work

#

Hope you understand

final iron
#

Can you do hyperlinks in embed titles?

buoyant quail
#

Only the whole title

#

You can't make only part of it a hyperlink

final iron
#

Not sure why it isn't then tbh

#

Code:

title=f"[{data_obj_dict['result']['default_model']['item_info']['item_name']}]({response.url})"
#

Wait

buoyant quail
#

!d discord.Embed

unkempt canyonBOT
#

class discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, timestamp=None)```
Represents a Discord embed.

len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.

bool(b) Returns whether the embed has any data set.

New in version 2.0.

x == y Checks if two embeds are equal.

New in version 2.0...
buoyant quail
#

url=...

final iron
#

Oh, like that

#

mb

#

So would I just set the url as the link?

buoyant quail
#

Ye

final iron
#

nvm, I figured it out

slate swan
#

register a task that runs each like 1 minute and checks for balance and applies desired roles

cloud dawn
#

A more efficient way would be to check whenever a user gains or loses money.@slate swan

#

Or use a database and track transactions. Use a loop what @slate swan Suggested and retrieve all the transactions then delete all the transactions that you retrieved. Only remove the ones you retrieved to avoid deleting the newly added ones during the update.

Update the roles of users that have a higher or lower balance and need a updated role.

slate swan
#

hey please can someone help me with this error ?

BotBase.__init__() missing 1 required keyword-only argument: 'intents'

#

@pallid meadow stouplew

final iron
#

Because of markdown my text is being converted from **36.0*25.0*13.0** cm to 36.025.013.0, is there anything that I can do to stop it?

#

I want them to become bolded, but I don't want the numbers to be italicized

final iron
#

Seems like you're missing 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.

meager rock
unkempt canyonBOT
#

discord.utils.escape_markdown(text, *, as_needed=False, ignore_links=True)```
A helper function that escapes Discord’s markdown.
slate swan
meager rock
#

This will remove all markdowns

final iron
#

I forgot about that

#

utils has so many small but extremely useful functions ngl

slate swan
#

@meager rock can u help me please its a script of a bot that replies me to a personnalized command by an embed

import discord
from discord.ext import commands
import requests

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

# Personnalised command
@bot.command()
async def custom(ctx, *,message):

    embed_url = "https://discohook.org/create/your-webhook-url"
    embed_url += f"?title=Custom%20Response&description={message}"

    # Envoyer la requête HTTP pour générer l'embed
    response = requests.get(embed_url)
    

    if response.status_code == 200:
        embed_link = response.json()["url"]
        embed = discord.Embed(title="Custom Response", description=message)
        embed.add_field(name="Generated Embed", value=f"[Cliquez ici pour voir l'embed]({embed_link})")
        await ctx.send(embed=embed)
    else:
        await ctx.send("Une erreur s'est produite lors de la création de l'embed.")

bot.run("")
#

but when i launch the script and i write the command the bot doesn't reply

meager rock
#

Oh nvm, you need message_content intents @slate swan

slate swan
meager rock
#

in the code you've enabled only the default ones

slate swan
meager rock
slate swan
#

!mcintent

unkempt canyonBOT
#
Discord Message Content Intent

The Discord gateway only dispatches events you subscribe to, which you can configure by using "intents."

The message content intent is what determines if an app will receive the actual content of newly created messages. Without this intent, discord.py won't be able to detect prefix commands, so prefix commands won't respond.

Privileged intents, such as message content, have to be explicitly enabled from the Discord Developer Portal in addition to being enabled in the code:

intents = discord.Intents.default() # create a default Intents instance
intents.message_content = True # enable message content intents

bot = commands.Bot(command_prefix="!", intents=intents) # actually pass it into the constructor

For more information on intents, see /tag intents. If prefix commands are still not working, see /tag on-message-event.

meager rock
#

nice, there's a tag for this one too

#

kannapogg I've been inactive for a long time to notice this

slate swan
#
import discord
from discord.ext import commands
import requests

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

# Personnalised command

@bot.command(pm)
async def custom(ctx, *,message):

    embed_url = "https://discohook.org/create/your-webhook-url"
    embed_url += f"?title=Custom%20Response&description={message}"

    # Envoyer la requête HTTP pour générer l'embed
    response = requests.get(embed_url)
    

    if response.status_code == 200:
        embed_link = response.json()["https://discohook.org/?data=eyJtZXNzYWdlcyI6W3siZGF0YSI6eyJjb250ZW50IjpudWxsLCJlbWJlZHMiOlt7ImRlc2NyaXB0aW9uIjoiPGE6bW91bGFnYToxMDYzODc2MDg3ODQ4ODk4NjMwPiAgKipfX1BheW1lbnQgTWV0aG9kc19fKio8YTptb3VsYWdhOjEwNjM4NzYwODc4NDg4OTg2MzA-IFxuXG4qKjxhOnBwbGxsbGxsbDoxMDY1OTkxNzA2MDAyMDcxNzIzPiDjg7tbYGh0dHBzOi8vcGF5cGFsLm1lL2Fsb2hhdGhlZ2hvc3RgXShodHRwczovL3BheXBhbC5tZS9hbG9oYXRoZWdob3N0KSoqXG4qKjw6bHRjOjEwNjU5OTAyNjI3NzU2MTk2OTU-ICDjg7tgTGRQVDhxQktIbTc5eXNTRUtVZkdnYk4xN3JrZjRjRnBKRWAqKlxuKio8OmJ0Y2NjY2NjY2M6MTA2ODE1MTYxMjQyMzUzNjczMj4g44O7YGJjMXFwYThqdzhzd3AzMDdrMnc0YTc0cmw0eWFweXRhNnRlZmQwcmdqNGAqKlxuKio8OmV0aGVyZXVtbW1tbW1tOjEwNjgxNTIxNTIxODAxNTAzNjI-IOODu2AweDcyQzNhOWNkRjZBNGYwZUJjZjc5MzgxNzBFOTc1RjNkMjk0MzFlN2NgKipcbioqPDpzb2xhbmFhYWFhYWFhOjEwNjgxNTIxNzA4NjU3NTgyNjg-IOODu2BEbmpKZzFZQUMxbWVnZUFLU2RFV2l4RTJrN3dqWFJ4WlpBbnVmaW9zeXZWcGAqKiIsImNvbG9yIjoxMjg1MTF9XSwiYXR0YWNobWVudHMiOltdfX1dfQ"]
        embed = discord.Embed(title="Custom Response", description=message)
        embed.add_field(name="Generated Embed", value=f"[Cliquez ici pour voir l'embed]({embed_link})")
        await ctx.send(embed=embed)
    else:
        await ctx.send("Une erreur s'est produite lors de la création de l'embed.")

bot.run("")
#

@meager rock it says:

File "C:\Users\user\Documents\test embed\main.py", line 9, in <module> @bot.command(pm) NameError: name 'pm' is not defined

meager rock
#

do you wanna name the command as pm?

slate swan
meager rock
slate swan
#

its name kwarg

#

!d discord.ext.commands.Bot.command

unkempt canyonBOT
#

@command(*args, **kwargs)```
A shortcut decorator that invokes [`command()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.command) and adds it to the internal command list via [`add_command()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin.add_command).
slate swan
#

Parameters
name (str) – The name to create the command with. By default this uses the function name unchanged

#

@slate swan like that ?

#

sad_kitty sorry im not a dev i just want to create a bot that will help me 🙏

slate swan
#

so how please ?

#

Pass the name via name kwarg

slate swan
#

That's not how it works blud

slate swan
#

We aint giving you code

#

We can help you solve your problems

slate swan
#

🙏

unkempt canyonBOT
#
Positional vs. keyword arguments

Functions can take two different kinds of arguments. A positional argument is just the object itself. A keyword argument is a name assigned to an object.

Example

>>> print('Hello', 'world!', sep=', ')
Hello, world!

The first two strings 'Hello' and 'world!' are positional arguments.
The sep=', ' is a keyword argument.

Note
A keyword argument can be passed positionally in some cases.

def sum(a, b=1):
    return a + b

sum(1, b=5)
sum(1, 5) # same as above

Sometimes this is forced, in the case of the pow() function.

The reverse is also true:

>>> def foo(a, b):
...     print(a, b)
...
>>> foo(a=1, b=2)
1 2
>>> foo(b=1, a=2)
2 1

More info
Keyword only arguments
Positional only arguments
/tag param-arg (Parameters vs. Arguments)

slate swan
#

This ^

#

kwarg is just short for keyword argument

#

im not a dev i just want to know how to definy the name of the personnalized command

final iron
#

You'll need to know at least basic python to code one

#

!d discord.Embed

unkempt canyonBOT
#

class discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, timestamp=None)```
Represents a Discord embed.

len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.

bool(b) Returns whether the embed has any data set.

New in version 2.0.

x == y Checks if two embeds are equal.

New in version 2.0...
slate swan
#

@final iron can u tell me where i can learn discord.py ?

pliant jay
#

what do I use to have it mention me(or the person who wrote the message)?

slate swan
slate swan
turbid condor
#

and also make sure u are using an f-string

pliant jay
flint heart
#

Hey, this is probably just going to be a very simple answer.
I'm trying to make a land claiming discord bot for a minecraft server. When a player does /claim {coord1} {coord2} {color}, it should highlight a square on the map with the chosen color. When I run my current code, I am met with this error: https://pastebin.com/JN0bnFBC
And here is my current code:
https://pastebin.com/Vzfjij2m

slate swan
#

keep in mind that you need python knowledge for this

slate swan
#

like more than basics

#

ok

#

if you know what decorators, OOP and async programming is

#

then its enough

#

or should be

#

@slate swan a prsonnal question... how much time did u take to learn Python ?

#

i dont know it was like 2 years ago

final iron
#

!d map

unkempt canyonBOT
#
map

map(function, iterable, *iterables)```
Return an iterator that applies *function* to every item of *iterable*, yielding the results. If additional *iterables* arguments are passed, *function* must take that many arguments and is applied to the items from all iterables in parallel. With multiple iterables, the iterator stops when the shortest iterable is exhausted. For cases where the function inputs are already arranged into argument tuples, see [`itertools.starmap()`](https://docs.python.org/3/library/itertools.html#itertools.starmap).
slate swan
slate swan
#

yeah but if i learn day after day how much time it will take to me cry_gn approximately ?

#

im just saying i started learning python 2 years ago and dont know how long it took me to learn it so far to understand discord.py

#

also i took the hard way

#

just knowing bare basics and going to discord.py directly

final iron
slate swan
#

which slowed me down

#

it depends on many things. do you know any other programming language ?

final iron
#

Want to subclass? Extra time. Want to use a DB? Extra time. Want to do http requests? Extra time

flint heart
#

Theres no args necessary

slate swan
flint heart
#

It's just /map

slate swan
#

do you actually code and try out things do some small projects/challenges

#

or you just watch some tutorial and expect to remember it after few days

#

cause learning programming is playing with code and seeing what it does when you change somehing this way to learn

slate swan
final iron
#

Not the command

#

!d map

unkempt canyonBOT
#
map

map(function, iterable, *iterables)```
Return an iterator that applies *function* to every item of *iterable*, yielding the results. If additional *iterables* arguments are passed, *function* must take that many arguments and is applied to the items from all iterables in parallel. With multiple iterables, the iterator stops when the shortest iterable is exhausted. For cases where the function inputs are already arranged into argument tuples, see [`itertools.starmap()`](https://docs.python.org/3/library/itertools.html#itertools.starmap).
slate swan
final iron
#

That's the line your code is erroring on

#

Supposedly

slate swan
final iron
#

Also I would change your map function name as it's clashing with the built-in function

#

Makes it more complicated, more unreadable etc

slate swan
#

🙏

#

for example im such a weird guy i like reading source code and getting in depth how something works to undestand it from the inside

#

prolly not recommended for start but yeah

final iron
#

!d discord.app_commands.CommandTree.command

unkempt canyonBOT
#

@command(*, name=..., description=..., nsfw=False, guild=..., guilds=..., auto_locale_strings=True, extras=...)```
A decorator that creates an application command from a regular function directly under this tree.
final iron
#

@flint heart You can use the name arg instead

final iron
#

Reading exclusively isn't gonna help you learn that well

#

Try doing mini projects

flint heart
#

mean*

#

Thanks!

slate swan
flint heart
#

I'll just change it to like current-map or something

slate swan
#

😉

final iron
#

Just saying, this isn't the solution to your issue, it's just something I spotted

flint heart
#

Oh, alr

#

Im testing it rn

final iron
#

You're passing int as the first arguement to the map() function when it should be a function

#

I don't really use map() so I'm just guessing after reading the documentation

slate swan
#

!e py list_of_strings = ["1", "2", "3", "4", "5"] print(list_of_strings) print(list(map(int, list_of_strings)))

final iron
#

I ain't gon lie map() confuses me

flint heart
#

LMAO I LEFT THE TOKEN IN MY PASTEBIN AND SOMEONE RAN A SCRIPT TO MAKE IT SAY "I GAINED CONSCIOUSNESS" 😆

final iron
#

Also lambda

flint heart
#

I just reset it tho, so all good now

unkempt canyonBOT
#

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

001 | ['1', '2', '3', '4', '5']
002 | [1, 2, 3, 4, 5]
final iron
#

lambda is witchcraft

slate swan
final iron
#

I dunno, I just don't understand it ig

slate swan
#

all it does it runs the function on each item from the iterable

final iron
#

oh

slate swan
#

doesnt it say that on the docs

#

!d map

unkempt canyonBOT
#
map

map(function, iterable, *iterables)```
Return an iterator that applies *function* to every item of *iterable*, yielding the results. If additional *iterables* arguments are passed, *function* must take that many arguments and is applied to the items from all iterables in parallel. With multiple iterables, the iterator stops when the shortest iterable is exhausted. For cases where the function inputs are already arranged into argument tuples, see [`itertools.starmap()`](https://docs.python.org/3/library/itertools.html#itertools.starmap).
final iron
#

Yeah it does

slate swan
#

iterator that applies function to every item of iterable

final iron
#

!d lambda

unkempt canyonBOT
#

An anonymous inline function consisting of a single expression which is evaluated when the function is called. The syntax to create a lambda function is lambda [parameters]: expression

final iron
#

I don't understand lambda ngl

slate swan
#

i never use lambdas xd

#

its like short function

final iron
#

Or is it just a faster way of doing it

slate swan
#
def f(x):
    return x ** 2

# same as 

f = lambda x: x ** 2
final iron
#

hmm

slate swan
#

also its faster

final iron
#

I dunno, I'm just wondering

#

I'll try to use map instead of loops now

slate swan
#

its not like every for loop can be replaced with it

final iron
#

Yeah ik

slate swan
#

but if you have something like ```py
for item in items:
int_items.append(int(item))

final iron
#

Yeah, map would've been useful when I was manipulating spreadsheets

#

I was doing basically that

buoyant quail
naive briar
#

(it's slower than a list comprehension when you need to use a lambda for it)

buoyant quail
#

Also about map, filter (+ functools, itertools) - if you can use it without using python (defs or lambdas) then it will give you very good speed.
Because you will have a loop that is fully executed in C without python

slate swan
#

Yeah if its in stdlib its prolly faster than manual implementation

delicate epoch
#

anyone know a good tutorial or soemthing on how to host my bot on linode? can't find a good video

maiden fable
delicate epoch
maiden fable
harsh orbit
#

I knew the reason

#

The bot not detecting the message cause there are another message send before it

#

Do you have an idea how to solve this?

buoyant quail
#

Write a correct check.
wait_for returns first event on which your check returns True

#

Other events are skipped

harsh orbit
#

You can try

#
  • check is correct in the first message (check only) m.author ......., But the if condition is not correct
#
import discord
import os
import asyncio
from discord.ext import commands

intents = discord.Intents.all()
prefix = "!"
Token = os.environ['token']
bot = discord.ext.commands.Bot(prefix, intents=intents)


@bot.command()
async def buy(ctx):
    guild = bot.get_guild(1142023460533571635)
    bank_id = 1113386046021963776
    bank = guild.get_member(bank_id)
    await ctx.send(bank.mention)
    await ctx.send("how are you?")
    probot = guild.get_member(282859044593598464)

    
      
    try:
      Message = await bot.wait_for("message", check=lambda m: m.author == ctx.author and m.channel == ctx.channel, timeout= 50.0)
      message = Message.content.lower()
      
      
      

    except asyncio.TimeoutError:
      await ctx.send("Time ended")

    else:
      if "hi" in message:
        await ctx.send("Thanks for buy")

      
        

@bot.event
async def on_ready():
  print("Online")

bot.run(Token)
buoyant quail
#

You are checking for any message from the same author

harsh orbit
#

What about "if "hi" in message"

#

should I add in Check
m.content ==?

buoyant quail
#

But after getting the message

harsh orbit
#
  • I don't want specific contact I just want to check if 2 things in it
buoyant quail
harsh orbit
harsh orbit
buoyant quail
#

As you already did it. But inside the check.

harsh orbit
#

like
100 in m?

buoyant quail
#

m.content

harsh orbit
#

Ok I will try and test

harsh orbit
buoyant quail
#

Send as text

#

It's hard to read with these wraps

harsh orbit
#

I can't copy the error

buoyant quail
#

The code

harsh orbit
#
import discord
import os
import asyncio
from discord.ext import commands

intents = discord.Intents.all()
prefix = "!"
Token = os.environ['token']
bot = discord.ext.commands.Bot(prefix, intents=intents)


@bot.command()
async def buy(ctx):
    guild = bot.get_guild(1142023460533571635)
    bank_id = 1113386046021963776
    bank = guild.get_member(bank_id)
    await ctx.send(bank.mention)
    await ctx.send("how are you?")
    probot = guild.get_member(282859044593598464)

    
      
    try:
      Message = await bot.wait_for("message", check=lambda m: m.author == ctx.author and m.channel == ctx.channel, timeout= 50.0 and "100" in m.content and bank.mention in m.content)
      message = Message.content.lower()
      
      
      

    except asyncio.TimeoutError:
      await ctx.send("Time ended")

    else:
      ctx.send("I`m good")

      
        

@bot.event
async def on_ready():
  print("Online")

bot.run(Token)
#

I missed await but nvm

#

The error about m