#discord-bots

1 messages · Page 115 of 1

slate swan
#

Hello, my code doesn't work and I wanted to know if someone could tell me how to modify it so that it works? py keywords = ['bonjour', 'salut'] @client.event async def on_message(message): if keywords in message.content: await message.channel.send('bonjour')

still elbow
winged coral
#

I don't think it should?

#

if keywords in message.content This is backwards

still elbow
#

no

slate swan
still elbow
# slate swan

Your going to have to loop through or select them manually your list etc keywords[0] or keywords[1].
if (keywords[0] in message.content) or (keywords[1] in message.content). Iterating for keyword in keywords: if keyword in message.content:

#

i am on mobile i can’t really explain it much better

wary crystal
#

Why would you do that?

winged coral
#

if any(word in message.content for word in keywords)

still elbow
#

or that

winged coral
#

Might have to make it a list not sure if any works on generators 🤔

wary crystal
#

word isn't a word though

still elbow
#

his list

wary crystal
#

It's a character

alpine cove
wary crystal
#

!e ```py
for word in "Hello World!": print(word)

unkempt canyonBOT
wary crystal
#

It should be split first

winged coral
#

for word in keywords

wary crystal
#

Oh I looked at your comp wrong

slate swan
#

it answers to the message but not to the right keywords

still elbow
#

indent probably

wary crystal
#

But it would also make sense imo to split message.content as well

winged coral
#

@slate swan Do you want the message to be one of the keywords or do you want it to contain one of the keywords?

winged coral
#

So my comp should work fine

slate swan
#

if any(word in message.content for word in keywords) ?

winged coral
#

Yeah although you might have to cast the generator as a list

#

Don't think so though

#

Lemme see

#

You don't

slate swan
#

it doesn't work

winged coral
#

How so

gilded stump
#

anyone here knows javascript too?

mental hollow
#

Is there any packages I can use to help me moderate nicknames on Discord & change things such as h€rr0 to "herro"? Like take away the special characters and replace them for 'normal' ones?

slate swan
#

hey i want to get the user who added the bot to the server to send him a greeting message... I can always do that for the owner but it's not always the owner who invites the bot

hushed galleon
#

^ didnt think of that, although its not always feasible as per the answer stating it requires mange guild perms

cloud dawn
#

Zalgo brr

#

For those who don't know what zalgo is -> e̸̽́x̶͌̕ȁ̸̑m̴͋̇p̷̐̎l̸̽̓e̷̓͗

hushed galleon
#

well if its just diacritics you can remove those, but for other characters i remember seeing a library with handcrafted mappings to ascii, but i forgot its name

cloud dawn
#

!charinfo e̸̽́

unkempt canyonBOT
alpine cove
#

Thеsе аге гцssiаи lеttегs

cloud dawn
#

!charinfo и

unkempt canyonBOT
hushed galleon
#

!pip unidecode i think was what i remembered, although its not necessarily meant to convert unicode to their closest latin character, e.g. becomes EUR

unkempt canyonBOT
mossy jacinth
#

can someone tell me how i can send the result into the same channel as the command was used in?

unkempt canyonBOT
gilded stump
#

!d nextcord.Status.idle

unkempt canyonBOT
gilded stump
#

r?help

#

r?ajuda

mossy jacinth
#

Tried to add an option to make a title but this came?

amber ether
#

And 13

mossy jacinth
#

and whats wrong there?

#

Found it out

#

but the only error was that i wrote "title" instead of "name" on line 13

amber ether
#

Wait u did wrote title xd

slate swan
#

I'm fairly new to coding and I've already made a main.py folder for my bot and got it online but I'd like to make a seperate folder to add different commands to without just piling up everything in my main.py folder but how would I link those commands to my main.py folder?

slate swan
#

Thanks I'll check it out

torn sail
granite plume
#
if message.content.lower() == 'hello': 
    #helloflag = True
    message = await message.channel.send('Hello. How are you feeling today? ')
        
if message.content.lower() in ['good', 'fine', 'great', 'happy']:
    await message.channel.send("That's good")

How do I make it so that when the user responds to “Hello, how are you feeling today?”, if the user says “good”, the bot says “that’s good”

sick birch
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.10)"). 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.10)") 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.10)") 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
#

@sick birch hey where do you see future of text based commands, will discord totally remove it?

sick birch
#

I would suggest building your bot from the ground up with slash commands in mind to account for scalability

#

even if you don't like it (i know many don't)

granite plume
#
async def on_message(self, message):
    if message.author == self.user:
        return
    if message.content == 'ping':
        await message.channel.send('pong')

    if not self.helloflag and message.content.lower() != "hello":
        await message.channel.send('Say hello to start')

    if message.content.lower() == 'hello': 
        self.helloflag = True
        message = await message.channel.send('Hello. How are you doing today?')
    
    if self.helloflag:
        if message.content.lower() in ['good', 'fine', 'great', 'happy']:
            await message.channel.send("That's good")
            self.helloflag = False
        elif message.author != self.user:
            print(message.content.lower())
            await message.channel.send("Oh ok")
            self.helloflag = False
slate swan
#

or self.bot.user

#

whichever ur using

granite plume
#

alright thanks

lament plinth
#

have u guys seen this before lmao

#

cuz i havent

lament plinth
#

i did not know that discord.py updated to 2.0 sorry

#

thats why my cogs didnt work

slate swan
#

How do I make my bot send a embed after a certain amount of messages are sent
Ik how to make a embed

tall patrol
pulsar bridge
#

Hey, simple issue here that my tired brain can't fix

@bot.command()
@commands.cooldown(1, 86400, type = discord.ext.commands.BucketType.user)
async def daily(ctx):
    try:
        query = { "user_id": ctx.author.id }
        existing_user = money_other.find(query)
        for result in existing_user:
            current_points = result["points"]
            actual_money = result["money"]
        moneyamount_two = actual_money + (random.randint(350, 420))
        addpoints = current_points + 1
        original_query = { "user_id": ctx.author.id }
        updated_money_values = { "$set": { "money": moneyamount_two } }
        updated_points = { "$set": { "points": addpoints}}
        money_other.update_one(original_query, updated_points)
        money_other.update_one(original_query, updated_money_values)
        embed_title = f"Daily collected, f{ctx.author.name}!"
        embed = discord.Embed(title=embed_title, description="", color=1000000)
        await ctx.send(embed=embed)

    except CommandOnCooldown:
        embed = discord.Embed(title=f'{ctx.author.name}, You need to wait {retry_after} seconds until you can claim your daily again!', description="", colour=1000000)
        await ctx.send(embed=embed)

Why doesn't the except part execute?
Just ignores it and gives me the error code in the terminal

alpine cove
#

its command.error

#

look it up in the docs

pulsar bridge
#

Aight

#

lets see if I can find something

#

What would the solution be though? Or could you link the exact place?
There's like, 30 different instances of it being mentioned in the docs...

vale wing
#

Just saying it isn't a good idea to do such cooldown with decorator

#

Cause if you shutdown the bot it will reset

pulsar bridge
#

I was told it was the best idea DC_z2shrug

vale wing
#

Better to use a db

vale wing
alpine cove
alpine cove
pulsar bridge
#

Got that, doesn't affect what I'm doing too much as the cooldowns will be short and I don't update the bot much
Is for a small server. Daily command is just to see if I can get it working

#

all I need to know is
if there is a solution to my error
where to find it
If there isn't a solution
Then I'll go back and experiment

alpine cove
#

as said command.error

pulsar bridge
#

Could you point me to where in the docs is it explained?
As I said, there were quite a few places it was mentioned.

vale wing
#

!d discord.ext.commands.Command.error

unkempt canyonBOT
#

@error```
A decorator that registers a coroutine as a local error handler.

A local error handler is an [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") event limited to a single command. However, the [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") is still invoked afterwards as the catch-all.

Changed in version 2.0: `coro` parameter is now positional-only.
pulsar bridge
#

Epic, thanks a ton

light violet
#

How do i make a simple music bot iwth auto song search

alpine cove
#

there are millions of tutorials

light violet
#

I k btw i dont want to use ytdl

#

I just want to play the song from a url

warped mirage
#

