#discord-bots

1 messages · Page 179 of 1

naive briar
#

Is that all

loud junco
#

im so confused

#

rip

heady verge
#

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

vale wing
#

!d discord.ext.commands.Bot.hybrid_command

unkempt canyonBOT
#

@hybrid_command(name=..., with_app_command=True, *args, **kwargs)```
A shortcut decorator that invokes [`hybrid_command()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.hybrid_command "discord.ext.commands.hybrid_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.Bot.add_command "discord.ext.commands.Bot.add_command").
heady verge
#

pycord

vale wing
#

It simply doesn't exist

#

Does it in disnake

heady verge
#

so its not possible to use hybrid cmds?

vale wing
#

Too bad

vale wing
heady verge
#

hmm, okay ty

slate swan
#

why i cant import app_commands?

#

I did pip install -U discord

slate swan
#

alrdy installed

maiden fable
#

pip uninstall discord

slate swan
naive briar
slate swan
maiden fable
#

remove discord

naive briar
unkempt canyonBOT
maiden fable
slate swan
#

ok done

#

i still cant import app_commands

#

anyone knows why?

timid spade
#

is there any way (other than the boosting role one) to check if a member is boosting the server or not?

slate swan
naive briar
unkempt canyonBOT
#

An aware datetime object that specifies the date and time in UTC when the member used their “Nitro boost” on the guild, if available. This could be None.

timid spade
#

also
this is soo much pain
how to test this thing, i dont wanna boost and unboost like a million times

naive briar
#

Read the embed, that's the answer

timid spade
#

This could be None
could be..
when member is not boosting?

static holly
#

hi!

#

i need help please ^^

#

for a image in embed

naive briar
#

Just ask it

lyric sphinx
#

discord.py doesnt automatically convert member argument of the function to a member object, no?

#

try to implement a kick by id thing first

#
@client.command()
async def kick(ctx):
  user = ctx.guild.get_member(<user id>)
  await user.kick(reason=None)
lyric sphinx
#

also you can try

member: commands.MemberConverter
#

instead of member: discord.Member

#

(you need to from discord.ext import commands first)

#

also why would you even do this

async def kick(ctx, member:discord.Member, reason=None):
    if reason == None:
        reason='No reason given'
#

just do reason='No reason given', no?

#

why would you make your bot's code obfuscated?

#

you dont apply esoteric stuff to something like bot's code if it doesnt help you 🤷

#

how is setting a default string value for a function argument less readable than setting it to None and then having an if statement

terse cloud
#

my bot dont send server messages but private he send

lyric sphinx
#

yeah sure let me use

euler = lambda steps: __builtins__.sum([(0^1 & (0 | 1))/(__import__(name=(__import__('base64').b64decode("bWF0aA==").decode('utf-8'))).factorial(_)) for _ in __builtins__.iter(__builtins__.range(steps))])

instead of a mathematical constant

#

no, its just the fact that i dont know how to do funky code

mental hollow
terse cloud
#
from discord.ext import commands


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


@bot.command()
async def ping(ctx):
    await ctx.send("lol xd bruh nice")

@bot.event
async def on_ready():
    await bot.change_presence(
        activity=discord.Streaming(name="Play in the Code", url=""))
    print('Bot is Online')

bot.run("+++++++++++++")```
naive briar
#

If you type hint it in the command parameters/arguments

lyric sphinx
#

!e

exec(dir(__builtins__)[dir(__builtins__).index('print')]+'("idk")')
unkempt canyonBOT
#

@lyric sphinx :white_check_mark: Your 3.11 eval job has completed with return code 0.

idk
naive briar
#

Ew, exec

lyric sphinx
lyric sphinx
slate swan
#

you can but that won't be the correct typehint for your type checker and language server

#

eval

lyric sphinx
slate swan
#

kinda, yeah
but eval isn't capable of performing imports and stuff iirc

naive briar
unkempt canyonBOT
#

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

meow
lyric sphinx
slate swan
#

!e ```py
eval("import this")

unkempt canyonBOT
#

@slate swan :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 |   File "<string>", line 1
004 |     import this
005 |     ^^^^^^
006 | SyntaxError: invalid syntax
naive briar
#

If you don't count getattr then I guess

slate swan
lyric sphinx
#

!e

eval(__import__('this'))
unkempt canyonBOT
#

@lyric sphinx :x: Your 3.11 eval job has completed with return code 1.

001 | The Zen of Python, by Tim Peters
002 | 
003 | Beautiful is better than ugly.
004 | Explicit is better than implicit.
005 | Simple is better than complex.
006 | Complex is better than complicated.
007 | Flat is better than nested.
008 | Sparse is better than dense.
009 | Readability counts.
010 | Special cases aren't special enough to break the rules.
011 | Although practicality beats purity.
... (truncated - too many lines)

Full output: https://paste.pythondiscord.com/apupuyafop.txt?noredirect

lyric sphinx
slate swan
#

isnt it a part of globals too lol

lyric sphinx
#

!e

getattr(__builtins__, dir(__builtins__)[dir(__builtins__).index('print')])("test")
unkempt canyonBOT
#

@lyric sphinx :white_check_mark: Your 3.11 eval job has completed with return code 0.

test
slate swan
#

!e globals()["print"]

naive briar
#

🤷

slate swan
#

its not sad

lyric sphinx
#

yeah true

terse cloud
#

how can i made a slash menu?

#

how can i make a slash menu?

naive briar
#

Pins

slate swan
#

what's a slash menu 🤔

heady coyote
#
async def roles(interaction: discord.Interaction):

    select = Select(options= [
        discord.SelectOption(label="Quant",emoji="🦴",description="The great programming language"),
        discord.SelectOption(label="Bitcoin",emoji="🦴",description="Nice programming language"),
        discord.SelectOption(label="Etherum",emoji="🦴",description="Nice programming language"),
        discord.SelectOption(label="Solana",emoji="🦴",description="Nice programming language")

        
        ])

    view = View()
    view.add_item(select)
    await interaction.response.send_message("role bar: ", view=view)

how do i append role when sb chooses for example quant?

heady coyote
#

thx

patent dome
#

whats the error

slate swan
#

the code is correct, and you didnt send what the error is

patent dome
#

wait..

naive briar
#

Genius

patent dome
#

sry

#

raise PrivilegedIntentsRequired(exc.shard_id) from None
discord.errors.PrivilegedIntentsRequired: Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.

Discord Developer Portal

Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.

slate swan
#

did you try reading it

terse cloud
#

How can i made a description?

#
async def esport(ctx):
    await ctx.respond("Test")```
slate swan
#

description = "ur description" in the slash_command decorator

slate swan
heady coyote
#

doesnt help me

slate swan
slate swan
naive briar
#

He just told you how

terse cloud
#

Please

terse cloud
terse cloud
slate swan
slate swan
terse cloud
slate swan
terse cloud
static holly
#

is there a solution to avoid falling several times on the same image with random.choice(image)?

#

i have 20 images*

quick gust
#

maybe remove the image from the list?

slate swan
#

the random module isnt really that random lol

#

!d secrets.choice

unkempt canyonBOT
#

secrets.choice(sequence)```
Return a randomly chosen element from a non-empty sequence.
static holly
slate swan
#

ow

#

wait fk

#

#bot-commands message
the results are repetative

static holly
#

@slate swan what is the difference with random.choice and sercet.choice?

slate swan
#

and so is the .choice func

heady coyote
#

@slate swan can i add role by interaction.user.add_role()?

young dagger
#

How can I improve the performance of this code to retrieve data from the database more quickly?

        summoner = collection.find_one({"discord_id": member.id})
        if summoner:
            summoner_id = summoner.get("summoner_id")
            summoner_name = get_summoner_name(summoner_id, RIOT_API_KEY)
            tier = summoner.get("tier")
            rank = summoner.get("rank")
            elo = summoner.get("elo_rating")
            users.append({"member": member, "summoner_name": summoner_name, "tier": tier, "rank": rank, "elo_rating": elo})```
static holly
slate swan
slate swan
unkempt canyonBOT
#

random.sample(population, k, *, counts=None)```
Return a *k* length list of unique elements chosen from the population sequence. Used for random sampling without replacement.

Returns a new list containing elements from the population while leaving the original population unchanged. The resulting list is in selection order so that all sub-slices will also be valid random samples. This allows raffle winners (the sample) to be partitioned into grand prize and second place winners (the subslices).

Members of the population need not be [hashable](https://docs.python.org/3/glossary.html#term-hashable) or unique. If the population contains repeats, then each occurrence is a possible selection in the sample.
heady coyote
#

cuz doesnt work

lyric sphinx
#

Any disnake users here?

        @bot.slash_command(name='test', description='description')
        async def test(inter):
            embed = disnake.Embed(
                title="Embed Title",
                description="Embed Description",
                color=disnake.Colour.yellow(),
                url="https://disnake.dev/",
                timestamp=datetime.datetime.now(),
            )

            embed.set_author(
                name="Embed Author",
                url="https://disnake.dev/",
                icon_url="https://disnake.dev/assets/disnake-logo.png",
            )

            embed.set_thumbnail(url="https://disnake.dev/assets/disnake-logo.png")

            embed.set_image(url="https://disnake.dev/assets/disnake-thin-banner.png")

            embed.add_field(name="Regular Title", value="Regular Value", inline=False)

            embed.add_field(name="Inline Title", value="Inline Value", inline=True)
            embed.add_field(name="Inline Title", value="Inline Value", inline=True)
            embed.add_field(name="Inline Title", value="Inline Value", inline=True)

            embed.set_footer(
                text="Embed Footer",
                icon_url="https://disnake.dev/assets/disnake-logo.png",
            )

            await inter.response.send_message(embed=embed)

why does this not work?

naive briar
#

What's the problem

#

it's not working doesn't explain anything

lyric sphinx
#

well there are no errors in the terminal, it just sends an app is not responding error

#

oh, ok, seems like it is an error that happens due to me trying to make the bot controlled both by a terminal and slash commands

lyric sphinx
#

How could i implement a terminal-controlled stuff in my bot without breaking slash commands?

naive briar
#

Threading

lyric sphinx
#

how would i interact with the bot object from 1st thread inside the 2nd thread?

naive briar
#

!e

import threading
import queue

import time

jobs = queue.Queue()


def command_worker():
    while True:
        print("Working on:", jobs.get())


m = threading.Thread(target=command_worker, daemon=True)
m.start()

jobs.put_nowait("sync")

time.sleep(3)

jobs.put_nowait("reload")
time.sleep(0.1)
unkempt canyonBOT
#

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

001 | Working on: sync
002 | Working on: reload
livid hedge
#

Does someone know a free provider for hosting my discord bot?

#

I used heroku but it isn't free anymore

spiral kiln
#

So I have a modal, the modal has 2 textinputs.
This modal is sent when a user clicks a button.
If any of the text inputs are filled in it updates an embed.
I want it so once the textinput has been submitted, it changed the button style of the button it was sent from.

static holly
#

could someone give me the piece of code to add to send an emoji on the embed that my bot sends in the command.
the "await ctx.message.add_reaction("\U0001F60E)" command sends an emoji on the message from which the member's command is sent. but I can't assign it to the embed instead

naive briar
#

Store the message that your bot sent then add the reaction to it

static holly
naive briar
#

!d discord.TextChannel.send

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

Sends a message to the destination with the content given.

The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.

To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.

To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
naive briar
#

The method returns the sent message, store it in a variable

daring crypt
#
@bot.event
async def on_member_join(member):
    role = discord.utils.get(member.server.roles, id="1063812548924813397")
    await bot.add_roles(member, role)

is supposed to give members a role upon joining but it just doesnt, no errors nothing

#

just doesnt give it to em

naive briar
#

member.server isn't a thing anymore

#

!d discord.Member.guild

unkempt canyonBOT
static holly
daring crypt
daring crypt
#

im really new to python and discord.py, i just replace member.server with discord.Member right?

naive briar
#

No, member is an instance of discord.Member

#

You should have basic OOP knowledge to be more comfortable with discord.py

daring crypt
#

im not trying to make a fully fledged bot, just one that stays online and gives members a role once they join

static holly
#

idu, sorry

#

is not very clear for me ^^

naive briar
daring crypt
meager chasm
daring crypt
#

but i really dont need it for anything else so i dont see the purpose of learning an entire programming language to create 1 feature

meager chasm
#

good luck finding someone to spoonfedd you then

daring crypt
#

i dont want someone to spoonfeed mee

#

just help me understand this ONE thing

scenic canopy
#

is there any hosts like heroku to host my bot?

daring crypt
scenic canopy
daring crypt
scenic canopy
daring crypt
#

your code will be public

#

but not your token

vale wing
lyric sphinx
#

i was trying to create a command that'd send an embed with latest homework btw, works perfectly now

#

👀 isnt this kinda pog

static holly
#

i tried with ```py
newmsg= await message.channel.send(embed_msg)
await newmsg.add_reaction("\U0001F60E")

same probleme...
thin raft
#

just why

#

<@&831776746206265384>

quick gust
#

wtf

daring crypt
#

man wtf

haughty geyser
#

!tempban 398556306832752642 14d Not sure what that was but it definitely wasn't appropriate for here

unkempt canyonBOT
#

:incoming_envelope: :ok_hand: applied ban to @lucid wadi until <t:1675005746:f> (14 days).

scenic canopy
scenic canopy
vocal snow
#

please send the full traceback

scenic canopy
# vocal snow please send the full traceback
- 
Ignoring exception in command <nextcord.application_command.SlashApplicationCommand object at 0x7f3b859893a0>:
Traceback (most recent call last):
  File "/home/jaiyesh/.local/lib/python3.9/site-packages/nextcord/application_command.py", line 906, in invoke_callback_with_hooks
    await self(interaction, *args, **kwargs)
  File "/home/jaiyesh/development/discord.bot/shadow.py", line 185, in image_gen
    return await msg.edit(content="Content Generated by **craiyon.com**" , file=nextcord.File(image , "image.png") , view = DropdownView(msg , images , interaction.user.id))
  File "/home/jaiyesh/development/discord.bot/shadow.py", line 175, in __init__
    self.add_item(Dropdown(self.message , self.images , self.user))
  File "/home/jaiyesh/development/discord.bot/shadow.py", line 156, in __init__
    super.__init__(
TypeError: descriptor '__init__' of 'super' object needs an argument

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

nextcord.errors.ApplicationInvokeError: Command raised an exception: TypeError: descriptor '__init__' of 'super' object needs an argument
vocal snow
#

super().__init__

#

you need to call super() there

vivid gate
#

Do anyone know how can I get an friend request link?
like an discord server link that you can click to join but click to add friend

scenic canopy
vocal snow
#

super is a class, you need to instantiate it

scenic canopy
vocal snow
young dagger
#
     summoner = collection.find_one({"discord_id": member.id})
        if summoner:
            summoner_id = summoner.get("summoner_id")
            summoner_name = get_summoner_name(summoner_id, RIOT_API_KEY)
            tier = summoner.get("tier")
            rank = summoner.get("rank")
            elo = summoner.get("elo_rating")
            users.append({"member": member, "summoner_name": summoner_name, "tier": tier, "rank": rank, "elo_rating": elo})
        else:
            not_in_database.append(member.mention)```