Guys, is there an issue with discord.py imports not working in python 3.11?

#

My imports arent working so i am unsure

#

on 3.10 it works, not on 3.11

vale wing
warped mirage
vale wing
#

That issue happens because of bad interpreters management, you caused it and can fix by yourself, it's not a code problem

warped mirage
#

I had python 3.10.5 which worked, when i switch to 3.11.0 nothing, like i deleted 3.10.5 to be sure, but it still doesn't work, i even tried uninstalling and reinstalling the package, any idea what I should do?

vale wing
#

Uninstall all python versions and install 3.11 with "Add Python to PATH" checkmark. Also use venvs for packages management

warped mirage
#

I never used venvs Lol

vale wing
#

You should

warped mirage
#

How come

vale wing
#

!venv

unkempt canyonBOT
#

Virtual Environments

Virtual environments are isolated Python environments, which make it easier to keep your system clean and manage dependencies. By default, when activated, only libraries and scripts installed in the virtual environment are accessible, preventing cross-project dependency conflicts, and allowing easy isolation of requirements.

To create a new virtual environment, you can use the standard library venv module: python3 -m venv .venv (replace python3 with python or py on Windows)

Then, to activate the new virtual environment:

Windows (PowerShell): .venv\Scripts\Activate.ps1
or (Command Prompt): .venv\Scripts\activate.bat
MacOS / Linux (Bash): source .venv/bin/activate

Packages can then be installed to the virtual environment using pip, as normal.

For more information, take a read of the documentation. If you run code through your editor, check its documentation on how to make it use your virtual environment. For example, see the VSCode or PyCharm docs.

Tools such as poetry and pipenv can manage the creation of virtual environments as well as project dependencies, making packaging and installing your project easier.

Note: When using Windows PowerShell, you may need to change the execution policy first. This is only required once:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser

vale wing
#

Not to have this problem in the future

warped mirage
#

I just added to path, still doesn't work lol

vale wing
#

Then use venv

warped mirage
#

maybe discord package is in wrong file

#

Lmfao on 3.10.5 it works again

#

Something wrong with 3.11 then

unkempt canyonBOT
light violet
#

My bot isnt playing the music

#

Wott is the prob

vocal snow
unkempt canyonBOT
#

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)
light violet
#

@vocal snow dont help me with ytdl btw if u see in play cmd it plays a file from storage i want help regarding that

light violet
#

W8

#

@commands.command()
async def play(self, ctx, *, query):
"""Plays a file from the local filesystem"""

    source = discord.PCMVolumeTransformer(discord.FFmpegPCMAudio("./Mood.mp3"))
    ctx.voice_client.play(source, after=lambda e: print(f'Player error: {e}') if e else None)

    await ctx.send(f'Now playing: {query}')
#

@vocal snow

vocal snow
#

looks good to me

#

are you getting an error

light violet
#

Nope

#

Btw nothing is heard

slate swan
#

how would I go about making an economy command for my bot in a separate subfolder and linking it to the main.py with a cog?

#

discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'NoneType' object has no attribute 'purge'

placid skiff
# slate swan

User.dm_channel is returning None, the bot doesn't have a private channel with the specified user

rugged shadow
slate swan
placid skiff
#

Then probably it can't be found in the bot cache, anyway just use the create_dm coroutine

#

PEP8 triggered

rugged shadow
#

like

def x():
    """Does x blah blah blah"""
    pass
slate swan
rugged shadow
#

Yes

slate swan
#

how

rugged shadow
#

I think docstrings are automatically set to the help property of that command

#

Only works if you properly place the docstring

slate swan
#

hmm but im not using text commands how does that help

rugged shadow
#

maybe if you ever decide to write a front-end for that bot, iterate through the bot's commands

slate swan
#

ty

warped mirage
#

Python 3.11 still ain’t working for me like I can’t do discord imports, someone help

rugged shadow
#

are you in a venv

warped mirage
#

No

rugged shadow
#

what IDE are you using?

warped mirage
rugged shadow
slate swan
#

how

rugged shadow
warped mirage
#

Vscode

rugged shadow
# slate swan how
@commands.slash_command(...)
async def cleardm(...):
    """slash command blah blah"""
slate swan
#

got it

rugged shadow
#

maybe it's using the old one

warped mirage
#

Ye I changed to 3.11,

#

Then the imports for discord don’t work

#

If I switch back to 3.10.5

rugged shadow
#

what do you mean by "don't work"

warped mirage
rugged shadow
rugged shadow
#

different python version will have different packages

#

try py -3.11 -m pip install discord.py

warped mirage
#

I use discord.py2.0 the one from github that was download

rugged shadow
#

no need to download from github

vale wing
#

Real ubuntu 22.10

mossy jacinth
#

Hello! I want to add an option to add custom colors to the embed and if no hex was given it will use a random color but it still uses random colors even when a hex was given

#

or is there no such thing called number in modals? If so what should it be?

naive briar
#

Because you're telling it to choose a random colour if the self.number is not None, because you set its value in the __init__, it will always exist and never be None. I assume that you want to check if the colour was provided or not. You should check its value if it's None instand

warped mirage
rugged shadow
#

i think so

warped mirage
#

Ok

pearl fjord
#

how can i run a discord bot in a thread with threading.Thread ?

mossy jacinth
naive briar
naive briar
alpine cove
#

either jobs is a list or job[job]

#

bruh

#

idk how you structured your shit

slate swan
#

not tryna be rude or anything but do you just use peoples code or something? you error is just a basic python error and you stored it a specific way so you should know the issue

shrewd apex
#

at this point u are just playing lego with python

paper sluice
#

tf

shrewd apex
#

job_name = jobs(int[job][“name“]) ducky_australia

paper sluice
#

syntax has left the chat

pliant gulch
#

1["name"]?

#

I don't think you meant to subscript an integer

shrewd apex
#

if i put it in help channel i am prolly gonna get ignored

pliant gulch
#

What

slate swan
#

yo

#

async def on_raw_reaction_add(self, payload):
"""
Give a role based on a reaction emoji.
"""
if payload.message_id != self.target_message_id:
return

#

(like this )

slate swan
unkempt canyonBOT
#

class discord.RawReactionActionEvent```
Represents the payload for a [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add") or [`on_raw_reaction_remove()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_raw_reaction_remove "discord.on_raw_reaction_remove") event.
slate swan
#
@bot.event
async def on_message(msg):
  channel = bot.get_channel(996119147337494538)

  embed = discord.Embed(title=f"New feedback!", description=f"User: {msg.author.mention} \n \n Feedback: {msg}", timestamp=datetime.now() , color=0x4e80cf)
  embed.set_thumbnail(url=msg.author.display_avatar.url)
  embed.set_footer(text=f"Requested by {msg.author} | {msg.author.guild.name}")
  moji=await channel.send(embed=embed)
  await moji.add_reaction('![Fishy](https://cdn.discordapp.com/emojis/998098439948730368.webp?size=128 "Fishy")')  ```
and it wont stop spamming that
vocal snow
#

well

#

you're sending a message whenever you receive a message

#

its a loop

slate swan
#

i am trying to do that if they send a message in a sepcific channel

#

also how do i do that if the message is from a bot it wont send

vocal snow
#

you need an if statement to do both of those

slate swan
#

if msg.author.bot:
return?

vocal snow
#

yep

#

and you can check if message.channel is the channel the want there too

slate swan
#

okay

#

@vocal snow it does that

vocal snow
#

looks like a message object repr to me

#

you're passing in the message object instead of just the content (msg.content)

slate swan
#

ohh

#

i think that would do that

#

@vocal snow

vocal snow
#

you're still passing an object directly

slate swan
#
@bot.event
async def on_message(msg):
  Channel = bot.get_channel(996119147337494538)
  if msg.channel is not Channel:
    return
  embed = discord.Embed(title=f"New feedback!", description=f"User: {msg.author.mention} \n \n Feedback: {msg.content}", timestamp=datetime.now() , color=0x4e80cf)
  embed.set_thumbnail(url=msg.author.display_avatar.url)
  embed.set_footer(text=f"Requested by {msg.author} | {msg.author.guild.name}")
  if msg.author.bot:
    return
  moji=await Channel.send(embed=embed)
  await moji.add_reaction('![Fishy](https://cdn.discordapp.com/emojis/998098439948730368.webp?size=128 "Fishy")')```
vocal snow
#

are you sure you saved your code

slate swan
#

i have auto save

#

ill try running it again

#

IDK WHAT HAPPENED

#

TYSM

vocal snow
#

👍

slate swan
#

@vocal snow thats weird

#

now only that event works

#

no other commands

vocal snow
#

you need to process the commands

slate swan
#

await bot.process_commands(msg)

vocal snow
#

yes

slate swan
#

?

#

still doesnt work

vocal snow
#

code please

slate swan
# vocal snow code please
@bot.event
async def on_message(msg):
  Channel = bot.get_channel(996119147337494538)
  if msg.channel is not Channel:
    return
  embed = discord.Embed(title=f"New feedback!", description=f"User: {msg.author.mention} \n \n Feedback: {msg.content}", timestamp=datetime.now() , color=0x4e80cf)
  embed.set_thumbnail(url=msg.author.display_avatar.url)
  embed.set_footer(text=f"Requested by {msg.author} | {msg.author.guild.name}")
  if msg.author.bot:
    return
  moji=await Channel.send(embed=embed)
  await moji.add_reaction('![Fishy](https://cdn.discordapp.com/emojis/998098439948730368.webp?size=128 "Fishy")')
  await bot.process_commands(msg)```
vocal snow
#

so you only want commands to work in that channel?

slate swan
#

nono

vocal snow
#

ok, so think about how the function is going to work

slate swan
#

umm

vocal snow
#

if msg.channel is not Channel: return

#

this ends the function right there

slate swan
#

OH

#

then what do i do instead

vocal snow
#

think about it

#

there's no compulsion that you have to process commands at the end of the event

slate swan
#

so at the start?

vocal snow
#

you just need to restructure the logic

#

you can do it at the start, but then it'll process commands sent by bots as well

slate swan
#

oh

vocal snow
#

so you'll need to move those if statements around a bit

slate swan
#

i cant do it that way right

vocal snow
#

think of the flow

#
  1. you check if the msg author is a bot
#
  1. if it is, return
#
  1. process commands
slate swan
#

oh

vocal snow
#
  1. check if the channel is the one you want
#
  1. send your embed
slate swan
#
@bot.event
async def on_message(msg):
  Channel = bot.get_channel(996119147337494538)
  if msg.author.bot:
    return
  embed = discord.Embed(title=f"New feedback!", description=f"User: {msg.author.mention} \n \n Feedback: {msg.content}", timestamp=datetime.now() , color=0x4e80cf)
  embed.set_thumbnail(url=msg.author.display_avatar.url)
  embed.set_footer(text=f"Requested by {msg.author} | {msg.author.guild.name}")
  await bot.process_commands(msg)
  if msg.channel is not Channel:
    return
  moji=await Channel.send(embed=embed)
  await moji.add_reaction('![Fishy](https://cdn.discordapp.com/emojis/998098439948730368.webp?size=128 "Fishy")')```
#

will it be like that

vocal snow
#

that would work

slate swan
#

i will try

vocal snow
#

but there's no reason to create the embed if you're not going to send it anyways

#

so you can move that part after the 2nd if statement too

slate swan
#

works

slate swan
#

also

#

can u help me w that-

#

how do i do that it will purge the author message

#

will await msg.channel.purge(limit=1)
would do it?

vocal snow
#

just use msg.delete

slate swan
vocal snow
#

()

slate swan
#

and then limit?

#

or just it

vocal snow
#

there is no limit since the api call is to delete that specific message

slate swan
#

ohh okay thanks

lucid galleon
#

I want that bot will dm me when someone send help message``` elif message.content.startswith("help"):
send me message

#

any help?

lucid galleon
#

here's the code ```
intents = discord.Intents.default()
intents.message_content = True

client = discord.Client(intents=intents)

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

elif message.content.startswith("help"):
      send me message
#

also it's printing none``` user = client.get_user(1035557353845706762) print(user)

naive briar
#

!d discord.Client.get_user - it'll return None if it can't find the user with the given ID

unkempt canyonBOT
#

get_user(id, /)```
Returns a user with the given ID.

Changed in version 2.0: `id` parameter is now positional-only.
naive briar
#

Also you have to wait until the bot have fully started before using that

lucid galleon
#

as i have given my own id

#

still it's showing None

#

🤔

lucid galleon
#

]

primal token
primal token
#

make a check, that checks if discord.Client.get_user was successful or not

lucid galleon
#

ok then?

primal token
#

e.g

user =  clientvar.get_user(id) or await clientver.fetch_user(id)
lucid galleon
#

ok

#

Not working```
user = client.get_user(788606884285251644) or await client.fetch_user(788606884285251644)
print(user)

#

here's the error<coroutine object Client.fetch_user at 0x0000017C90F333C0> F:\pyenv\lib\site-packages\discord\client.py:409: RuntimeWarning: coroutine 'Client.fetch_user' was never awaited await coro(*args, **kwargs) RuntimeWarning: Enable tracemalloc to get the object allocation traceback

primal token
#

show your code

sick birch
#

No

lucid galleon
#
 elif message.content.startswith("help"):
        user = client.get_user(788606884285251644) or await client.fetch_user(788606884285251644)
        print(user)
        await message.channel.send("ok")
primal token
#

Did you saved your code, if you did, did you used the fetch_user method with send and only had 1 await?

primal token
# sick birch No

Not like i wanna see your code, you probably use nested classes

#

😒

lucid galleon
#

what i did is shown to you

primal token
#

and can you show the whole traceback?

#

!traceback

unkempt canyonBOT
#

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.

lucid galleon
#

ok

unkempt canyonBOT
#

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.

lucid galleon
#

please delete it

primal token
#

The actual whole thing!

lucid galleon
#

!trace elif message.content.startswith("help"):
user = client.get_user(788606884285251644) or await client.fetch_user(788606884285251644)
print(user)
await message.channel.send("ok") ```
elif message.content.startswith("help"):
user = client.get_user(788606884285251644) or await client.fetch_user(788606884285251644)
print(user)
await message.channel.send("ok")

unkempt canyonBOT
#

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.

lucid galleon
#

is this correct ?

slate swan
#

can someone help me w making the buttons always work? everytime i run the bot twice the buttons are not working same w select menus, how do i make it work everytime?

unkempt canyonBOT
#

add_view(view, *, message_id=None)```
Registers a [`View`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View "discord.ui.View") for persistent listening.

This method should be used for when a view is comprised of components that last longer than the lifecycle of the program.

New in version 2.0.
slate swan
slate swan
#

add_view(view, *, message_id=create_ticket:green)
?

#

@sick birch

lucid galleon
slate swan
#

Hello, I don't know about bulk message deletion, I read the document but I don't understand, can anyone help?

slate swan
slate swan
#

Ohh

#

Search in youtube i dont rlly know how to explain

slate swan
faint mural
slate swan
#

yo anyone wanna make an discord bot?

faint mural
spice scroll
#

currentyl trying rn. I was successful a couple years back and now i cant do shit

slate swan
spice scroll
#

what kind of bot

slate swan
slate swan
spice scroll
#

i don't think 🧠❌

slate swan
#

hmmm

faint mural
#

This is an event, which gets called on an bulk delete. So no it is not the same.

slate swan
#

idak

slate swan
#

like an msg bot

#

it says like Hello good morning and send embed texts and stuff

spice scroll
#

I could, doing one for a school project anyway

slate swan
#

so we doing vscode or replit

spice scroll
slate swan
#

btw i am not good at making an bot

spice scroll
#

I use pycharm 💀

slate swan
#

lol

slate swan
spice scroll
#

another IDE

slate swan
#

lol

slate swan
#

we use replit

#

ok?

spice scroll
#

ok

slate swan
#

alr dm me

spice scroll
#

oh yeah

slate swan
#

ill send link