#

Or should I just keep it as it is?

slate swan
#

Hello everyone

#

how i can fix this?

#

im using slash commands

#

trying to know if the bot is connected to voice chat

outer flint
#

can I have a command that has a space in it? thonkhmm
such as
+string1 string2?

naive briar
slate swan
outer flint
#

can't I have it as it's own command? thonkhmm
obviously with having an on_message_send that check + string1 string

terse cloud
#

hey i need help, how do i get the bot to send me the answer pricvat when i send a message in the server?

#
async def esport(ctx):
    embed = discord.Embed(title="E-Sport", description="gg", color=0xf95757)
    embed.set_thumbnail(url="")
    embed.set_author(name="gg")
    embed.add_field(name="hh", value="hh", inline=False)
    embed.set_footer(text="th")
    embed.set_image(url="")
    await ctx.respond(embed=embed)```
livid hedge
#

Does someone know a free provider for hosting my discord bot?
I used heroku but it isn't free anymore

outer flint
#

nope, I self host it on my laptop lOl

vocal snow
livid hedge
#

thank you Zeffo

slate swan
#

already fixed

slate swan
#

Hello

hardy cloak
#

does ctx still work for yall, for some reason it doesnt for me?

slate swan
#
async def on_message(message):
  if(message.channel.id == '1059977737000992799'):
    
   if(message.content != "!verify"):
      await message.delete()```
#

Why bot isn't responding to anything after i added this to my code

vague jungle
slate swan
vague jungle
#

and is the bot capable of viewing that channel?

slate swan
#

Yes it has administrator perms

vague jungle
#

did you declare youre intents on message content

slate swan
#

..

#

What

vague jungle
#
intents = discord.Intents.default()
intents.message_content = True
bot = discord.Client(intents=intents)

To be able to read message content now requires you to declare your intent

slate swan
#

client = commands.Bot(command_prefix='!', intents=intents)```
#

I did this

#

Mitche

vague jungle
#

oh

#

throw your channel id into a var

slate swan
#

How

#

Like channelid = "id"

vague jungle
#
ID1=1059977737000992799
if(message.channel.id == ID1):```
slate swan
#

Do i need to use ""?

#

I think yes

slate swan
vague jungle
#

just uh.. just copy what I threw for ya?

#

its even youre channel id already but no you do not need quotes

#

and since youre referencing a variable you do not need singles around your var name

#

so just

ID1(your varname) = 1059977737000992799(your channel id)

then if(message.channel.id = ID1(your varname))

slate swan
#

@vague jungle ohh

#

Listen messages delete

#

But !verify command isn't working

vague jungle
slate swan
#
async def verify(ctx):
  await ctx.send('Sent verification info. Please check your DMs.')
  await ctx.author.send(embed=main)
  time.sleep(3)
  await ctx.channel.purge()

@client.event
async def on_message(message):
  if(message.channel.id == ID1):
    
   if(message.content != "!verify"):
      await message.delete()


client.run(os.environ['token'])
keep_alive()```
naive briar
#

!d asyncio.sleep

unkempt canyonBOT
#

coroutine asyncio.sleep(delay, result=None)```
Block for *delay* seconds.

If *result* is provided, it is returned to the caller when the coroutine completes.

`sleep()` always suspends the current task, allowing other tasks to run.

Setting the delay to 0 provides an optimized path to allow other tasks to run. This can be used by long-running functions to avoid blocking the event loop for the full duration of the function call.

Example of coroutine displaying the current date every second for 5 seconds:
vivid gate
#

Do anyone know how can I get an friend request link?
like an discord server link that you can click to join but click to add friend

vocal snow
#

?

slate swan
#

What did u send

naive briar
#

Read the URL link would have told you that

slate swan
#

U think

#

await bot.process_commands(message)

#

This i guess?

#

Idk there is bunch of text that has nothing to do with my problem

vocal snow
#

the link explains how to solve that

slate swan
#

Which part in the link

vocal snow
#

it provides two solutions, you can use any one

slate swan
#

There's alot kf solutions for other problems

vocal snow
slate swan
#

await bot.process_commands(message)
By adding this

#
async def on_message(message):
  if(message.channel.id == ID1):
    
   if(message.content != "!verify"):
      await message.delete()
      await bot.process_commands(message)```
#

Not it

#

Lemme try another one

fair magnet
#

hey i made a web scraper and i wanted to connect itnwith my dc bot any idea how to make it since i dont know how to start

#

just a simple !scrape command and then where i have to input the product info which gets send to my scraper

slate swan
fair magnet
#

so i dont have to go everytime i want to scrape something in my python file yk ?

sick birch
#

If the message is anything but !verify, delete the message and process command

fair magnet
#

how

#

thats my problem

slate swan
sick birch
fair magnet
#

yes

#

go on

cloud dawn
fair magnet
#

Check dm Boss

hollow gazelle
#

from discord_components import SelectOption
ModuleNotFoundError: No module named 'discord_components'

cloud dawn
hollow gazelle
#

how would i do that

gusty flax
cloud dawn
#

use the app_command from discord.

hollow gazelle
#

ik but how do i make the drop down

gusty flax
#

and get SelectOption from discord.SelectOption

gusty flax
hollow gazelle
#

ok

gusty flax
#

@hollow gazelle tho, ur select even when disabled needs to have a selectoption

hollow gazelle
#

ok

slate swan
# sick birch Do you have a command handler?

@client.command()
async def verify(ctx):
await ctx.send('Sent verification info. Please check your DMs.')
await ctx.author.send(embed=main)
time.sleep(3)
await ctx.channel.purge()

#

how to use an emoji as parameter ?

naive galleon
slate swan
#

/ea 🙂

naive galleon
#

You can prolly make emoji as arg but use type hint string instead of .emoji

slate swan
#

it should work tho

#

Emoji had a converter

#

not sure about a transformer

naive galleon
#

Yea

slate swan
#

!d discord.Emoji

unkempt canyonBOT
#

class discord.Emoji```
Represents a custom emoji.

Depending on the way this object was created, some of the attributes can have a value of `None`...
slate swan
slate swan
#

if i use str, i can't save the emoji

slate swan
#

!d discord.app_commands.Transformer

unkempt canyonBOT
#