slate swan
#
  File "C:\Users\lende\Desktop\Desktop\Sesh-Bot-main_-_Saldo_1\aa\main.py", line 2, in <module>
    import discordModules.auth as auth
  File "C:\Users\lende\Desktop\Desktop\Sesh-Bot-main_-_Saldo_1\aa\discordModules\auth.py", line 4, in <module>
    import clientCommands
  File "C:\Users\lende\Desktop\Desktop\Sesh-Bot-main_-_Saldo_1\aa\clientCommands.py", line 4, in <module>
    import commands.events.on_message
  File "C:\Users\lende\Desktop\Desktop\Sesh-Bot-main_-_Saldo_1\aa\commands\events\on_message.py", line 5, in <module>
    from discordHelpers.createQuestions import *
  File "C:\Users\lende\Desktop\Desktop\Sesh-Bot-main_-_Saldo_1\aa\discordHelpers\createQuestions.py", line 8, in <module>
    from discord_components import Button, component, ButtonStyle
ModuleNotFoundError: No module named 'discord_components'``` help me please
#

the library has been discontinued and you dont have it installed

slate swan
#

you'll have to use discord.py's Views to make buttons and stuff instead of this library

spice scroll
#

!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. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.

To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.

Next, in your bot 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

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

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

For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.

spice scroll
#

i put those in as follows and it says it doesnt cant import intents from discord

mossy jacinth
untold iron
#

Hey there, im struggling to print the value from payout

#

Whenever i run i get None

#

Please let me know what im doing wrong

slate swan
#

is there a way to run the bot async with another task that uses the terminal?

whole sparrow
#

Guys, how do I add a space after the title in an embed for my description

drifting swallow
#

payout*

#

so like payout.items[0].value

dreamy heron
#

payout ['items']['amount']['value']

#

@untold iron this Will work

untold iron
#

Thank you all

#

Working, i need to learn dictionaries

#

much appreciated

obtuse blaze
#

I was told to make classmethods if I wanna call an async fuction inside __init__ but how do I await ? is it like await Class.Method()?

faint mural
#

Rather than doing that, just define self.something: something = None and add the value to it in some function like setup_hook

slate swan
#

a possible way would be using asyncio.create_task()

obtuse blaze
#
    def __init__(self,author) -> None:
        super().__init__()
        self.value = None
        self.author = author
        self.damage,self.player,self.mob = Mobs(author).MobEncounter()```

```class Mobs():
  def __init__(self, id):
    self.id = id
  async def MobEncounter(self):
      async with aiosqlite.connect('db.db') as con:
        cur = await con.execute("SELECT Constitution,Max_Constitution,Dexterity,Intelligence,mana,Strength,floor,class,level FROM Character WHERE user_id = ?", (self.id,))
        player = cur.fetchone()
        if player[7] == "Adventurer":
          damage = (10 * ((player[2] * 1)+(player[3] * 0.25)+(player[4] * 0.1)+(player[5] * 1.5))) 
        elif player[7] == "Magician":
          damage = (10 * ((player[2] * 0.25)+(player[3] * 1.5)+(player[4] * 1)+(player[5] * 0.1)))
        elif player[7] == "Wanderer":
          damage = (10 * ((player[2] * 0.5)+(player[3] * 0.1)+(player[4] * 0.1)+(player[5] * 0.5)))
        cur = con.execute("SELECT MobName,MobHealth,MobDamage,Mobexp FROM Mobs where floor = ? and Mob_ID = ?", (player[6],))
        mob = cur.fetchone()
        list_mob = []
        list_player = []
        for i in mob:
          list_mob.append(i)
        for i in player:
          list_player.append(i)
      
      return damage,list_player,list_mob```
#

Here is code for context

slate swan
#

!e ```py
import asyncio

class Foo:
def init(self):
asyncio.create_task(self.bar())

async def bar(self):
   print("hello")

can ignore this part

async def main():
Foo()

asyncio.run(main())

unkempt canyonBOT
#

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

hello
slate swan
#

example code^, you can convert it to however you want to use

obtuse blaze
#

ohhh so in this case it would be
self.damage,self.player,self.mob = asyncio.create_task(MobEncounter()) I remove class and just leave empty fuction

slate swan
#

well, you cant.

#

because create_task doesnt return a value

obtuse blaze
#

smh

#

so how could I do it in this context? ThonkSpin

slate swan
#

but, you can assign self.damage etc withing the async function itself

#

instead of returning them

obtuse blaze
#

my brain going boom

#

sry XD

slate swan
#

did you not understand what im trying to say?

obtuse blaze
#

imma be honest not really sorry for that im just trying to think in so much stuff

slate swan
#
# dont do this.
class Foo:
    def __init__(self):
       self.hello = asyncio.create_task(self.bar())
    
    async def bar(self):
       return "hello"
# do this instead
class Foo:
    def __init__(self):
       asyncio.create_task(self.bar())
    
    async def bar(self):
       self.hello = "hello"```
obtuse blaze
#

so in this case I would need to move the method "MobEncounter" to the button class

#

correct?

slate swan
#

your MobEncounter method is also faulty, you forgot to await many things there

faint mural
#

A definition of instance variables outside init isn't recommended in general, there are rare cases in which it is natural.

For example, when you have a parent class that defines several variables that its child classes won't use, and whose definition will make its child waste time or resources, or will be simply unaesthetic.

It should be defined there.

obtuse blaze
#

cause I had it without await and wanted to make it into await thats why im asking here

#

cause I have this problem for a long long time

#

alr imma try tysm to everyone

obtuse blaze
#

I think I mess up

mossy jacinth
#

Hello! No error here but how can I make this more compact? So it doesnt take so many lines?

sick birch
#

Consider using a dict to make it look better

mossy jacinth
#

can you show me an example?

slate swan
#

how would i have a changing discord bot status? so one will be like watching over many members another will be like !help

#

!e print

unkempt canyonBOT
#

@slate swan :warning: Your 3.10 eval job has completed with return code 0.

[No output]
glad cradle
mossy jacinth
sick birch
#

I don't know if None is hashable

#

You might try checking if it's None seperately

#

Also if you don't say anything it might be "", not sure though

mossy jacinth
slate swan
#

!e

x = {None: 34}
print(x[None])
unkempt canyonBOT
#

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

34
sick birch
#

yup

#

discord.py is probably giving you an empty string then

slate swan
#

he's actually using nextcord ^^

sick birch
#
embed_colors = {...}
if self.name2.value == "":
  # use random color
else:
  color = embed_colors.get(self.name2.value)

or something similar

sick birch
mossy jacinth
#

so like this?

slate swan
#

I need a gen bot made, can and willing pay!

mossy jacinth
#

isnt that against the rules here

#

rule 9 or something

sick birch
unkempt canyonBOT
#

9. Do not offer or ask for paid work of any kind.

slate swan
sick birch
#

no worries

glad cradle
slate swan
#

need help by making it change the embed on the first part of the /help command aka dropdown menu

#
async def self(interaction: discord.Interaction):
  class SelectView(View):
    @discord.ui.select(options=[
      discord.SelectOption(label="roblox", value="roblox", description="roblox commands"),
      discord.SelectOption(label="social", value="social", description="social command"),
    ])
    async def select(self, interaction, select):
      if select.values[0] == 'roblox':
        em = discord.Embed(color=0x00ff00)
        em.add_field(name='roblox', value='roblox commands')
        await interaction.response.send_message(embed=em)
      if select.values[0] == 'social':
        em = discord.Embed(color=0x00ff00)
        em.add_field(name='social', value='social commands')
        await interaction.response.send_message(embed=em)
  view = SelectView()
  await interaction.response.send_message('help command', view=view)```
#

im trying to make it change the first text and make it change to a embed after select a dropdown

slate swan
#

Hello!

I am trying to make a verify command and when they clikc the button it sends them a capthca

I have the captcha down but I want to bot to respond with 'Check you dms'

But the dms part is a hyperlink to link to the bot and there dms

How would i do something like that?

Current code:

await interaction.response.send_message(f'{sender.mention} Check your [dms]()')
sick birch
slate swan
#

how do that

sick birch
#

Getting the sent DM message or getting its jump URL

slate swan
#

the linking to the dms

sick birch
#

!d discord.Message.jump_url

unkempt canyonBOT
slate swan
#

how to i make it just to the dm?

sick birch
#

you get the DM message and call .jump_url on it

#

the user can click on that and it'll take them to the message in the DM

slate swan
#

can someone help me about discord.py custom command , permission check.

slate swan
#

Hey!

i was wondering how to do this:

i am using pycord

sick birch
slate swan
#

ty

#

also:

I am trying to add timestamps to my embeds i have that but its off by 7 hours my time how would i fix that?

#

datetime.utcnow()

#

how would i make it do mst time?

slate swan
slate swan
# slate swan discord.py has a method for this already, ```timestamp=ctx.message.created_at```

returns error
Traceback (most recent call last):
File "C:\Users\xrkzl\AppData\Roaming\Python\Python310\site-packages\discord\bot.py", line 1008, in invoke_application_command
await ctx.command.invoke(ctx)
File "C:\Users\xrkzl\AppData\Roaming\Python\Python310\site-packages\discord\commands\core.py", line 359, in invoke
await injected(ctx)
File "C:\Users\xrkzl\AppData\Roaming\Python\Python310\site-packages\discord\commands\core.py", line 135, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'NoneType' object has no attribute 'created_at'

slate swan
#

yea

slate swan
slate swan
# slate swan what are the commands parameters
@bot.slash_command(description="Returns the bots current ping")
async def ping(ctx):
    cool = random.randint(1,3)
    first = f"{round(bot.latency* 1000)}ms"
    second = f"{round(bot.latency* 2100)}ms"
    embed=discord.Embed(description="Pong! \n\n**Initial latency:** `Loading...` \n**Round-Trip latency:** `Loading...`", color=embedcolor, timestamp=times)
    embed.set_footer(text=f'Command run by {ctx.author}', icon_url=iconurl)
    await ctx.respond(embed=embed)
    await asyncio.sleep(cool)
    embed=discord.Embed(description=f"Pong! \n\n**Initial latency:** `{first}` \n**Round-Trip latency:** `{second}`", color=embedcolor, timestamp=times)
    embed.set_footer(text=f'Command run by {ctx.author}', icon_url=iconurl)
    await ctx.edit(embed=embed, delete_after=20.0)
    where = ctx.channel
    if botlog == True:
        embed=discord.Embed(title="Command Logging", color=embedcolor, timestamp=times)
        embed.add_field(name="Command ran", value="/ping", inline=False)
        embed.add_field(name="Command ran by", value=f"{ctx.author.mention} | {ctx.author.id}", inline=False)
        embed.add_field(name="Where", value=where.mention)
        await bot.get_channel(logcha).send(embed=embed)
        logweb.send(embed=embed)
    else:
        pass
obtuse blaze
#

on @app_commands.check how can I put 2 fuctions?

slate swan
#

i'm sure theres a way for slash commands

#

don't know it off the top of my head

slate swan
#

instead of datetime.utcnow()

just do

datetime.now()

supple thorn
#

sudden urge to get back to trying to make bots any significant differences between discord.py and disnake while i was away?

supple thorn
#

that is one sus folder name

gaunt agate
#

its for a discord server with my friends

#

but whats the error mean

#

how do i fix this error

#

whats the intents argument

slate swan
#

Hello, i'm making a blackjack game in my bot and i'm running into an issue

in blackjack you can 'double down' but only if you have not yet drawn any cards after your original 2 starting cards, and if your 2 starting cards add up to a total of 9, 10 or 11 points.

I would like to make it so after the "draw" button has been clicked once, the "double_down" button will be disabled from then on until the game has ended, but I can not figure out how to do it.
I would also like for the "double_down" button to be disabled by default if the player's 2 starting cards do not add up to 9, 10 or 11.
I tried creating a function to evaluate the list player_hand and return true or false then use that value to define the disabled parameter for my button but that did not work out.

class BlackjackButtonHandler(discord.ui.View):
    def __init__(self, ctx: discord.Interaction, player_hand, dealer_hand, deck):
        super().__init__()
        self.ctx = ctx
        self.player_hand = player_hand
        self.dealer_hand = dealer_hand
        self.deck = deck

    @discord.ui.button(label='Draw', emoji=bj_draw, style=discord.ButtonStyle.green)
    async def draw(self, interaction: discord.Interaction, button: discord.ui.Button):
        # my code here

    @discord.ui.button(label='Double Down', emoji=bj_dd, style=discord.ButtonStyle.blurple)
    async def double_down(self, interaction: discord.Interaction, button: discord.ui.Button):
        # more code here

(I omitted most of the irrelevant code)

Please can somebody help me figure it out and thanks in advance (i am using discord.py 2.0.1)

#
import discord
import random


TOKEN = 'My Token'
intents = discord.Intents.all()

bot = commands.Bot(command_prefix='!', intents=intents)
@bot.event
async def on_ready():
  print('We have logged in as {0.user}'.format(bot))

@bot.command()
async def displayembed(ctx):
  embed = discord.Embed(
   title = "Title",
   description = "Description",
   colour = discord.Colour.blue()
  )
  embed.set_footer(text="Footer")
  embed.set_author("Bread")
  await ctx.send(embed=embed)

bot.run(TOKEN)
#

it gives me this error

#

how do I fix it

#

I was trying to make a simple embed since I'm new to coding a bot

supple thorn
supple thorn
slate swan
#

!embed

#

is that wrong?

supple thorn
#

what you name the function is the command's name

#

well for now but you'll learn how to not make the function name the command name

supple thorn
slate swan
#

need help by making it change the embed on the first part of the /help command aka dropdown menu

async def self(interaction: discord.Interaction):
  class SelectView(View):
    @discord.ui.select(options=[
      discord.SelectOption(label="roblox", value="roblox", description="roblox commands"),
      discord.SelectOption(label="social", value="social", description="social command"),
    ])
    async def select(self, interaction, select):
      if select.values[0] == 'roblox':
        em = discord.Embed(color=0x00ff00)
        em.add_field(name='roblox', value='roblox commands')
        await interaction.response.send_message(embed=em)
      if select.values[0] == 'social':
        em = discord.Embed(color=0x00ff00)
        em.add_field(name='social', value='social commands')
        await interaction.response.send_message(embed=em)
  view = SelectView()
  await interaction.response.send_message('help command', view=view)```im trying to make it change the first text and make it change to a embed after select a dropdown
slate swan
#

what is the issue here?

#

I used !displayembed and this error came up

supple thorn
slate swan
#

try to do

embed.set_author(name="Bread")
#

oh

supple thorn
slate swan
#

Oh

supple thorn
#

if you check the docs the parameters has a * in it

#

meaning any parameters after is a kwarg

slate swan
#

I see

#

It finally worked