class discord.app_commands.Transformer```
The base class that allows a type annotation in an application command parameter to map into a [`AppCommandOptionType`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.AppCommandOptionType "discord.AppCommandOptionType") and transform the raw value into one from this type.

This class is customisable through the overriding of methods and properties in the class and by using it as the second type parameter of the [`Transform`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Transform "discord.app_commands.Transform") class. For example, to convert a string into a custom pair type:
slate swan
#
async def on_message(message):
  if(message.channel.id == ID1):
    
   if(message.content != "!verify"):
      await message.delete()
   else:
     async def verify(ctx):
       await ctx.send('Sent verification info. Please check your DMs.')
       await ctx.author.send(embed=main)```
#

Why isn't this working

potent spear
slate swan
#

To delete every message except !verify and !verify is command that sends embedded message in dms

potent spear
slate swan
#

Mhm

#

Maybe

#

I had command written already before but because of on_message event bot didn't want to respond to command

slate swan
#

That didn't actually work

slate swan
#

Exactly what zeffo gave to me

potent spear
potent spear
#

get it out and all will work fine

potent spear
slate swan
#

Hmm how to get it out it still gives error

slate swan
#

is this right ?

potent spear
slate swan
#

I tested it anyways nvm

#

I can't get this out of if statement

shut elk
#

I have a question, if I have a button that when u press it, it sends the same button again and disables the last one, how would I make the new button that is sent to have a new label?

potent spear
slate swan
#
async def on_message(message):
  if(message.channel.id == ID1):
    
   if(message.content != "!verify"):
      await message.delete()

await bot.process_commands(message)```
potent spear
slate swan
#

How do i get it out of if statemnt?

potent spear
slate swan
#

Accidentally spaced down

potent spear
#

like vscode or whatever

slate swan
shut elk
#

looks something like this

shut elk
#

i'd edit original response which will only edit hte one that i just clicked idk how to edit for the future button sent

potent spear
slate swan
slate swan
#
async def on_message(message):
  if(message.channel.id == ID1):
    
   if(message.content != "!verify"):
      await message.delete()
  await bot.process_commands(message)```
#

I did this one not the last one

slate swan
#

to make bot still respond to command and deletes everything else but not the !verify

#

Like it deletes now but it won't respond to !verify

potent spear
slate swan
#

Yep

potent spear
potent spear
slate swan
#

Command !verify

slate swan
potent spear
slate swan
slate swan
# potent spear that it should respond
async def verify(ctx):
  await ctx.send('Sent verification info. Please check your DMs.')
  await ctx.author.send(embed=main)
  time.sleep(3)
  await ctx.channel.purge()```
#

This is code for command

slate swan
potent spear
#

^^

slate swan
#

time.sleep worked fine but anyways I'll change it

slate swan
#

It still isn't the problem

potent spear
slate swan
potent spear
unkempt canyonBOT
#

Pasting large amounts of code

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

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

potent spear
#

most likely, you have other errors in your code going on

slate swan
#

Do you understand the basics of python?

potent spear
#

I highly suggest you to first of all step away from using notepad as a code editor

#

especially as a beginner

slate swan
#

I said I'm using replit

#

^^

#

↑↑

#

Replit is not recommended either

#

Still works

#

Bruh from helping me fix the got we got to recommendations

#

Just help me fix this I'm stupid asf

potent spear
slate swan
potent spear
#

there's more errors in your code you're not showing

potent spear
#

your process_commands is STILL in an if statement

slate swan
#

Idk how to get it out

#

I admit

#

@potent spear not sure if we should be helping he quite literally has a variable named phish

#

Phish is litteraly just redirecting to another side instead of one that's shown in hyperlink

#

I could just remove it if I didn't want you to see

#

But i don't have anything to hide it's safe code so I didn't remove it

potent spear
# slate swan I admit
if (shit)
  print("in the if statement")
  print("still inside")
print("out of the if statement")```
slate swan
#

The phish variable value isn’t seen in the code which is what made me think it’s something malicious

#

Because you purposely removed it

#

Ye i guess that's valid reason to be suspicious

slate swan
#
await bot.process_commands(message)```
#

Ah no spaces

potent spear
#

!indent

unkempt canyonBOT
#

Indentation

Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.

Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.

Example

def foo():
    bar = 'baz'  # indented one level
    if bar == 'baz':
        print('ham')  # indented two levels
    return bar  # indented one level

The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.

Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines

More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation

potent spear
#

read that ^

slate swan
#

It’s tabs not spaces

#

Ikk wait lemme paste

#

That’s unindented yes

potent spear
#

try and see, you'll get the hang of how indentation works if you read what I told you to

slate swan
#

That’s the best way to learn it ^

potent spear
#

having an actual code editor will help you massively
in that case, you don't even have to care if it's a space or a tab, because the code editor formats it FOR YOU

slate swan
#

Can i just know why does it point there

potent spear
slate swan
potent spear
slate swan
#

I clicked it and it said formated

#

It turned out like this

potent spear
slate swan
potent spear
#

that line in your error should be indented one level

#

in your case, it's indented three levels

#

it's not ALIGNED with the outer most if statement, meaning it shouldn't be in any

potent spear
potent spear
#

yes, your line of code is inside the second if statement, you can SEE the difference, if you still don't understand, there are more info links in that bot's message

slate swan
#

Uhh

#

Ok wait

#

What do i do

#

Delete tabs(intends)?

potent spear
#

correct

#

try and see, read about it, you'll find out

slate swan
#

Here? bot.process_commands(message)

#

Where i typed here? I need to delete intends

#

Behind that code

#

I did all possible combinations

potent spear
#

yeah, that line is incorrectly indented, as mentioned for the 100th time

slate swan
#

I ran it after deleting every single intend

potent spear
#

you did not, just read about it, you'll find out, you're blindly guessing

slate swan
#

And none worked

potent spear
#

don't come back unless you've either fixed it or read all the links the bot told you to

slate swan
#

Lmao

#

Litteraly skull

#

Jit i deleted some intends bot ran and still command not working

#

OHHH

#

LMAOOOOO I SEEE

#

YESSIR I FIXED IT

#

I mean yall helped tysm

#

At the end i got intends right but bot.process_commands(message) wasn't right because i use client.command not bot.command didn't define bot

potent spear
slate swan
#

Idrc about that sorry

potent spear
#

you should

slate swan
#

How do i stack more exceptions?

#

Like if(message.content != "!verify","Sent verification info. Please check your DMs."):

potent spear
slate swan
#

Ye okay

potent spear
potent spear
heavy swift
#

?tags

slate swan
#

!tags

unkempt canyonBOT
#
Available tags

» traceback
» type-hint
» under
» underscore
» venv
» virtualenv
» voice-verification
» windows-path
» with
» xy-problem
» ytdl
» zip

spiral crypt
#
@client.event
async def on_member_remove(member):

Is this how I would check if a user has left the server? or does it have to be @client.listen()

slate swan
#

either work

potent spear
#

note that you'll need member intents for this

spiral crypt
potent spear
spiral crypt
#

yeah it is yepyep

potent spear
#

👍

hollow gazelle
#

^^^^^^^^^^^^^^^^^
AttributeError: 'Member' object has no attribute 'avatar_url'

#

File "C:\Users\rhino\OneDrive\Desktop\evolve\main.py", line 82, in on_member_join
embed.set_author(name=member.name, icon_url=member.avatar_url)
^^^^^^^^^^^^^^^^^
AttributeError: 'Member' object has no attribute 'avatar_url'

#

thats full error

vague jungle
#

^

#

avatar_url was removed

hollow gazelle
#

i had that

#

File "C:\Users\rhino\OneDrive\Desktop\evolve\main.py", line 82, in on_member_join
embed.set_author(name=member.name, icon_url=member.avatar.url)

vague jungle
#

Thats not an error code

hollow gazelle
#

holdon

vague jungle
#

Holding

hollow gazelle
#

raise e
File "C:\Users\rhino\OneDrive\Desktop\evolve\main.py", line 82, in on_member_join
embed.set_author(name=member.name, icon_url=member.avatar.url)
^^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'url'

vague jungle
#

did.. did you define member?

hollow gazelle
#

ye

vague jungle
#

can you post your code?

sick birch
#

The member doesn't have a profile picture

hollow gazelle
#

inna second

#

oh ye

#

makes sensebut embed dont send

potent spear
#

phaha, that's a classic

#

you have to check if member.avatar isn't None first

sick birch
#

member.display_avatar.url should be failsafe

hollow gazelle
#

ok

potent spear
sick birch
#

the default avatar

potent spear
#

in the correct color too?

sick birch
#

yes

#

the color of the default avatar depends on your discrim % 5

potent spear
#

good to know

hollow gazelle
#

it worked

slate swan
#

How can a discord bot create a topic?
How can a discord bot pin a message?

#

Pls help

slate swan
#

I don't speak English

#

1 min

#

thread*

sick birch
#

!d discord.Message.create_thread

unkempt canyonBOT
#

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

Creates a public thread from this message.

You must have [`create_public_threads`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.create_public_threads "discord.Permissions.create_public_threads") in order to create a public thread from a message.

The channel this message belongs in must be a [`TextChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel "discord.TextChannel").