#
async def displayembed(ctx):
  embed = discord.Embed(
   title = "Title",
   description = "Description",
   colour = discord.Colour.blue()
  )
  embed.set_footer(text="Footer")
  embed.set_author(name="Bread")
  await ctx.send(embed=embed)```
how would I go about turning this command into a cog in a separate sub-folder?
supple thorn
#

how did you jump that far from being new to cogs

slate swan
#

which version of discord.py are you using, it's different in different versions i think

#

3.11

supple thorn
alpine cove
#

bruh

slate swan
slate swan
#

how often are we allowed to repost problems here btw

#

if we dont manage to get help the first time

#

2.0.1

supple thorn
#

you'll have a better luck a random person will see the help channel rather than scrolling up here

slate swan
#

okay thanks

#

so how would I go about making cogs for discord.py 2.0.1? Just want my commands to be organized in separate folders but still linked to the main file

supple thorn
#

can you install disnake with 3.11?

#

seems like some libraries aren't supporting 3.11 yet

#

cause this should definitely be greater than 14.0

gaunt agate
#

how can i make my discord bot send a message in general when it goes online

south coyote
#

message.channel.send

gaunt agate
#

but in what function

south coyote
#
@client.event
async def on_ready(message):
    print(f'We have logged in as {client.user}')
    await message.channel.send("Here's Johnny!")

gaunt agate
#

but it doesnt know what message is

south coyote
#

my bad

gaunt agate
#

yh

south coyote
#

my bad

gaunt agate
#

how do you do it then?

south coyote
#
@client.event
async def on_ready(message):
    print(f'We have logged in as {client.user}')
    await message.channel.send("Here's Johnny!")
gaunt agate
#

doesnt work

#

@supple thorn do you know how to do it?

south coyote
#

put message in the parentheses

gaunt agate
#

i need to send it to the channel

south coyote
#

hmmm

#
if message.channel.id == <channel id>
gaunt agate
#

i got it to work

south coyote
#

doesn't that work?

#

like i said?

gaunt agate
#

yh

supple thorn
gaunt agate
#

like this

south coyote
#

cool

supple thorn
#

useless f-string

#

it's just a string with no variables needed

south coyote
#

true

gaunt agate
south coyote
#

thanks for sharing man that was helpful

primal token
south coyote
#

im gonna try it

gaunt agate
supple thorn
#

just not

#

recommended

primal token
#

Thats odd how the channel object would be in cache on startup

south coyote
#
@client.event
async def on_ready(message):
    print(f'We have logged in as {client.user}')
    channel = channel.get_channel("XXXXXXXXXXXXXXX")
    await message.channel.send("Who's got some weed?")
#

that's supposed to work?

gaunt agate
#

no

south coyote
#

why

sick birch
#

IDs can't be strings

south coyote
#

i did that for sharing purposes

obtuse blaze
#

I'm using Ubuntu VM machine to host bot and SQlite ATM. To which SQL should I change to that would be compatible with Ubuntu? cause SQlite has been giving a lot of problems

supple thorn
#

nice to see you again

sick birch
#

fancy seeing you around
how are things with you?

supple thorn
#

now i can't install disnake on 3.11

sick birch
#

i'm pretty sure most of the libraries are still working on getting to 3.11

supple thorn
#

yeah

#

i might have to get 3.10 again

#

just to do this

primal token
#

Just use poetry

hushed galleon
sick birch
#

is 311 on arch repos yet

hushed galleon
#

frozenlist, yarl, and multidict, which are dependencies of aiohttp, are missing prebuilt wheels for 3.11

hushed galleon
#

yeah, pretty sure you can untoggle the windows sdk on the right side of that build tools installer to save a couple GB

supple thorn
#

this definitely gonna take hours

supple thorn
hushed galleon
#

nah

supple thorn
#

i'm deleting this shit after

#

also did any big differences happen when i was away

hushed galleon
#

not that i know of

supple thorn
fluid shadow
#
guild = await client.fetch_guild(1026213629172924446)
role = await guild.fetch_roles()
role = discord.utils.find(lambda r: r.id == 1035377754201399307, role)
# role.members -> []

why does this return an empty list, I have members intent on

hushed galleon
#

fetch_guild wont include members with it

fluid shadow
hushed galleon
#

get the guild object that's cached by your bot using Client.get_guild(...)

#

that one will be populated with members through the gateway connection

fluid shadow
#

Thank you!

supple thorn
hushed galleon
#

i guess you might actually need all 6 gigabytes to install disnake

supple thorn
#

bruh

hushed galleon
#

lol my bad

primal token
#

Why not just use poetry and 3.10👽

supple thorn
primal token
#

Why?!??

sick birch
#
name = client.get_guild(id).name

where client is a discord.Client instance of commands.Bot instance

supple thorn
#

i need to somehow remind myself to get rid of this shit after they add support for 3.11

hushed galleon
#

you sure you dont want to keep the build tools? python's got more where that came from

supple thorn
#

depends if i remember when they support 3.11

supple thorn
#
ValueError: mutable default <class 'disnake.utils._MissingSentinel'> for field name is not allowed: use default_factory
#

i'm assuming this is because of 3.11

slate swan
#

for some reason it says undefined

#

but I put in the cog name correctly

obtuse blaze
#

how can I start an async fuction inside __init__? create_task doesn't work since its a ui.Select Class

supple thorn
slate swan
#

thought a cog could do that

vocal snow
vocal snow
#

You can consider using discord.py's extensions which will allow you to hot load/unload python modules and you can add cogs in those modules

mossy jacinth
#

someone explain please?

slate swan
#

If it's a slash command.

#

nah its response

#

the error is referring to your view itself tho

#

can u show code for the view? @mossy jacinth

slate swan
slate swan
slate swan
#

loooli pycord uses ctx in slash cmds too

hollow agate
#

pycord is quite literally garbage

paper sluice
#

pygarbage

slate swan
#

trashcord

slate swan
#

but yes pycord smells

slate swan
#

you just gotta do ctx.send_modal and it returns ctx.interaction.response.send_modal

#

bro what the fuck

#

why lmfaooooooooooo

#

we don't hate pycord for no reason

#

wow. thats next level right there

pulsar bridge
#

Anyone got a place with examples / detailed explanation of the @ error thing?
I read the docs but I’m too dumb to understand how to use it derp

#

!d discord.ext.commands.Command.error
Is the docs location of it

unkempt canyonBOT
#

@error```
A decorator that registers a coroutine as a local error handler.

A local error handler is an [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") event limited to a single command. However, the [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") is still invoked afterwards as the catch-all.

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

same thing but command sepcific

pulsar bridge
#

Aight, lemme check it out

slate swan
#

how can we format one liner for loops, like in the code below:

llist_embed.add_field(name='Activated Licenses', value='\n'.join([n for n in alic]))

i want to bold each element in the list but idk how to, i dont want to use it in the value directly coz then the format will apply to all items in the list except for the last one

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.

slate swan
#

why is it not keeping the tickets button online

#

"In order to keep views persistent, all their items need to have a custom id and a timeout of None"

#

can you make your bot start another bot?

slate swan
slate swan
#

Oh i dont hsve yet

slate swan
#

it is possible?

#

yes but not suggested

slate swan
#

hi

#

how i make my bot only be used by a role?

naive briar
#

!d discord.ext.commands.has_role

unkempt canyonBOT
#

@discord.ext.commands.has_role(item)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member invoking the command has the role specified via the name or ID specified.

If a string is specified, you must give the exact name of the role, including caps and spelling.

If an integer is specified, you must give the exact snowflake ID of the role.

If the message is invoked in a private message context then the check will return `False`.

This check raises one of two special exceptions, [`MissingRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") if the user is missing a role, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").

Changed in version 1.1: Raise [`MissingRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") instead of generic [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")...
slate swan
naive briar
slate swan
#

in a command

naive briar
#

It's an decorator

slate swan
slate swan
naive briar
#

You did not define botperms

slate swan
naive briar
#

Set the item argument to either the role's name or its ID

slate swan
#

ok

obtuse blaze
#

How can I make that when sometimes a moderators name it sends them a dm with the message and timestamp of that message?

#

like this? ThonkSpin

split forge
#

How I canFix this

#

Im trying / commands and embed

slate swan
#

without looking at ur code we cant help u with that

#

u should check if something is in the wrong place (maybe just 3 spaces or so)

slate swan
split forge
#

wait

#

can you come dm?

slate swan
#

reaction is a class, u need the amount atribute

#

wait a min, i'll search in the docs

obtuse blaze
#
    async def on_message(self,message):```


How can I send a dm to a user with their id (I get id from DB) and send it on this event?
slate swan
#

reaction.count >= starData

vale wing
obtuse blaze
#

tysm

slate swan
#

no

#

reaction.emoji is the name (str)

#

reaction.count is the count (int)

#

starData is the number of stars needed ig, but in ur case its type str

#

whats starData ?

#

yeah, but whats the value?

#

yes

#

print(type(data[0], data[0])

#

was sagt dir das?

#

what does that tells u

#

sry, switched to german for a sec xD

gaunt agate
#

how do i crash a discord bot within the code?

slate swan
#

so, what do u have to do, if reaction.count is an int?

#

and u want to compare both

gaunt agate
ionic edge
#

Is your code copy pasted?

ionic edge
#

or new to python?

#

Seems like

#

Yes, i thought you might me knowing about python but i guess you are a newbie like me lol

slate swan
#

np

obtuse blaze
#

is there a way to make sub options on a slash command?

slate swan
#

what's a sub option?

obtuse blaze
#

ok let me explain so its easier to understand im rly bad at explaning XD

#

take this for example, when user chooses Level it will show another options

#

depending on first choice

shrewd apex
#

wdym other options its only one argument

winged coral
#

Either list all possible arguments on that arg or make 2 more optional args that are used or not depending on the first choice

#

There's no way to make decisions based on the first choice until the command is actually sent

mild pilot
#

Hello guys, is there a "test bot" you can invite to check if your bots functions works? I know there was 2 years ago, i just cant find it anymore 😦

faint mural
#

Just write tests

mild pilot
#

Will try look it up

mild pilot
slate swan
mild pilot
#

like you could invite "FishBot" on quakenet

slate swan
#

i personally just dispatch my own events manually

shrewd apex
#

slash?

slate swan
#

if you want them to hide from normal users ( wont include owners and admins ) you can just turn it off from the server settings

#

yes it can definitely be done through a bot, ill let you know about the method and required perms
gimme a moment

shrewd apex
#

isnt there a check for app_commands?

slate swan
shrewd apex
#

!d discord.app_commands.guilds

unkempt canyonBOT
#

@discord.app_commands.guilds(*guild_ids)```
Associates the given guilds with the command.

When the command instance is added to a [`CommandTree`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree "discord.app_commands.CommandTree"), the guilds that are specified by this decorator become the default guilds that it’s added to rather than being a global command.

Note

Due to an implementation quirk and Python limitation, if this is used in conjunction with the [`CommandTree.command()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree.command "discord.app_commands.CommandTree.command") or [`CommandTree.context_menu()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree.context_menu "discord.app_commands.CommandTree.context_menu") decorator then this must go below that decorator.

Example...
shrewd apex
#

can be added as a deco

slate swan
#

lol wtf

snow pulsar
#

Help!
Can i login discord as an end user, not as a bot ?

#

Yes. that right.

#

Oh :(. Thank for answer.

rugged shadow
#

i'm getting back to Discord bots, what library should I use now?

paper sluice
#

hikari

rugged shadow
#

hiuikai?

#

ok

paper sluice
mighty pilot
#

Is there a way to specify how many characters can be put into a slash command option

mighty pilot
#

dpy

glad cradle
#

I use disnake so idk

mighty pilot
#

do you know how its done on disnake

slate swan
#

what's the hex for the default embed color discord.py sends?

#

in the docs it says 0, but 0 is meant for solid black

#

!d discord.Colour.default

unkempt canyonBOT
#

classmethod default()```
A factory method that returns a [`Colour`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Colour "discord.Colour") with a value of `0`.
mighty pilot
#

that would be the hex for the interger 0

#

a quick google tells me #23272A is the 'official discord color palette black'

slate swan
mighty pilot
slate swan
#

tried 0

#

yeah the second one works

mighty pilot
#

sweet

slate swan
#

ty

mighty pilot
#

np

onyx lark
#

does sombody make bot for free pls DM me

#

i need you if you do

mighty pilot
onyx lark
#

😄

mighty pilot
#

thats a lot of work. good luck in your search.

onyx lark
#

thx mate

slate swan
#

will using two different databases throughout my bot cause any performance issues or anything i'm not aware of? One being a large mongo database and the other being a large postgre database

mossy jacinth
#

any possible way to stop the example link at the ")!"?
So that the )! is in a normal white color?

mighty pilot
#

use "('https://......png')!" maybe

slate swan
#

can someone help me w making the buttons always work? everytime i run the bot twice the buttons are not working same w select menus, how do i make it work everytime?

glad cradle
#

!d disnake.ext.commands.Param

unkempt canyonBOT
#
disnake.ext.commands.Param(default=Ellipsis, *, name=None, description=None, choices=None, converter=None, convert_defaults=False, autocomplete=None, channel_types=None, lt=None, ...)```
A special function that creates an instance of [`ParamInfo`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.ParamInfo "disnake.ext.commands.ParamInfo") that contains some information about a slash command option. This instance should be assigned to a parameter of a function representing your slash command.

See [Parameters](https://docs.disnake.dev/en/latest/ext/commands/slash_commands.html#param-syntax) for more info.
glad cradle
#

see min_lenght and max_lenght

glad cradle
glad cradle
shrewd apex
#

i see no point of having two different type of database storage system just for storing data

#

unless u are using one for like cache and other for storage or something

primal token
#

It would be better to have one database with 2 tables to make things easier implementing

vale wing
#

Ofc

slate swan
slate swan
shrewd apex
primal token
slate swan
#

mongo connections are usually cheap

shrewd apex
#

^^

slate swan
#

discord.py is async while mongodb motors wrapper is pymongo thrown in executor

shrewd apex
slate swan
#

it blocks dpy after thousands of fetches

shrewd apex
#

🗿

#

!pypi motor

unkempt canyonBOT
slate swan
mossy jacinth
#

Hey how can i check if the value of self.name2.value is in a list and if not send a message? I know the code is messy and i repeat myself, I tried using a dict but failed miserably...

slate swan
primal token
slate swan
#

can someone help me w making the buttons always work? everytime i run the bot twice the buttons are not working same w select menus, how do i make it work everytime?

zealous jay
#

Do these events work with slash commands?

#

found this

#

but I don't see anything on the console

slate swan
#

yeah you just gotta add add between them

slate swan
onyx lark
zealous jay
# slate swan code ?
# DISCORD
import discord
from discord.ext import commands


class Logs(commands.Cog):
    def __init__(self, client: commands.Bot) -> None:
        self.client = client


    @commands.Cog.listener()
    async def on_app_command_completion(
        self, interaction: discord.Interaction, command: discord.app_commands.Command
    ):
        print("REGISTRADO")


async def setup(client: commands.Bot) -> None:
    await client.add_cog(Logs(client))
    print(f"Module logs.py was loaded succesfully.")
slate swan
#

AttributeError: 'Bot' object has no attribute 'listener'

#

@bot.listener()

#

did that instead of @commands.Cog.listener()

#

but i dont have cogs then what do i do

zealous jay
#

are you using commands.Bot or discord.Client?

slate swan
#

commands.Bot

zealous jay
#

wasn't it bot.listen()?

slate swan
#

ill try

shrewd crow
#

can you even create discord bot in python btw?

paper sluice
#

you can

shrewd crow
paper sluice
#

you can create one in any language which is capable of making web requests

glad cradle
#

you can build a discord Bot in assembly too

shrewd crow
glad cradle
#

the programming language closest to the machine language

shrewd crow
#

btw i never figured out what's the difference between the high level programming language and object oriented programming language

#

i have heard python is object oriented

#

or both

#

?

sick birch
shrewd crow
sick birch
#

You could also argue python isn't object-oriented

#

It's also high level

shrewd crow
#

oh

sick birch
#

Rust, is also not object-oriented and is high level (to a definition of high level)

shrewd crow
glad cradle
#

python is pretty special

sick birch
#

Python gives you the option of using objects or not

#

You can do functional programming in Python if your heart desires so

shrewd crow
#

like what does objected oriented and high level means?

sick birch
#

Java

#

Object oriented and high level

shrewd crow
#

👀

sick birch
#

You probably want to take apart and define "object oriented" and "high level"
"object oriented" - any language that supports typical implementation details of object orientation, such as classes, objects, inheritance, polymorphism, etc
"high level" - how far away from the CPU it is, not in terms of physical distance, but that of abstraction layers

paper sluice
sick birch
#

Having both, a language can be deemed to be "object oriented" and "high level"

sick birch
#

Examples of high level - Java, Python, Rust, JS/TS
Examples of low level - C, Rust, Zig, Assembly, etc

primal token
#

A high level language is basically a language with allot of abstractions

#

Abstractions meaning features a user can use and other internal features

slate swan
#

and automatic memory management ofc

#
import discord
from discord.ext import commands 
import sqlite3
import random

class Event(commands.Cog):

    def _init_(self,bot):
        self.bot=bot

    @commands.Cog.listener()
    async def on_ready(self):
        db = sqlite3.connect("main.sqlite")
        cursor = db.cursor()
        cursor.execute('''CREATE TABLE IS NOT EXISTS main (
            user_id INTERGER, wallet INTERGER, bank INTERGER
        )''')
        print("BOT IS ONLINE")

    @commands.Cog.listener()
    async def on_message(self, message):
        if message.author.bot:
            return
        
        author = message.author
        db = sqlite3.connect("main.sqlite") 
        cursor = db.cursor()
        cursor.execute ("SELECT user_id From main Where user_id is = (author.id)")
        result = cursor.fetchone() 
        if result is None:
            sql = ("INSERT INTO main(user_id, wallet, bank) VALUES ?, ?, ?")
            val = ("author.id 100,10")
            cursor.execute(sql, val) 
        db . commit() 
        cursor.close()
        db.close()```
This is what I have in the other folder but for some reason it says it can't import it
#

Really can't find the issue as to why it won't import

primal token
#

Why dont you just use the async function named setup?

slate swan
#

how do I go about using that function?

whole sparrow
#

Guys, how do I add a spaceb etween title and description

primal token
slate swan
#

guys

#

can someonehelp me w making cogs

primal token
slate swan
#

Ok gotta

#

my discord bot wont pop up in integrations, but its in the server. Any idea why?

ripe blaze
#

when using select/buttons - the buttons/selections dont work after I restart the bot.
is there a way to work around this?

slate swan
#

im trying to get help for it too

sick birch
#

see an example for making views persistent

slate swan
#

and it still doesnt work

#

what do u mean sync?

sick birch
sick birch
#

if you don't everything stays on your computer

slate swan
#

ah, never knew this

#

how do I do this

unkempt canyonBOT
#

examples/app_commands/basic.py lines 25 to 28

async def setup_hook(self):
    # This copies the global commands over to your guild.
    self.tree.copy_global_to(guild=MY_GUILD)
    await self.tree.sync(guild=MY_GUILD)```
slate swan
#

It works in another server, a test server. Just not the server the bot is gonna be utilized in

#

Hello, I have made a blackjack game for my bot using discord.py 2.0.1. The bot uses buttons that the user can press to choose whether they want to draw, stand or double down. I also created a timeout function that disables the buttons and effectively ends the game if too much time has passed without any user input.

Everything works as intended and the game itself runs perfectly fine, however I am running into an issue where the on_timeout function will still be called some time after the player has ended their game and I am looking for a way to 'cancel' the timeout after the game has ended.

here is my relevant code:

class BlackjackButtonHandler(discord.ui.View):
    def __init__(self, ctx: discord.Interaction, player_hand, dealer_hand, deck, bet):
        super().__init__(timeout=3) # placeholder value
        self.ctx = ctx
        self.player_hand = player_hand
        self.dealer_hand = dealer_hand
        self.deck = deck
        self.bet = bet
        self.update()

    @discord.ui.button(label='Draw', emoji=bj_draw, style=discord.ButtonStyle.green)
    async def draw(self, interaction: discord.Interaction, button: discord.Button):

        deal_card(self.player_hand, self.deck)

        embed_updated = embed_new(interaction, self.player_hand)

        elif determine_total(self.player_hand) > 21:

            embed_add_field_dealer_unknown(embed_updated, self.dealer_hand)
            embed_updated.add_field(name='Loser!',
                                    value='😢 You went bust, better luck next time!',
                                    inline=False)

            await interaction.message.edit(embed=embed_updated, view=None)

        # Game would 'end' here because the player went above 21, so the buttons will disappear and the timeout should be cancelled

    async def on_timeout(self):

        embed_timeout = embed_new(self.ctx, self.player_hand)
        embed_add_field_dealer_unknown(embed_timeout, self.dealer_hand)
        embed_timeout.add_field(name='Timed out!',
                                    value='🕑 You ran out of time!',
                                    inline=False)

        self.draw.disabled = True
        self.stand.disabled = True
        self.double_down.disabled = True

        await self.ctx.edit_original_response(embed=embed_timeout, view=self)

If anybody can help me figure this out it'd be much appreciated and thank you in advance.

sick birch
slate swan
# sick birch then you mustn't have done it right :p
class PersistentView(discord.ui.View):
    def __init__(self):
        super().__init__(timeout=None)

    @discord.ui.button(label='Green', style=discord.ButtonStyle.green, custom_id='persistent_view:green')
    async def green(self, interaction: discord.Interaction, button: discord.ui.Button):
        await interaction.response.send_message('This is green.', ephemeral=True)

    @discord.ui.button(label='Red', style=discord.ButtonStyle.red, custom_id='persistent_view:red')
    async def red(self, interaction: discord.Interaction, button: discord.ui.Button):
        await interaction.response.send_message('This is red.', ephemeral=True)

    @discord.ui.button(label='Grey', style=discord.ButtonStyle.grey, custom_id='persistent_view:grey')
    async def grey(self, interaction: discord.Interaction, button: discord.ui.Button):
        await interaction.response.send_message('This is grey.', ephemeral=True)


class PersistentViewBot(commands.Bot):
    def __init__(self):
        intents = discord.Intents.default()
        intents.message_content = True

        super().__init__(command_prefix=commands.when_mentioned_or('$'), intents=intents)

    async def setup_hook(self) -> None:
        self.add_view(PersistentView())

    async def on_ready(self):
        print(f'Logged in as {self.user} (ID: {self.user.id})')
        print('------')


bot = PersistentViewBot()


@bot.command()
async def prepare(ctx):
    await ctx.send("What's your favourite colour?", view=PersistentView())```
tried her code and it doesnt show it
sick birch
#

Probably not but worth putting a print statement in there

slate swan
slate swan
# sick birch Is there another button you can use to end the game?

I created 3 buttons for 'draw', 'stand' and 'double down'. The bot automatically detects when certain criteria have been met for the game to end and plays it out accordingly, so the user doesn't have to click a button to end the game themselves.

I'm looking for a way to explicitly stop the timeout from elapsing when these certain criteria have met (such as the player going 'bust' and getting above 21 points)

sick birch
sick birch
#

I meant something like

class PersistentViewBot(commands.Bot):
  ...
  async def setup_hook(self) -> None:
    print("Setup hook called")
    self.add_view(PersistentView())
slate swan
slate swan
#

So my bot wont show up in my integrations page in my server. why?

#

how can i use a space between a slash command name

ripe blaze
mighty pilot
slate swan
slate swan
slate swan
rare echo
sick birch
mighty pilot
#

well i guess the only way youd bust is on a draw...

mighty pilot
#

im not 100% sure what the -> does yet tbh i havent read up on it

deft hill
#

I have a ton of scammers in a server I am a staff in. They go by the name sᴛʀɪᴋᴇ ɪᴛ ʙɪɢ or 𝗦𝘁𝗿𝗶𝗸𝗲 𝗜𝘁 𝗕𝗶𝗴. They are different fonts/language characters. Anyway to search all common fonts and languages for characters that resemble Strike It Big? I currently have some basic code that catches the newbs of the scamming world:

    if member.name.lower() == 'strike it big':
        await member.ban(reason='Impersonating Mark - Custom Bot Auto Ban')
        print('Banned a wild SIB impersonator!')
        embed = discord.Embed(
        title=":sparkles: Impersonator Banned :sparkles:", description=f"A member by the name of 'Strike It Big' joined the server and was instantly banned by our auto-detection service! \nUser Name: {member} \nUser ID: {member.id}", color=0x336EFF
                )
        await channel.send(embed=embed)
    if member.name.lower() == 'strikeitbig':
        await member.ban(reason='Impersonating Mark - Custom Bot Auto Ban')
        print('Banned a wild SIB impersonator!')
        embed = discord.Embed(
        title=":sparkles: Impersonator Banned :sparkles:", description=f"A member by the name of 'Strike It Big' joined the server and was instantly banned by our auto-detection service! \nUser Name: {member} \nUser ID: {member.id}", color=0x336EFF
                )
        await channel.send(embed=embed)

This is ran on_member_join.

slate swan
#

I put self.stop() as the very first line of code within the 'stand' and 'double down' buttons and they work, I don't get timed out after standing or doubling down

still getting timed out after going bust or landing on 21 after drawing though

update: i'm getting timed out after going bust or standing like 50% of the time

#

@mighty pilot (sorry forgot to click reply)

#

So my bot wont show up in my integrations page in my server. why?

glad cradle
slate swan
#

yes

glad cradle
#

the integrations page currently shows only the first 50 Bots

slate swan
#

so then?

glad cradle
#

remove some bots

slate swan
#

can I not manage the b ot