New in version 2.0.
slate swan
sick birch
#

!d discord.Message.pin

potent spear
unkempt canyonBOT
#

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

Pins the message.

You must have [`manage_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") to do this in a non-private channel context.
slate swan
potent spear
#

F, my guy is creating his own wrapper

potent spear
slate swan
#

I can create a discord bot very easily
But there is a problem with "thread"

hollow gazelle
#
Ignoring exception in on_member_join
Traceback (most recent call last):
  File "C:\Users\rhino\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 377, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\rhino\OneDrive\Desktop\evolve\main.py", line 89, in on_member_join
    raise e
  File "C:\Users\rhino\OneDrive\Desktop\evolve\main.py", line 87, in on_member_join
    raise e
  File "C:\Users\rhino\OneDrive\Desktop\evolve\main.py", line 84, in on_member_join
    embed.set_footer("Evolve Devlopment")
TypeError: Embed.set_footer() takes 1 positional argument but 2 were given
potent spear
hollow gazelle
#

oh

slate swan
hollow gazelle
potent spear
slate swan
potent spear
hollow gazelle
#

ok

sick birch
slate swan
#

What is code for mention author

sick birch
#

py -3 -m pip -U install discord.py I believe is the command

slate swan
#

Hack Bot*🤣

#

I forgot

sick birch
slate swan
#

await ctx.send('Sent verification info. Please check your DMs. message.author.mention')

#

This would work?

#

nope

slate swan
hollow gazelle
slate swan
#

!fstring

unkempt canyonBOT
#

Creating a Python string with your variables using the + operator can be difficult to write and read. F-strings (format-strings) make it easy to insert values into a string. If you put an f in front of the first quote, you can then put Python expressions between curly braces in the string.

>>> snake = "pythons"
>>> number = 21
>>> f"There are {number * 2} {snake} on the plane."
"There are 42 pythons on the plane."

Note that even when you include an expression that isn't a string, like number * 2, Python will convert it to a string for you.

slate swan
#

you'd need a fstring for that to work

#

What

sick birch
slate swan
#

Oh ye i remember

slate swan
#

Ty

#

await ctx.send(f"Sent verification info. Please check your ctx.author.mention")

#

Doesn't work

slate swan
#

{ctx.author.mention}

#

await ctx.send(f"Sent verification info. Please check your {ctx.author.mention}")

#

Ty

hazy vault
#

Hello guys, I have a question....Can I get a project from the famous bots?

#

Like a probot

slate swan
# slate swan Ty

Error:
await ctx.send(f"Sent verification info. Please check your ctx.author.mention")
^^^^^^^^^^^^^

#

await ctx.send(f"Sent verification info. Please check your {ctx.author.mention}")
^^^^^^^^^^^^^

slate swan
#

U already told me

#

Ok

#

'Context' object has no attribute 'create_thread'

#
async def on_message(message):
  if(message.channel.id == ID1):
    
   if(message.content != f"Sent verification info. Please check your {ctx.author.mention}"):
      await message.delete()
  await client.process_commands(message)```
#

This is the code that deletes everything bessides bot reply to !verify command

#

And

slate swan
#

Error i get is ctx is not defined

hazy vault
#

guuyyyyyys I'm here

slate swan
#

For ctx.author.mention

hazy vault
#

Hello guys, I have a question....Can I get a project from the famous bots?
Like a probot

slate swan
hazy vault
#

Web?

#

it's bot

slate swan
hazy vault
#

no

slate swan
hazy vault
#

I meant is it possible to take a project from any bot

slate swan
#

No

slate swan
#
async def verify(ctx):
  await ctx.send(f"Sent verification info. Please check your {ctx.author.mention}")
  await ctx.author.send(embed=main)
  await asyncio.sleep(3)
  await ctx.channel.purge()

@client.event
async def on_message(ctx):
  if(ctx.channel.id == ID1):
    
   if(ctx.content != f"Sent verification info. Please check your {ctx.author.mention}"):
      await ctx.delete()
  await client.process_commands(message)```
hazy vault
#

And modify it

hazy vault
hazy vault
#

I expected that

slate swan
#
async def verify(ctx):
  await ctx.send(f"Sent verification info. Please check your {ctx.author.mention}")
  await ctx.author.send(embed=main)
  await asyncio.sleep(3)
  await ctx.channel.purge()

@client.event
async def on_message(ctx):
  if(ctx.channel.id == ID1):
    
   if(ctx.content != f"Sent verification info. Please check your {ctx.author.mention}"):
      await ctx.delete()
  await client.process_commands(ctx)```
#

Now bot is deleting it's reply

slate swan
#

Wdym no

#

await ctx.delete()😭

slate swan
#

What?

slate swan
slate swan
slate swan
slate swan
slate swan
#

No error

slate swan
#

await ctx.message.delete()

slate swan
#

._.

#

:/

#

What then needs to be done?

#

It nee

slate swan
#
async def verify(ctx):
  await ctx.send(f"Sent verification info. Please check your {ctx.author.mention}")
  await ctx.author.send(embed=main)
  await asyncio.sleep(3)
  await ctx.channel.purge()

@client.event
async def on_message(ctx):
  if(ctx.channel.id == ID1):
    
   if(ctx.content != f"Sent verification info. Please check your {ctx.author.mention}"):
      await ctx.message.delete()
  await client.process_commands(ctx)```
#

ctx.message.delete() - Not for you

#

Wdym

#

Not for me? For someone else you've said

potent spear
slate swan
#

Mhm

potent spear
#

it has one param: message, not ctx

slate swan
#

Mhm

potent spear
#

so if you understand what that means, you should know what to change

slate swan
#

Mhm

potent spear
#

only a command has ctx as first param, you could add extra arguments, depending if your command needs some

#

that's all written in the starters guide etc

slate swan
shut elk
#

class chan1(discord.ui.View):
    def __init__(self) -> None:
        super().__init__(timeout=None)

    @discord.ui.button(label="", style = discord.ButtonStyle.blurple,custom_id='channel1')
    async def c1(self, interaction:discord.Interaction, button: discord.ui.Button):
         ... #makes a new button with channel.send(view=self, embed=embed)
#

how would I change label of the newly created button for other than ""

potent spear
shut elk
#

right now when I run it, it only produces buttons with "" and I don't know how to change it to something different

slate swan
#
async def verify(message):
  await message.send(f"Sent verification info. Please check your {message.author.mention}")
  await message.author.send(embed=main)
  await asyncio.sleep(3)
  await message.channel.purge()

@client.event
async def on_message(message):
  if(message.channel.id == ID1):
    
   if(message.content != f"Sent verification info. Please check your {message.author.mention}"):
      await message.delete()
  await client.process_commands(message)```
#

Why bot deletes it's reply???

potent spear
potent spear
slate swan
#

Mhm

slate swan
#

Just tell me is there a way for it to not delete it's reply

potent spear
slate swan
#

And it was working well until i added mention

#

After i added {message.author.mention}

#

It deletes reply

potent spear
#

if you just want me to shut up and give you the answer:
await ctx.channel.create_thread(....)

slate swan
potent spear
slate swan
#

translator fu*

shut elk
#

i mean, i know how to edit change it but not for the new button

slate swan
potent spear
slate swan
potent spear
potent spear
slate swan
#

:/

potent spear
# slate swan How to do
@client.command()
async def verify(ctx):
  await ctx.send(f"Sent verification info. Please check your {message.author.mention}")
  await ctx.author.send(embed=main)
  await asyncio.sleep(3)
  await ctx.channel.purge()

@client.event
async def on_message(message):
  # this makes sure the bot doesn't respond to itself
  if (message.author == client.user):
    return
  # this is all bullshit, as the message is already deleted in the verify command
  #if(message.channel.id == ID1):
    
   # if(message.content != f"Sent verification info. Please check your {message.author.mention}"):
  #await message.delete()
  await client.process_commands(message)```
potent spear
ionic garden
#

how do i clear all commands of a bot?
just completely remove any and all slash commands?
(this is bc dupes are appearing and they're making me so uncomfortable)

shut elk
potent spear
potent spear
slate swan
potent spear
slate swan
#

I realized that it is very difficult for me to create a branch

#

._.

slate swan
#

!pin

unkempt canyonBOT
#

You are not allowed to use that command here. Please use the #bot-commands channel instead.

shut elk
#

but yes

potent spear
potent spear
shut elk
#

isnt it this server tho

potent spear
slate swan
ionic garden
potent spear
ionic garden
#

bruuuh

#

a whole hour?

potent spear
ionic garden
#

no

slate swan
#

I need to change the nickname of all server members (discord.py)

slate swan
#

you know the way choices are in dicts well how would i get all user ids from sql db and make as choice

mental hollow
#

and use:

#

!d discord.Member.edit

unkempt canyonBOT
#

await edit(*, nick=..., mute=..., deafen=..., suppress=..., roles=..., voice_channel=..., timed_out_until=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Edits the member’s data.

Depending on the parameter passed, this requires different permissions listed below...
slate swan
#

What's wrong?

#

Why my bot won't respond

potent spear
potent spear
slate swan
potent spear
# slate swan yea

your db is already connected to your discord bot?
so you can store it in a variable through a command?

potent spear
jaunty hare
#

hi! if someone can help me, why with pycharm its all okay, but with visual studio code give me this error

potent spear
#

just remove some letters from the token, idc

potent spear
#

I most likely know what's up, you're getting this token from some file, right?

#

it has to do with the path

#

your token isn't properly read, just print it before you put it in the run, you'll see

jaunty hare
potent spear
#

I'll fix them for you

#

so, you've currently hardcoded your path, which means that when you move your project folder, you'll get errors

#

I'll change the filepath to look for config.json in your current folder ( where your main bot file is too) good?

jaunty hare
#

good

potent spear
#

from pathlib import Path

jaunty hare
#

ajam

potent spear
#

config_file_path = Path(__file__).parent / 'config.json'

#

you'll know what to do with that, good luck!

jaunty hare
#

thnak u bro

slate swan
#
async def who(ctx, member: discord.Member, roles=None, author=None):
    """- Displays a users account details."""
    if member:
        embed = discord.Embed(title=f"User information for {member.name}",
                              description=f"Join and creation information for {member.mention}")
        embed.add_field(name="Server Join:", value=member.joined_at.strftime("%d/%m/%y, %H:%M:%S"))
        embed.add_field(name="Discord Registration:", value=member.created_at.strftime("%d/%m/%y, %H:%M:%S"))
        embed.set_thumbnail(url=member.avatar_url)
        await ctx.send(embed=embed)```
#

Member objest has no attribute avatar_url

potent spear
slate swan
#

?

potent spear
slate swan
#

Idk i used old code from old bot

#

It worked back then shrug

potent spear
#

well, since then, things have changed

slate swan
#

I guess so

slate swan
#

I'm on phone

#

I think there's still search thing somewhere

potent spear
#

you can scroll through, it's not that big

slate swan
#

Alr i found

#

That helps alot

potent spear
#

yup, learning how to use the docs will save you tons of time

elder shuttle
#

So i'm trying to have my bot pin a message that is reacted with 📌

It has a command, and then it has something like

await self.bot.wait_for('reaction_add',check=check,timeout=30)

potent spear
#

mhm, the check is important too

#

make sure it contains the same args as the on_reaction_add would

slate swan
#

All of a sudden %M: is invalid syntax

#

embed.add_field(name="Discord Registration:", value=member.created_at.strftime("%d/%m/%y, %H:%M:%S"))

potent spear
#

from now on, just send your WHOLE error traceback with all code you have. you'll get way quicker answers

ionic garden
potent spear
slate swan
ionic garden
#

yeah, i did regen my bot token?

potent spear
slate swan
#

Oh i had links there

unkempt canyonBOT
#

Pasting large amounts of code

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

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

ionic garden
#

lol alr

slate swan
#
async def who(ctx, member: discord.Member, roles=None, author=None):
    """- Displays a users account details."""
    if member:
        embed = discord.Embed(title=f"User information for {member.name}",
        embed.add_field(name="Server Join:", value=member.joined_at.strftime("%d/%m/%y, %H:%M:%S"))
        embed.add_field(name="Discord Registration:", value=member.created_at.strftime("%d/%m/%y, %H:%M:%S"))
        embed.set_thumbnail(url=member.avatar)
        await ctx.send(embed=embed)```
#

I don't think you need whole code?

unkempt canyonBOT
#

Here's how to format Python code on Discord:

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

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

slate swan
#

I did it?

potent spear
#

I need it in python

slate swan
#
@client.command()
async def who(ctx, member: discord.Member, roles=None, author=None):
    """- Displays a users account details."""
    if member:
        embed = discord.Embed(title=f"User information for {member.name}",
        embed.add_field(name="Server Join:", value=member.joined_at.strftime("%d/%m/%y, %H:%M:%S"))
        embed.add_field(name="Discord Registration:", value=member.created_at.strftime("%d/%m/%y, %H:%M:%S"))
        embed.set_thumbnail(url=member.avatar)
        await ctx.send(embed=embed)
potent spear
slate swan
#

Okay

potent spear
#

also, remember the link I sent you? there's something important regarding the .avatar attribute

naive briar
cunning pasture
#

Do people prefer traditional prefix commands or interactions/slash commands?

naive briar
#

Prefix commands

potent spear
#

more user-friendly is slash commands I'd say

naive briar
#

Slash commands are somewhat limited

potent spear
#

it tells you what arguments you need etc
noobs don't know how to use text commands

naive briar
#

Like member arguments, you can't input IDs there

cunning pasture
#

Would slash commands be better for commands with multiple arguments and prefix commands be better for singular commands?

cunning pasture
potent spear
#

just use hybrid commands if you can't pick lol

cunning pasture
potent spear
#

you know what a hybrid command is, right?

naive briar
cunning pasture
naive briar
#

Try it, or did they fix that?

potent spear
cunning pasture
potent spear
#

by using a typed integer typehint

#

!d discord.AppCommandOptionType.integer

unkempt canyonBOT
naive briar
#

I don't know about you, but I wouldn't add a new argument just for IDs

cunning pasture
naive briar
#

Some time the server is big

#

And usernames are not limited to only English letters

#

You can easily miss the target member

potent spear
#

which means you wouldn't be able to mention them?
I'd just copy paste their name, no escaping that

ionic garden
#

uh i just synced my discord commands (they're all hybrid_command or commands.command)
but the slash commands aren't registering?
prefix commands work (a.inventory) but slash commands don't & give this error: https://paste.pythondiscord.com/ekomezifus

cunning pasture
naive briar
#

I would use something like member context manager and get inputs from a modal instead

ionic garden
cunning pasture
#

hm

upbeat gust
#

I think you synced to the wrong scope before and now they don't exist in your code but they do on discord

upbeat gust
ionic garden
slate swan
#
@client.event
async def on_message(message):
    if message.content == "Help":
        await message.reply("**If you're asking for help just watch fucking tutorial [#1061090311314624522](/guild/267624335836053506/channel/1061090311314624522/) watch it from top and then if you still don't understand something just dm @fervent escarp**")
#

What's wrong i get no errors but bot won't respond

upbeat gust
#

Do you have the message_content intent?

slate swan
#

I made 4 same events just another message like help, Help, how to

slate swan
mental hollow
#

loop through "everyone" then

slate swan
#
intents = discord.Intents.all()


client = commands.Bot(command_prefix = "!", intents=intents)
client.remove_command('help')
upbeat gust
upbeat gust
#

I'm not sure sorry, you could try syncing an empty tree to clear it then sync the hybrid commands

ionic garden
#

yeah that's what i did

#

oh wait hold on lemme try something

#

lmao

#

now the commands aren't show up at all

#

bruh i just got ratelimited

slate swan
ionic garden
#

that sounds sus, and might violate rule 5 of this server

slate swan
potent spear
#

idem for unsync

ionic garden
#

but sync commands are prefix commands?

potent spear
#

ah, in that case, maybe make a custom typehint, ~enum

#

SYNCSCOPE.GUILD
or SYNCSCOPE.GLOBAL yk

#

idk what the pep (~correct casing) is for enums tho, so this uppercase might not be needed 🙂

unkempt canyonBOT
#
Certainly not.

No documentation found for the requested symbol.

ionic garden
pliant gulch
#

I think it would be cool to make your sync command using flags, it's versatile

potent spear
ionic garden
#

oh lol

jaunty hare
#

is this okay? what i wanna do is, when someone click the button, it first get the person who clicked and then add it to a mysql database

naive briar
#

Move your button callback definition down

#

And use aiosqlite instead of sqlite3

jaunty hare
#

why?

naive briar
#

Why what

jaunty hare
naive briar
#

sqlite3 is blocking

#

!blocking

unkempt canyonBOT
#

Why do we need asynchronous programming?
Imagine that you're coding a Discord bot and every time somebody uses a command, you need to get some information from a database. But there's a catch: the database servers are acting up today and take a whole 10 seconds to respond. If you do not use asynchronous methods, your whole bot will stop running until it gets a response from the database. How do you fix this? Asynchronous programming.

What is asynchronous programming?
An asynchronous program utilises the async and await keywords. An asynchronous program pauses what it's doing and does something else whilst it waits for some third-party service to complete whatever it's supposed to do. Any code within an async context manager or function marked with the await keyword indicates to Python, that whilst this operation is being completed, it can do something else. For example:

import discord

# Bunch of bot code

async def ping(ctx):
    await ctx.send("Pong!")

What does the term "blocking" mean?
A blocking operation is wherever you do something without awaiting it. This tells Python that this step must be completed before it can do anything else. Common examples of blocking operations, as simple as they may seem, include: outputting text, adding two numbers and appending an item onto a list. Most common Python libraries have an asynchronous version available to use in asynchronous contexts.

async libraries
The standard async library - asyncio
Asynchronous web requests - aiohttp
Talking to PostgreSQL asynchronously - asyncpg
MongoDB interactions asynchronously - motor
Check out this list for even more!

jaunty hare
#

ohhh

naive briar
#

aiosqlite is asynchronous binding for sqlite3, so it's not blocking but still is the same

#

!pypi aiosqlite

unkempt canyonBOT
jaunty hare
#

thank u bro

ionic garden
#

can someone tell me why the default value for inline in Embed.add_field is true

#

because the majority of the time i want it to be false

blazing condor
ionic garden
#

well i guess i'm in the minority lmao

blazing condor
#

lmao right

#

depends on the specific use case and what the user finds to be more visually appealing and easy to read.

ionic garden
#

so rn my cogs are like this:

#

i'm concerned about the # of cogs getting out of hand later on
can i organize them into subdirectories & still have them all load?

naive briar
#

Ye

sick birch
fading marlin
sick birch
#

Our bots like @unkempt canyon have a crap load of cogs

swift acorn
ionic garden
ionic garden
sick birch
#

file extensions are pretty much worthless

ionic garden
#

ok but
my ide cares

sick birch
#

The convention is that it should be a .py file

#

Though it doesn't have to be

swift acorn
#

File extensions actually pretty much mean nothing, and are just an indicator to your OS connecting it directly to a program

ionic garden
#

alr then

ionic garden
spiral crypt
#
@client.listen()
async def on_message(message):
    if message.author.bot:
        return

For some reason when I have that if message.author.bot it sends things twice, but when i remove it it works, howeverrr i also dont want the bot to trigger the other stuff in my on_message, any ideas?

sick birch
spiral crypt
#

no o:

sick birch
#

Can you show us your rank command?

spiral crypt
#
@client.command()
async def rank(ctx):
    args = {
        'bg_image': rank_card_backgrounds[config[str(ctx.author.id)]["rankcard"]-1],
        'profile_image': ctx.author.avatar_url,
        'level': xp[str(ctx.author.id)]["level"],
        'current_xp': 0,
        'user_xp': xp[str(ctx.author.id)]["xp"],  # User current xp
        'next_xp': level_thresholds[xp[str(ctx.author.id)]["level"]],
        'user_position': lookup.get_leaderboard_position(str(ctx.author.id), xp),
        'user_name': ctx.author.name,
    }
    image = Generator().generate_profile(**args)

    file = discord.File(fp=image, filename='image.png')
    await ctx.send(file=file)

However its not just the rank command, its any command i send

sick birch
#

Can you show us your entire on_message?

spiral crypt
#
@client.listen()
async def on_message(message):
    if message.author.bot:
        return
    user_id = str(message.author.id)
    if user_id not in config:
        config[user_id] = {"level_up_message_active": True, "rankcard": 1}
    user_config = config[user_id]
    if user_id not in xp:
        xp[user_id] = {"level": 1, "xp": 0, "cooldown": 0}
    user_xp = xp[user_id]


    if user_xp["cooldown"] <= 0:

        user_xp["xp"] += random.randint(1, 3)
        user_xp["cooldown"] = 15

        while user_xp["xp"] >= level_thresholds[user_xp["level"]]:
            user_xp["xp"] = user_xp["xp"] - level_thresholds[user_xp["level"]]
            user_xp["level"] += 1
            if user_config["level_up_message_active"] and message.channel.id not in blacklist:
                await message.channel.send(f"{message.author.mention} level up to {user_xp['level']}!")

            for i, rank in enumerate(rank_thresholds):
                if user_xp["level"] >= rank["threshold_level"]:
                    role = discord.utils.get(message.guild.roles, name=rank["name"])
                    await message.author.add_roles(role)
    await saves.save_xp(xp)
    await saves.save_config(config)
sick birch
#

hmmmm

#

I'd check to see if you have another bot process running

#

If you're not sure restart your computer

spiral crypt
#

will check gimme a moment and ill let ya know

#

huh yeah idk why that was happening then, never had that issue

sick birch
#

Did restarting fix it?

spiral crypt
#

yeah

sick birch
#

Well you know what they say
"Have you tried turning it off and on again?"

spiral crypt
#

yep xP

#

thank you

slate swan
#

Question: How do I loop voice_client.play() when it ends? I tried to look on discord.py docs but could be missing something.

vale wing
unkempt canyonBOT
#

asyncio.run_coroutine_threadsafe(coro, loop)```
Submit a coroutine to the given event loop. Thread-safe.

Return a [`concurrent.futures.Future`](https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.Future "concurrent.futures.Future") to wait for the result from another OS thread.

This function is meant to be called from a different OS thread than the one where the event loop is running. Example...
austere vale
#
#message delete
  @commands.Cog.listener()
  async def on_message_delete(self, message):
    async for entry in message.guild.audit_logs(action=nextcord.AuditLogAction.message_delete,limit=1):
      embed=nextcord.Embed(title="Message delete", description= f"Deleted by {entry.user.mention} \(this is unreliable\) in {message.channel.mention}\nMessage: {message.content}\nMessage author: {message.author.mention}",color=0xfd9fa1, timestamp=datetime.datetime.utcnow())

does anyone know what i should put in place of entry.user.mention so that it correctly mentions whoever deleted the message?

flat pier
#

at least according to the docs it doesn't say it does

slate swan
#

its also not very reliable to use audit log to track actions, doesn't always get added

austere vale
#

ah, so theres no way to do it

static holly
#

hi, i want change my main page with TOken line by a .env file with token,
After import os and dotend (load_dotenv) i have a issue:
TypeError: expected token to be a str, received NoneType instead

slate swan
#

use python dotenv to load your env first

#

!pypi python-dotenv

unkempt canyonBOT
static holly
slate swan
#

install it and add ```py
import dotenv
dotenv.load_dotenv()

static holly
# slate swan install it and add ```py import dotenv dotenv.load_dotenv() ``` in ur code
import discord
from discord.ext import commands
from cogcmd.cog_info import cog_info
from cogcmd.cog_cmd import liste_commandes
import os
from dotenv import load_dotenv

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


load_dotenv()
TOKEN = os.getenv("TOKEN")

@bot.event
async def on_ready():
        print("Le bot connecté")

        await bot.load_extension("cogcmd.cog_info")
        await bot.load_extension("cogcmd.cog_cmd")

bot.run(TOKEN)
#

what is the error? 😕

slate swan
#

Do you have a TOKEN key set in your .env file?

static holly
slate swan
#

well the error means that you dont

static holly
#

in .env file:

TOKEN = MTA2MzU0MzAw
slate swan
#

print os.environ to make sure it is or not

static holly
#

@slate swan

slate swan
#

your env file is not even saved

#

and are you sure you are in the correct directory?

static holly
#

it because i dont save my file before run the command

#

now i can share my source code ^^

heady verge
#

~~i am using pycord and in one of the cogs, i want to use bridge_command so i used ~~

@commands.bridge_command(guild_ids = ids, name = "snipe", description = "Gets a deleted message")

just as in discord.py commands.hybrid_command()
~~but i get this error - ~~
AttributeError: module 'discord.ext.commands' has no attribute 'bridge_command'. Did you mean: 'message_command'?
so how should i use bridge cmds in cogs?
Got it...

severe nacelle
#

Guys can you help me

#

How to connect python vscode with powershell

#

It's opening Microsoft Store if I type python in powershell

warped magnet
#

anyone know how to fix this? im pretty new to coding and i just used a sample code from a video and altered it a bit (repl.it)

slate swan
#

!intents

unkempt canyonBOT
#

Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.

There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.

Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:

from discord import Intents
from discord.ext import commands

# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True

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

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

warped magnet
#

hm

shut elk
#

Hold on, why is it that when I do this, only some people can do it

shut elk
naive briar
#

!d discord.app_commands.checks.has_role

unkempt canyonBOT
#

@discord.app_commands.checks.has_role(item, /)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check "discord.app_commands.check") that is added that checks if the member 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.

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

New in version 2.0...
shrewd fjord
#

Smort

slate swan
#

Amort

shrewd fjord
#

;-;

#

Bro always here to make fun of my mistakes 😔

slate swan
#

its an actual word

shut elk
#

the <> format

naive briar
#

What

vale wing
#

Role mention or smth

shut elk
shut elk
# naive briar What

also how do I limit a button to only one person being able to click it once

#

i tried button disable but if in time, 2 people can still click in same time

vale wing
#

!d discord.ui.View.interaction_check

unkempt canyonBOT
#

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

A callback that is called when an interaction happens within the view that checks whether the view should process item callbacks for the interaction.

This is useful to override if, for example, you want to ensure that the interaction author is a given user.

The default implementation of this returns `True`.

Note

If an exception occurs within the body then the check is considered a failure and [`on_error()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View.on_error "discord.ui.View.on_error") is called.
vale wing
#

Override this in your subclass

shut elk
vale wing
#

Simple OOP

shut elk
#

ok

shut elk
vale wing
#

me no like such questions

#

Typically person who asks like this doesn't even have OOP knowledge

shut elk
vale wing
#

Anyways you got the subclass of discord.ui.View right?

vale wing
#

Hold up a bit I will explain that