#discord-bots

1 messages · Page 472 of 1

hasty iron
#

i mean im not trying to be rude, but it doesn’t make sense

slate swan
#

Ok

#

Ty

ruby cosmos
#

Can multiple instances of a task loop run at once?

hasty iron
#

like a single task multiple times?

#

if so, iirc no

ruby cosmos
#

Yep

hasty iron
#

yeah you cant

#

it raises RuntimeError

ruby cosmos
#

So what could I do instead

slate swan
#

hurry answe pls how can i make it so certain ids can use a cmd as well as certain perms

hasty iron
ruby cosmos
#

So individual users can have loops for themselves

#

I guess I could do that with a command

slate swan
hasty iron
#

sorry, idk selenium

ruby cosmos
#

But I still want it to be cancellable with another command

slate swan
hasty iron
#

you could make an async function and implement the looping logic yourself

#

and start the task with

#

!d asyncio.loop.create_task

unkempt canyonBOT
#

loop.create_task(coro, *, name=None)```
Schedule the execution of a [Coroutines](https://docs.python.org/3.10/library/asyncio-task.html#coroutine). Return a [`Task`](https://docs.python.org/3.10/library/asyncio-task.html#asyncio.Task "asyncio.Task") object.

Third-party event loops can use their own subclass of [`Task`](https://docs.python.org/3.10/library/asyncio-task.html#asyncio.Task "asyncio.Task") for interoperability. In this case, the result type is a subclass of [`Task`](https://docs.python.org/3.10/library/asyncio-task.html#asyncio.Task "asyncio.Task").

If the *name* argument is provided and not `None`, it is set as the name of the task using [`Task.set_name()`](https://docs.python.org/3.10/library/asyncio-task.html#asyncio.Task.set_name "asyncio.Task.set_name").

Changed in version 3.8: Added the `name` parameter.
hasty iron
#

then you could save the task and call

#

!d asyncio.Task.cancel

unkempt canyonBOT
#

cancel(msg=None)```
Request the Task to be cancelled.

This arranges for a [`CancelledError`](https://docs.python.org/3.10/library/asyncio-exceptions.html#asyncio.CancelledError "asyncio.CancelledError") exception to be thrown into the wrapped coroutine on the next cycle of the event loop.

The coroutine then has a chance to clean up or even deny the request by suppressing the exception with a [`try`](https://docs.python.org/3.10/reference/compound_stmts.html#try) … … `except CancelledError` … [`finally`](https://docs.python.org/3.10/reference/compound_stmts.html#finally) block. Therefore, unlike [`Future.cancel()`](https://docs.python.org/3.10/library/asyncio-future.html#asyncio.Future.cancel "asyncio.Future.cancel"), [`Task.cancel()`](https://docs.python.org/3.10/library/asyncio-task.html#asyncio.Task.cancel "asyncio.Task.cancel") does not guarantee that the Task will be cancelled, although suppressing cancellation completely is not common and is actively discouraged.

Changed in version 3.9: Added the `msg` parameter.

The following example illustrates how coroutines can intercept the cancellation request:
ruby cosmos
#

Ok thanks

waxen python
#

I tried this

        vc_list = []
        for vc in self.client.voice_clients:
            for member in vc.members:
                vc_list.append(member)
        await ctx.send(f"There are {len(vc_list)} connected voice channels!")

but it just always returns 0, would you know if i did something wrong?
(its in a cog)

hasty iron
#

i believe you could simplify that to a list comp

waxen python
#

well, i need to have it working first

hasty iron
#

it could be an intent issue

#

do you have intents enabled

pliant gulch
#

Did you take a look at the docs????

waxen python
#

server members intents, yes

pliant gulch
#

It says its a VoiceProtocol not a voice channel

#

VoiceProtocol has a channel property which is what you want to access members on

hasty iron
#

it didn’t raise an error? 🤔

waxen python
#

nop

pliant gulch
#

Not sure either way just try that ig

#

I'm not good at voice

waxen python
#

im looking at that now

opaque trail
#

discord.FFmpegPCMAudio is blocking the main thread and makes my computer a fucking jet taking off? last week it did not do that, any ideas?

maiden fable
opaque trail
#

Nope, runned smoothly, perfectly, creating 500 instances extremely fast, now its blocking the main thread, making my cpu usage 100%, etc

maiden fable
#

Do u have logging turned on?

opaque trail
#

yes

maiden fable
#

And it's printing that the bot is being blocked or something?

opaque trail
#

obvisouly.

#

i just said it did block?

maiden fable
#

Well, sometimes the bot doesn't respond to commands and thTs when people say it's blocking

#

Well my best bet would be to see your resources consumption from the task manager or something

fading granite
#

Hi! I wanted to make a simple verification bot that presents a picture containing captcha to any new member and checks whether the new member enters it correctly and then gives them a role.
Can someone guide me on how do I go about? I feel lost.

lone lichen
vale root
#

Is there a way to make a embed's color a hex not the main colors?

maiden fable
#

0xcode

wind rapids
#

Anyone know why errors are still raised?

maiden fable
wind rapids
#

I have that, but errors are still raised

#

I thought that would capture all errors?

red canopy
#

does anyone know how to create a thread? guild.create_thread doesn't seem to be working

stark hearth
#

for <error>, its like MissingPermissions or CommandInvokeError

wind rapids
#

I did, it still raises the error

stark hearth
wind rapids
high flame
wind rapids
high flame
#

have you loaded the cog?

wind rapids
#

Yes

high flame
#

check again pithink

stark hearth
# wind rapids

maybe do @commands.has_permissions(ban_members=True) but run it again

high flame
stark hearth
wind rapids
high flame
#

also, you can't do that with 1.7

#

use 2.0 instead

wind rapids
high flame
wind rapids
high flame
#

does it log that?

wind rapids
#

Yes

high flame
#

ugh

stark hearth
wind rapids
high flame
stark hearth
high flame
#

that could not be a problem

stark hearth
red canopy
wicked atlas
#

Perhaps try putting a print statement outside of any conditions in your error handler, and see if it runs?

high flame
wind rapids
wicked atlas
#

So that print statement printed?

wind rapids
wicked atlas
#

odd

high flame
red canopy
#

k thx

red canopy
wicked atlas
#

To install 2.0, you need to install it directly from the repository

pip install git+https://github.com/Rapptz/discord.py@master
#

or use a fork, which I would do

high flame
#

this ^^

#

the latest stable version in pypi is 1.7.3

slate swan
#

is a say command ideal? or can it be used for things such as disabling your bot via violating chat tos

maiden fable
slate swan
#

alright thanks

vague grove
#

how can I "ping" a channel to see if it exists

wicked atlas
#

Well, if you use fetch_channel and the channel ID, you can see if it exists

#

If it dosen't exist, it returns None

vague grove
#

ah

#

good idea

slate swan
#

Anyone know why I can't run my discord bot
The error says I can't run the token
and I

#
client.run(token)
night onyx
#

Is there any method by which I can check whether a guild member is bot or not

slate swan
#

I'm not sure

slate swan
#

like that ?

kindred epoch
slate swan
#

i can't use a link for a server in my button

kindred epoch
#

Show how u did it

slate swan
#

the top one works but the bottom doesn't, they are the same code

kindred epoch
#

The code is what I mean

slate swan
#

i can't because the guild thing is in there

#

@kindred epoch i dmed u it

#

Can someone please help me with this it won't let me run the token for some reason

import discord
from discord.ext import commands

TOKEN = ('mytoken')

intents = discord.Intents.default()
intents.members = True
client = commands.Bot(command_prefix=';', intents=intents)


@client.event
async def on_ready():
    await client.change_presence(status=discord.Status.idle, activity=discord.Game('With cheese!'))
    print("Cheese Bot Is Ready!")


@client.command()
async def cheese(ctx):
    await ctx.send("cheese :cheese:")


@client.command()
async def embed(ctx):
    embed = discord.Embed(title="cheese", url="https://google.com", description="We love cheese", color=0xffa64d)
    await ctx.send(embed=embed)



client.run(TOKEN)
jade jolt
#

why is it inside a tuple

final iron
slate swan
jade jolt
#

some do that

#

is ur token valid

slate swan
#

Yes

jade jolt
#

try make a new one and use it

slate swan
#

I have and made a new bot

#

Idk if they changed how you run it

jade jolt
#

show error

#

if any

slate swan
#
line 27, in <module>
    client.run(TOKEN)
#

error ^

jade jolt
#

full error

slate swan
#

exit code 1

jade jolt
#

send the full traceback

final iron
#

^

wicked atlas
unkempt canyonBOT
#

bot```
Equivalent to [`User.bot`](https://discordpy.readthedocs.io/en/stable/api.html#discord.User.bot "discord.User.bot")
wicked atlas
jade jolt
#

you didnt enable intents inside the bot developer page

slate swan
#

I turned on the wrong thing

#

Skid

vivid nexus
#

heya
so i have a class that runs with a while True statement
and each time i send a command, i want to create a new instance of that class
however im p sure since it runs by a while loop, it doesnt do anything since thats jus running all at once and the command is waiting for the function to finish
any recommendations on how to implement threading so i can use it?

blazing coral
#

so i am kindly confused whats wrong with this code lol cause its not giving any errors just wont work

#

@client.event
async def on_message_send(message):
message = "@,everyone"
logchannel = client.get_channel(886651843051155497)

await logchannel.send(f'Message from bot \nContent: {message.content}')
#

the , between the @ and everyone isnt there in the code just wont let me send on here

#

without it

vale pendant
#

well what are you trying to do?

wicked atlas
blazing coral
#

it has worked in other things i dont get why not on this etc

wicked atlas
#

Also, you can send without pinging people if you format

#

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

wicked atlas
#
@client.event
async def on_message_send(message):
    # message = "@,everyone" <- remove this for a second
    logchannel = client.get_channel(886651843051155497)

    await logchannel.send(f'Message from bot \nContent: {message.content}') # This should now run sucessfully
#

Also, never heard of an event named on_message_send?

blazing coral
#

alright but now how is it going to know to send the message to my audit log if we dont tell it what word to send it on

blazing coral
#

when somone sends a message containing the word ('@everyon') i want it to send a thing to my log channel

wicked atlas
#

Oh, so you want to check if a message mentions everyone

blazing coral
#

no

wicked atlas
#

?

blazing coral
#

sorry read what you said wrong

#

yes

wicked atlas
#

Just use an if statement and the mention_everyone attribute

if message.mention_everyone:
    logchannel = client.get_channel(886651843051155497)
    await logchannel.send(f'Message from bot \nContent: {message.content}')
blazing coral
#

so how would i intergrate this to what i have etc

wicked atlas
#

Well, it would just go into your event

blazing coral
#

so just put the if in were i had the message =

#

alright make sense if statements confuse me alots so sorry for the trouble

wicked atlas
#

Yup

#

Also, just to clear up any confusion I think you might have, = is for assignment of variables, and == is for comparison of values

#

!comparison

unkempt canyonBOT
#

Assignment vs. Comparison

The assignment operator (=) is used to assign variables.

x = 5
print(x)  # Prints 5

The equality operator (==) is used to compare values.

if x == 5:
    print("The value of x is 5")
blazing coral
#

alright thanks

slate swan
#

I did it now but ty anyway

#

Do you know how I can add text infron and after the number?```py
@client.command()
async def cheesy(ctx):
await ctx.send((random.randint(1,100)))

boreal ravine
#

@slate swan f strings

slate swan
wicked atlas
#

!strings

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.

drifting arrow
#

@slate swan

@client.command()
async def cheesy(ctx):
    await ctx.send(f"My Text {(random.randint(1,100))}")
boreal ravine
#

@drifting arrow y spoonfeed

drifting arrow
#

Coz he's gonna be back anyway

boreal ravine
drifting arrow
#

Relax. I give it 5 minutes before he's back

boreal ravine
#

Why?

drifting arrow
#

Why what?

slate swan
#

I put one too many brackets

#

but ty anyway

boreal ravine
drifting arrow
#

Coz he will. Trust.

slate swan
#

I've done this before anyway I just couldn't remember that well

boreal ravine
#

y judge people

#

🤨

slate swan
#

@drifting arrow stop spoonfeeding

final iron
#

Yall know any good asynchronous api wrappers for mojang api?

slate swan
drifting arrow
#

wot

wicked atlas
#

Top 2000 cheese

stiff nexus
#
    def lock_bro(self):

        if self.pages.cur_page == self.pages.total:
            self.children[0].disabled = False
            self.children[1].disabled = False

            self.children[2].disabled = True
            self.children[3].disabled = True

        elif self.pages.cur_page == 1:
            self.children[0].disabled = True
            self.children[1].disabled = True

            self.children[2].disabled = False
            self.children[3].disabled = False

        elif 1 < self.pages.cur_page < self.pages.total:
            for b in self.children:
                b.disabled = False
``` why is it disabling the stop button
https://media.discordapp.net/attachments/829947392651427860/887526753587839036/unknown.png
wicked atlas
#

Because of ```py
self.children[2].disabled = True
self.children[3].disabled = True

#

Did you perhaps mean

            self.children[3].disabled = True
            self.children[4].disabled = True
stiff nexus
#

oh

#

thx @wicked atlas

#

also do u know how to do this page number button thing?

wicked atlas
#

I would say that is just setting the label of the buttons, plus an emoji

wicked atlas
#

Make sure you make the change in your elif too

stiff nexus
#

when i pressed the double left button

wicked atlas
#

            self.children[3].disabled = False
            self.children[4].disabled = False
stiff nexus
#

worked

#

i will tell if i get any error

lament mesa
jade jolt
#

sure

tame lynx
#

How to do embeds

#

Dk how do do it in Python

vale pendant
#

!d discord.Embed

unkempt canyonBOT
#

class discord.Embed(**kwargs)```
Represents a Discord embed.

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

Certain properties return an `EmbedProxy`, a type that acts similar to a regular [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.9)") except using dotted access, e.g. `embed.author.icon_url`. If the attribute is invalid or empty, then a special sentinel value is returned, [`Embed.Empty`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Embed.Empty "discord.Embed.Empty").

For ease of use, all parameters that expect a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") are implicitly casted to [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") for you.
tame lynx
#

thxthx

vale pendant
#

yeah ofc

tribal cove
#

is making music bots now banned, cant I even make my own ??

boreal ravine
slate swan
tribal cove
slate swan
#

cant then

hoary fog
#

i have a problem

slate swan
hoary fog
#

ImportError: cannot import name 'Player' from 'music_bot'

sick talon
#

How to make this drop down thing ?

fleet oracle
#
    async def servericon(self, ctx):
        icon = ctx.guild.icon.url
        if icon == None:
            await ctx.send('Este servidor no tiene ícono.')
        else:
            em = discord.Embed(title='Este es el ícono de este servidor.', color= discord.Color.red())
            em.set_image(url=icon)
            em.set_footer(text=f'Pedido por {ctx.author}', icon_url=f'{ctx.author.avatar.url}')

            await ctx.send(embed=em)```
#

Does it help how do I make when there is no icon, send a text saying so?

valid galleon
valid galleon
#

but most other features are already added

boreal ravine
valid galleon
boreal ravine
#

yeah ig rythm has dropdown menus which uses djs

visual island
valid galleon
#

java is the best for music bots, but its pretty bad for general ones

#

so most music bots used it

valid galleon
shell wing
#
@commands.Cog.listener()
    async def on_component(self, ctx: ComponentContext):
        if ctx.custom_id == 'c_ticket':
            overwrites = {
                ctx.guild.default_role:
                discord.PermissionOverwrite(read_messages=False),
                ctx.guild.me:
                discord.PermissionOverwrite(read_messages=True),
                ctx.author:
                discord.PermissionOverwrite(read_messages=True,
                                            send_messages=True)
            }
            channel = discord.utils.get(ctx.guild.channels,
                                             name=f'{ctx.author.name} ticket',
                                             overwrites=overwrites)
            
            if channel is not None:
                    await ctx.guild.create_text_channel(
                f'{ctx.author.name} ticket', overwrites=overwrites)
            else:
                await ctx.send("You've already created a ticket please close it to make a new one", hidden=True)
``` it straight away jumps to `else` statement
and like here i wanna check that if that user already has a channel or not
frosty prairie
#

:/ whats wrong

grim oar
#

What error

#

The user was not found, probably recheck the id

brisk helm
#
member = ctx.guild.get_member(id here)
await member.send("text")```
slate swan
#
u = await bot.fetch_user(id)
await u.send("dm")
grim oar
#

Also check if you are passing the id as int

grim oar
#

Uhh i won't recommend doing it like that, but most probably the member isn't cached

#

!d discord.Guild.fetch_member

unkempt canyonBOT
#

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

Retrieves a [`Member`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Member "discord.Member") from a guild ID, and a member ID.

Note

This method is an API call. If you have [`Intents.members`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Intents.members "discord.Intents.members") and member cache enabled, consider [`get_member()`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Guild.get_member "discord.Guild.get_member") instead.
grim oar
#

Try using it

slate swan
#

anyone wanna collab in my bots rewrite?

grim oar
#

Also do you have intents enabled

shell wing
#

    @commands.Cog.listener()
    async def on_component(self, ctx: ComponentContext):
        if ctx.custom_id == 'c_ticket':
            overwrites = {
                ctx.guild.default_role:
                discord.PermissionOverwrite(read_messages=False),
                ctx.guild.me:
                discord.PermissionOverwrite(read_messages=True),
                ctx.author:
                discord.PermissionOverwrite(read_messages=True,
                                            send_messages=True)
            }
            channel = discord.utils.get(ctx.guild.channels,
                                             name=f'{ctx.author.name} ticket',
                                             overwrites=overwrites)
            
            if channel is not None:
                  await ctx.guild.create_text_channel(
                    f'{ctx.author.name} ticket', overwrites=overwrites)
            else:
                  await ctx.send("You've already created a ticket please close it to make a new one", hidden=True)
```it like straight away jumps to `else`
slate swan
#

maybe its because your channel var is inside an if statement, idk much about this, but it must be that channel is None

#

nvm i think its not the problem

#

but python must recognize channel as None

#

so, your channel here doesnt return anything successfully, try checking your code again

visual island
shell wing
visual island
#

if channel is not None means that channel exists already, instead do you mean if channel is None?

shell wing
#

is None...ill try it

shell wing
visual island
#

new code?

#

and what library are you using anyway?

shell wing
# visual island new code?
channel = discord.utils.get(ctx.guild.channels,
                                             name=f'{ctx.author.name} ticket')
            
            if channel is None:
                  channell = await ctx.guild.create_text_channel(
                    f'{ctx.author.name} ticket', overwrites=overwrites)
                  tickty = discord.Embed(
                  title=f"Ticket for {ctx.author.name}",
                  description=
                  "`Close` for closing the ticket \n `Save` for saving the ticket in `Archived Tickets` requires admin permissions (Please dont change the name of the channel and the category",
                  color=0x530101)
                  
                      create_actionrow(
                          create_button(style=ButtonStyle.red,
                                        label="Close",
                                        custom_id="c_close"),
                          create_button(style=ButtonStyle.green,
                                        label="Save",
                                        custom_id="c_save"))
                  ]
                  await ctx.send(embed=newticket, hidden=True)
                  await asyncio.sleep(1)
                  await channell.send(f"{ctx.author.mention}",
                                    embed=tickty,
                                    components=components)
            else:
                  await ctx.send("You've already created a ticket please close it to make a new one", hidden=True)```
shell wing
visual island
slate swan
#

anyone wanna collab in my bots rewrite

shell wing
shell wing
slate swan
#

an economy, im planning to use sqlite for it. over 1.5k lines of code as the old bot

#

fyi

shell wing
#

economy bot...cant help it lol

slate swan
#

oh ok

#

collab with me i have ||nuke bot||

#

ive used a nuke bot before

shell wing
slate swan
#

ducky_angel 💣

shell wing
slate swan
#

ducky_australia 🔫

#

btw why cant you collab with an economy bot

shell wing
#

i can make the bot look good and other commands

slate swan
#

oh well rip then

#

the main focus is the data lol

shell wing
shell wing
slate swan
#

but have you ever worked with sql before

sweet merlin
#

how do i reply in event?

@bot.event
async def on_message(message):
    if  message.content.startswith('hi'):
        await message.channel.send('hello!')
    await bot.process_commands(message)```
i want to change "message.channel.sned('hello!')" to reply the author of the message
shell wing
slate swan
#

oh well rip then

shell wing
slate swan
#

duck kis

shell wing
sweet merlin
#

thanks

sweet merlin
maiden fable
#

message.author.mention

grim oar
#

ping the author using the reply or just mention them?

maiden fable
#

mention_author=True

shell wing
#
channel = discord.utils.get(ctx.guild.channels,
                                             name=f'{ctx.author.name} ticket')
            
            if channel is None:
                  channell = await ctx.guild.create_text_channel(
                    f'{ctx.author.name} ticket', overwrites=overwrites)
                  
            else:
                  await ctx.send("You've already created a ticket please close it to make a new one", hidden=True)
```the `else` aint working its still creating channels even though it exists
sweet merlin
#
@bot.event
async def on_message(message):
    if  message.content.startswith('hi'):
        await message.reply('hello!')
    await bot.process_commands(message)```
i want to make the message that start with hi, Hi, hI(like allow caplock)
slate swan
#

{ctx.author.name} ticket are u sure this is a valid channel name? @shell wing

grim oar
#

message.content.lower().startswith

maiden fable
sweet merlin
#

ok thanks

maiden fable
slate swan
#

can anyone suggest a fun command, i will try to make it

shell wing
slate swan
#

i thought discord channels have dashes

#

wat

maiden fable
#

Isn't that what I said....?

shell wing
maiden fable
#

-ticket not ticket

shell wing
shell wing
shell wing
#

and well there are sometimes spaces in user names too...so ig that they are causing an issue ??

maiden fable
#

Yea

#

!d str.replace use this

unkempt canyonBOT
#

str.replace(old, new[, count])```
Return a copy of the string with all occurrences of substring *old* replaced by *new*. If the optional argument *count* is given, only the first *count* occurrences are replaced.
shell wing
#

count...

slate swan
#
str(ctx.author).replace(" ", "-")

this should work

maiden fable
#

Yea

shell wing
slate swan
#

thats useless, but in cases when the object isnt a string itd be handy

#

you can remove them if u want

shell wing
#

it aint working..ill try to do the count one

maiden fable
#

Don't

shell wing
sweet merlin
#

message.content.contains()
it wont work

maiden fable
#

@slate swan BTW you need only 14 Boosts for Level 3 now

slate swan
maiden fable
#

Idk

slate swan
#

wanna collab in my bots rewrite

sweet merlin
shell wing
maiden fable
maiden fable
slate swan
#

economy, im planning to use sqlite for it, over 1.5k lines of code as the old bot

shell wing
slate swan
#

dm if interested, ill ask about the timezone

maiden fable
maiden fable
slate swan
#

so you cant collab rite

sweet merlin
maiden fable
#

Yea, not nowadays

slate swan
#

oh rip then

#

alr

maiden fable
maiden fable
slate swan
#

the old code?

maiden fable
slate swan
#

well we will commit to a repo, but im not hosting the bot on github tho

#

hello hunter

#

the old code, yes

maiden fable
#

Try printing the channel name in your code. I am damn sure it will be different cz of unicode

slate swan
#

so wanna collab?

#

gtg now dm if u want to

maiden fable
#

Sure. But I don't think I will be able to cz me noon in dpy

slate swan
maiden fable
slate swan
#

do u remember me

maiden fable
#

I didn't notice that message

slate swan
#

nice

maiden fable
slate swan
#

do u remember textbook

maiden fable
#

Mhm

#

U his alt or something?

slate swan
#

yeh lost that account

maiden fable
#

Ah

shell wing
shell wing
maiden fable
#

Hmm

shell wing
maiden fable
#

So the unicode is correct

shell wing
#

prob yes lol

shell wing
maiden fable
#

Well

#

I don't really know tbh

#

Can I see the code again?

#

Where u check for an existing channel?

shell wing
# maiden fable Where u check for an existing channel?
channel = discord.utils.get(ctx.guild.channels,
                                             name=f'{ctx.author.name}-ticket')
            
            if channel is None:
                  channell = await ctx.guild.create_text_channel(
                    f'{ctx.author.name}-ticket', overwrites=overwrites)
                  print (str(channell))
            else:
                await ctx.send("nahi")
maiden fable
#

Bruh

#

Wait I got it

shell wing
#

ok lol

maiden fable
#

f"{ctx.author.name.replace(" ", "-")}-ticket"

shell wing
maiden fable
#

DUDE WTF

shell wing
slate swan
#

Hi How do you make a discord bot with python? (PLEASE DM OR PING ONCE YOU REPLY)

shell wing
#

im tired of this now

#

thanks for the help

maiden fable
#

Yea take care man

shell wing
sweet merlin
#

how do i make the bot cant reply his own message?

stark bobcat
#

hi

slate swan
stark bobcat
#

u remember me

#

i'm yoda

slate swan
#

zero idea

#

ah

#

got it

stark bobcat
#

(:

slate swan
#

:)

ocean leaf
#

can someone pls help me?

ocean leaf
slate swan
ocean leaf
sweet merlin
stark bobcat
#

!resources

unkempt canyonBOT
#
Resources

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

ocean leaf
sweet merlin
slate swan
ocean leaf
sweet merlin
#

how do i make 2 command to one reply?

elif 'rip bozo' or 'ripbozo' in message.content.lower():
            await message.reply('https://tenor.com/view/rip-bozo-ripus-bozus-nik0321-unlive2774-potato-chip-smoker-bozo-gif-21079712')``` but it didnt work, it will reply all word and other character
unkempt canyonBOT
#

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

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

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

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

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

# ...or like this.
if favorite_fruit in ('grapefruit', 'lemon'):
    print("That's a weird favorite fruit to have.")
sweet merlin
maiden fable
#

That's the prefix. But read the embed please

sweet merlin
#

ok

slate swan
#

Is their a module to keep command logs of your discord bot?

maiden fable
sweet merlin
maiden fable
#

!d discord.on_command @slate swan

unkempt canyonBOT
#

discord.on_command(ctx)```
An event that is called when a command is found and is about to be invoked.

This event is called regardless of whether the command itself succeeds via error or completes.
slate swan
sweet merlin
maiden fable
#

Ah

sweet merlin
maiden fable
#

Bro... Why said to add !or to yr code?

sweet merlin
sweet merlin
#

im confusee

ocean leaf
#

pls help

sweet merlin
#

in bot.latency
try use client or something that you write on
bot = commands.Bot(command_prefix='>')

#

if u write it client = commands.Bot(blablabla) then use client

#

if u write bot then use bot

#

kk

slate swan
ocean leaf
#

plsssss

sweet merlin
#

it will do this

ocean leaf
sweet merlin
slate swan
sweet merlin
#

a?

#

after i using rip bozo trigger the bot will reply all characters

#
elif 'rip bozo' or 'ripbozo' in message.content.lower():
            await message.reply('https://tenor.com/view/rip-bozo-ripus-bozus-nik0321-unlive2774-potato-chip-smoker-bozo-gif-21079712')```
slate swan
ocean leaf
meager whale
sweet merlin
meager whale
sweet merlin
slate swan
sweet merlin
#

because you use clients = commands.Bot(command_prefix="*")

ocean leaf
sweet merlin
slate swan
meager whale
slate swan
#
@client.command()
async def banner(ctx, *,  bannermember : discord.Member=None):
    if bannermember == None:
     bannermember = ctx.author
    userBannerUrl = bannermember.banner_url
    embed = discord.Embed(title=f"{ctx.author}'s banner", color=0x030203)
    embed.set_image(url=user.banner.url)
    await ctx.send(embed=embed)
#

what did i do wrong

meager whale
#

Guys my bot is now working like it says that bot is ready but its responding

#

Like I created a command by which whenever I say hello the bot will say hi but the bot is not responding

slate swan
unkempt canyonBOT
#

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

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

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

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

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

Add that at the bottom of your on_message event

meager whale
#

Umm can you send screenshot

slate swan
slate swan
#

Do u have an on_message event

slate swan
slate swan
#

user instead of member?

#

No

#

That attribute doesn't exist

#

so what should i do

#

It's .banner.url

meager whale
#

This is my code, now where shall I add it

slate swan
#

.banner returns an asset object

slate swan
slate swan
#

Did u restart

#

And use your prefix

#

Did u restart

#

Bro my internet 😭😭

slate swan
meager whale
#

@slate swan my error is fixed

#

I was not using the prefix

slate swan
#

¯\_(ツ)_/¯

sweet merlin
slate swan
#

hello

#

i wanted to ask something

#

what does "@client.event" mean?

slate swan
slate swan
sweet merlin
#

never try that

slate swan
#

¯\_(ツ)_/¯

slate swan
slate swan
#

can someone also tell me what "async" means?

sweet merlin
# slate swan can someone also tell me what "async" means?

When you have an asynchronous function (coroutine) in Python, you declare it with async def, which changes how its call behaves. In particular, calling it will immediately return a coroutine object, which basically says "I can run the coroutine with the arguments you called with and return a result when you await me"
from google

slate swan
sweet merlin
slate swan
#

It should work

#

¯\_(ツ)_/¯

sweet merlin
#

no?

#

i think space is a string too

#

i did run "hi" and " hi" and it still wont work

slate swan
#

Did u restart too

sweet merlin
#

ye

sweet merlin
slate swan
#

Weird

maiden fable
#

How to check who invoked the help command with commands.HelpCommand?

#

wait nvm. prepare_help_command can be used

hoary gust
#

@maiden fable help

maiden fable
#

Yea?

hoary gust
#

Is it necessary to run the dashboard and the bot on the same machine to use ipc

maiden fable
#

no

hoary gust
#

I got a error

maiden fable
#

???

hoary gust
#

@maiden fable

maiden fable
#

I never used ipc, so cannot help you, Sorry

hoary gust
#

Ah ok

errant shuttle
#

@hoary gust

hoary gust
#

Here

errant shuttle
#

idk if i can actually help u

hoary gust
#

@errant shuttle I need help regarding ipc

errant shuttle
#

but i could try

hoary gust
errant shuttle
#

hmmmmm

untold token
#

If you pass an empty string

#

It would work

#

But make sure its
""

#

Not
" "

#

That space matters

hoary gust
#

Someone help

untold token
hoary gust
#

No I am using ipc to make my dashboard@untold token

untold token
#

And then it would work

untold token
hoary gust
#

Yep

untold token
untold token
#

To the port you defined to

hoary gust
#

U mean I have issue with the port?@untold token

untold token
#

Yes, most likely

#

Whatever you are trying to connect is not properly hosted on port 2000

hoary gust
#

But my port is something like 54316

sweet merlin
untold token
#

That's why aiohttp cannot connect to it

untold token
hoary gust
#

@untold token u mean I need to set my port as 20000

untold token
#

Yes

#

Not 20000

#

2000

hoary gust
#

Well there is 20000 written@untold token

untold token
#

Port 2333
Port 3030

#

Are the common ones

untold token
dim vapor
untold token
#

Code?

dim vapor
# untold token Code?

code for current inter edit where self_inter is inter.message

await self_inter.edit(content=">>> **`>` Select the games you play!**\n_ _", components=[row1, row])

(switching to disnake.py(forked from discord.py))

untold token
#

Well then refer docs

dim vapor
#

its not there

untold token
#

Of disnake

dim vapor
#

:/

untold token
#

Well ask support for it on github I guess

#

I don't know about that library

dim vapor
untold token
#

I only know about nextcord

untold token
dim vapor
#

oh

untold token
#

Message should be the message object

dim vapor
#

ya

untold token
#

!d discord.Message.edit

unkempt canyonBOT
#

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

Edits the message.

The content must be able to be transformed into a string via `str(content)`.

Changed in version 1.3: The `suppress` keyword-only parameter was added.
dim vapor
#

i get "Unknown Message"

velvet tinsel
#

Cool

untold token
#

Well its ephemeral

dim vapor
#

for ephemeral message alone

dim vapor
untold token
#

That message is temporary

dim vapor
#

agg

#

so like how can i edit it when its in that temp time

untold token
#

It doesn't edit the message

#

It just sends a new ephemeral message

#

If it would have edited it, there should be a sign that says edited

dim vapor
#

oh but how does it dismiss the previous one?

untold token
#

Like this.

dim vapor
dim vapor
untold token
#

Editing ephemeral message isn't possible, idts

dim vapor
#

ya i get it

untold token
dim vapor
#

but liek sending new one and dismissign the previous one is possable?

untold token
#

Refer to docs of disnake

dim vapor
#

bcause disnake is like exactly similar to the original discord.py

#

or ig i will switch to nextcord

untold token
#

I have never used ephemeral messages really

untold token
meager whale
#

How can I make a welcome command for my discord bot

untold token
#

You would still need to figure out

dim vapor
#

hmm

#

let me check now ig

untold token
meager whale
untold token
#

The db will store channel where the welcome messages need to send

#

For eg

#
@bot.listen() # decorator that listen for events
async def on_member_join(member):
   channel = bot.get_channel(welcome_channel_ID) # the channel ID where the welcome messages need to be send.
# this method will get channel object from the ID of channel
   await channel.send("Member joined")```
#

This is a simple example of on_member_join event

hoary gust
#

@untold token

untold token
#

Can you show your code?

hoary gust
shell wing
#
@commands.Cog.listener()
    async def on_component(self, ctx: ComponentContext):
        if ctx.custom_id == 'c_ticket':
            overwrites = {
                ctx.guild.default_role:
                discord.PermissionOverwrite(read_messages=False),
                ctx.guild.me:
                discord.PermissionOverwrite(read_messages=True),
                ctx.author:
                discord.PermissionOverwrite(read_messages=True,
                                            send_messages=True)
            }
            channel = discord.utils.get(ctx.guild.channels,
                                             name=f'{ctx.author.name} ticket')
``` how do i add cooldown on this ??
hasty iron
#

honestly, you should just use 2.0

shell wing
shell wing
hasty iron
#

yes you

shell wing
#

oh

#

discord-components is 2.0

hasty iron
#

views will make your life alot easier

#

discord-components isnt 2.0

hoary gust
#

@hasty iron help

#

i got another kind of error

hasty iron
#

what kind of error

shell wing
hoary gust
shell wing
#

but like can u tell me how to solve it ?

hasty iron
hoary gust
hasty iron
#

how about

#

we see the code

untold token
hoary gust
#

ok

shell wing
#
 if time_difference < 120:
          if ctx.custom_id == 'c_ticket':
              
``` this wont work right ?
untold token
#

The code where you are connecting with

hoary gust
#

well i took help from a tutorial, so plz dont get angry on me cause i am just learning how to work with ipc

@app.route("/dashboard")
async def dashboard():
    if not await discord.authorized:
        return redirect(url_for("login")) 

    guild_count = await ipc_client.request("get_guild_count")
    guild_ids = await ipc_client.request("get_guild_ids")

    user_guilds = await discord.fetch_guilds()

    guilds = []

    for guild in user_guilds:
        if guild.permissions.administrator:            
            guild.class_color = "green-border" if guild.id in guild_ids else "red-border"
            guilds.append(guild)

    guilds.sort(key = lambda x: x.class_color == "red-border")
    name = (await discord.fetch_user()).name
    return await render_template("dashboard.html", guild_count = guild_count, guilds = guilds, username=name)

@untold token@hasty iron

hasty iron
#

your server returned an invalid status code response when the client sent a request to connect i guess?

hasty iron
#

your server should return a 101(?) switching protocols http status code response

hoary gust
hasty iron
#

and by server and client i mean ipc ofc

hoary gust
#

except the dashboard route and the login

hasty iron
#

also can you send the full error

hoary gust
hoary gust
#

@hasty iron

#
guild_count = await ipc_client.request("get_guild_count")

this line is causing the error

untold token
#

What's the error

knotty barn
#

pls bal

#

oops

boreal ravine
#

idk what ipc is but why is get guild count a string

#

o nvm

hoary gust
#

@untold token

untold token
#

Invalid response status hmm

hoary gust
heavy radish
#

Where's somewhere I can save my code? Like on discord I can't send a lot of words

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

hoary gust
#

@untold token in the console bot didnt print that the server is ready but why

#

isint is supposed to be ready on its own

#

?

untold token
#

Well, I don't really get why its showing that

heavy radish
#

Hm....okay! I will try it out

hoary gust
# untold token Well, I don't really get why its showing that

bot is just printing that it is online but not the ipc server

class MyBot(commands.Bot):

    def __init__(self,*args,**kwargs):
        super().__init__(*args,**kwargs)

        self.ipc = ipc.Server(self,secret_key = "zzz")

    async def on_ready(self):
        """Called upon the READY event"""
        print("Bot is ready.")

    async def on_ipc_ready(self):
        """Called upon the IPC Server being ready"""
        print("Ipc server is ready.")

    async def on_ipc_error(self, endpoint, error):
        """Called upon an error being raised within an IPC route"""
        print(endpoint, "raised", error)

untold token
#

Hmm try
self.wait_until_ready() method

#

!d discord.ext.commands.Bot.wait_until_ready

unkempt canyonBOT
#

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

Waits until the client’s internal cache is all ready.
hoary gust
untold token
#

Not bot

hoary gust
#

ok

untold token
#

self is already bot instance that you subclassed

hoary gust
#

self.wait_until_ready(MyBot)

untold token
#

No....

#

Read the docs please

hoary gust
maiden fable
#

And read about some OOP also

hoary gust
#

i need to do bot not self

untold token
#

You subclassed commands.Bot as MyBot

hoary gust
#

its the main file not any cog

hoary gust
slate swan
untold token
#

^

maiden fable
#

Yea

untold token
hoary gust
#

well can u plz tell me what should i do for now cause i will learn about OOP but a bit later

maiden fable
#

Bro...

slate swan
#

Why do people keep getting in libs that aren't easy for beginners and require some knowledge when they have 0 knowledge of python like bruh

maiden fable
#

You are tryna drive a car without knowing how to change the gears, no offense

hoary gust
#

i got the issue

#

lemme fix this

untold token
#

Your IPC isn't connecting because your bot and ipc both are trying to connect at the same time

hoary gust
#

i forgot to start the server

#

lol

untold token
#

self.wait_until_ready would make your code wait until the bot ready and then ipc will connect

hoary gust
untold token
#

Oh okay

shell wing
#
@commands.Cog.listener()
    async def on_component(self, ctx: ComponentContext):
        time_difference = (datetime.datetime.utcnow() - self.last_timeStamp).total_seconds()
        if time_difference < 120:
          time_difference = (datetime.datetime.utcnow() - self.last_timeStamp).total_seconds()
            #rest code
         else:
            await ctx.send("sry cant")
``` it straight away jumps to `else`
fading granite
#

Can someone suggest me a good video for learning about Cogs in discord.py

heavy folio
#

hi, anyone has any idea how to use tagscript in discord.py? searched youtube and cant find anything. i wanna try and allow people to make custom commands

maiden fable
#

Try seeing the documentation folder

stark bobcat
#

hi

maiden fable
#

Ah hey there again BugCat!

stark bobcat
#

Hey

maiden fable
#

Hi

hoary gust
#

@untold token is it necessary to run the bot and the dashboard on the same machine to run the ipc

sick talon
#
@help.command()
  async def lock(self, ctx):
    colors = [0xFFE4E1, 0x00FF7F, 0xD8BFD8, 0xDC143C, 0xFF4500, 0xDEB887, 0xADFF2F, 0x800000, 0x4682B4, 0x006400, 0x808080, 0xA0522D, 0xF08080, 0xC71585, 0xFFB6C1, 0x00CED1]
    em13 = discord.Embed(title="Lock :lock:",description="A lock command through which the admin,mods of the server can lock the text channels of the server",color = random.choice(colors))
    em13.add_field(name="__**NOTE**__",value="You will require mod or admin role to run this command")
    em13.add_field(ame="__**Syntax**__",value="`fl.lock [channel] (reason)`")
    await ctx.send(embed=em13)

bot isnt responding to fl.help lock but i have coded fl.help mute in the similar manner and bot is responding to that idk why ?

  #Help mute command
  @help.command()
  async def mute(self, ctx):
    colors = [0xFFE4E1, 0x00FF7F, 0xD8BFD8, 0xDC143C, 0xFF4500, 0xDEB887, 0xADFF2F, 0x800000, 0x4682B4, 0x006400, 0x808080, 0xA0522D, 0xF08080, 0xC71585, 0xFFB6C1, 0x00CED1]

    em10 = discord.Embed(
    title="Mute 🔇",
    description="A mute command through which the admin,mods of the the server can mute the server members",
    color = random.choice(colors)
    )
    em10.add_field(name="__**NOTE**__",value="You will require mod or admin role to run this command")
    em10.add_field(name="__**Syntax**__", value="`fl.mute [user] (reason)`")
    await ctx.send(embed=em10)
stark bobcat
#

Don't know what you mean by bugcat but sure

maiden fable
#

The name of the person

stark bobcat
#

oh

#

mb

hasty iron
maiden fable
unkempt canyonBOT
#

class discord.ext.commands.HelpCommand(**options)```
The base implementation for help command formatting.

Note

Internally instances of this class are deep copied every time the command itself is invoked to prevent a race condition mentioned in [GH-2123](https://github.com/Rapptz/discord.py/issues/2123).

This means that relying on the state of this class to be the same between command invocations would not work as expected.
hoary gust
maiden fable
maiden fable
hasty iron
#

then whats the point of the ipc

sick talon
hasty iron
#

ipc lets you connect between two programs on the same machine

maiden fable
hasty iron
#

thats still ipc?

hoary gust
hasty iron
#

well discord.ext.ipc connects and starts a server on localhost so yes

maiden fable
hasty iron
#

you need it to be on the same machine

hasty iron
#

literally anything between 2 programs

maiden fable
hoary gust
#

well i have a main bot file and a backend file so how will i run 2 files at a time

sick talon
hoary gust
hasty iron
#

actually, you're using quart right?

hoary gust
#

@hasty iron

hasty iron
#

wait

hoary gust
#

ok

#

waiting

hasty iron
#

ok so quart.Quart has the run_task function

#

you can do something like

hoary gust
sick talon
#
  #Lock command
  @commands.command(case_insensitive = True)
  @commands.has_any_role(885434191783788564, 856071314740740096, 856061783722426378, 856465667296985108)
  async def lock(self, ctx, channel: discord.TextChannel=None, *, reason=None): 
    channel = channel or ctx.channel
    overwrite = channel.overwrites_for(ctx.guild.default_role)
    if overwrite.send_messages == True:
      overwrite.send_messages = False
      await channel.set_permissions(ctx.guild.default_role, overwrite=overwrite)
      em_reason = discord.Embed(title="**Channel locked**", description=f":lock: {reason}",color=discord.Color.red())
      embed = discord.Embed(description = f":fl_check: Locked channel <#{channel.id}>",color=discord.Color.green())
      await ctx.send(embed=em_reason)
      await ctx.send(embed=embed)
    elif overwrite.send_messages == False:
      em = discord.Embed(description=":fl_no: That channel is already locked.", color=discord.Color.red())
      await ctx.send(embed=em)

bot is ignoring this command as well :(
but there is no error popping in the console :lemon_angrysad:
@maiden fable

hasty iron
#

webserver.py


# do routing stuff here

async def run():
  await app.run_task(*args, **kwargs)

bot.py

import webserver

# bot stuff

bot.loop.create_task(webserver.run())
bot.run()
maiden fable
#

Do u have an error handler?

hasty iron
#

then you can run bot.py and it would run the web server too

sick talon
maiden fable
#

Wait

#

Do u have an else clause?

sick talon
maiden fable
#

?

sick talon
maiden fable
#

Cool

meager whale
#

Hey guys

#

I wanna learn how to make a Music bot

maiden fable
meager whale
#

Oh ok

#

Sorry

#

Pls don't ban me

hasty iron
#

unless you use your own music

#

and only ncs music

meager whale
#

Ohk

#

Soooo @hasty iron I am a Music producer so what if I use my music and songs from NCS

hasty iron
#

then you can freely make a music bot without breaking any tos or laws

meager whale
#

Ok

#

Thanks 😄

hasty iron
#

yes?

hoary gust
hasty iron
#

the positional and keyword arguments that that function takes

hoary gust
hasty iron
#

?

#

just read the docs

hoary gust
#

i mean what args shall i keep there

hasty iron
#

read the docs

hoary gust
hasty iron
#

....

#

quart docs

hoary gust
#

ok lemme

slate swan
#

Any who can help it not send gif?

maiden fable
#

!d discord.File

unkempt canyonBOT
#

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

Note

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

It takes two args

hasty iron
#

they have the args correct

#

filename is optional

maiden fable
#

Ah yea. Saw that after running the command. Mb

hoary gust
hasty iron
#

app.run blocks

#

app.run_task has the exact same arguments

hoary gust
#

ok

dapper cobalt
#

I really should stick to discord.py, because this isn't code, this is crap.

hasty iron
#

its called "another language other than python that uses a difference coding style"

hoary gust
#

@hasty iron

hasty iron
#

your ipc server is running on that port

#

why are you setting your webserver's port to 20000?

#

it should be 8080 or 8888

hoary gust
hasty iron
#

what

hoary gust
#

yes

hasty iron
#

that doesnt make sense, your webserver should be running on 8080

hoary gust
slate swan
#

using elif and receiving "Expected expression Pylance"

#

what am i doing wrong

hasty iron
#

who knows

#

would be good if we saw the code

slate swan
#

@client.event() async def on_message(message): username = str(message.author).split('#')[0] user_message = str(message.content) if message.channel.name == 'chat': if user_message.lower() == 'hello': await message.channel.send(f'Sup {username}?') elif user_message.lower == 'bye': await message.channel.send(f'Later {username}!')

sick talon
#

hey hi
umm..
so the lock is working but it isn't locking the channel where i am running the channel like for example i am running the command in #general so fl.lock #general this isnt working but for example i ran the command in #staff-chat fl.lock #general this is working

  #Lock command
  @commands.command(case_insensitive = True)
  @commands.has_any_role(885434191783788564, 856071314740740096, 856061783722426378, 856465667296985108)
  async def lock(self, ctx, channel: discord.TextChannel=None, *, reason=None): 
    channel = channel or ctx.channel
    overwrite = channel.overwrites_for(ctx.guild.default_role)
    if overwrite.send_messages == True:
        overwrite.send_messages = False
        await channel.set_permissions(ctx.guild.default_role, overwrite=overwrite)
        em_reason = discord.Embed(title="**Channel locked**", description=f":lock: {reason}",color=discord.Color.red())
        embed = discord.Embed(description = f":fl_check: Locked channel <#{channel.id}>",color=discord.Color.green())
        await ctx.send(embed=em_reason)
        await ctx.send(embed=embed)
    elif overwrite.send_messages == False:
      em = discord.Embed(description=":fl_no: That channel is already locked.", color=discord.Color.red())
      await ctx.send(embed=em)

umm.. so whats the issue ?

maiden fable
slate swan
#

Indentation is not the best either

slate swan
slate swan
unkempt canyonBOT
#
Resources

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

sick talon
#

getting this error when trying to make a missing required arugment error handler

AttributeError: module 'discord.ext.commands' has no attribute 'MissingRequiredArugment
slate swan
valid niche
#

!d discord.ext.commands.MissingRequiredArgument

unkempt canyonBOT
#

exception discord.ext.commands.MissingRequiredArgument(param)```
Exception raised when parsing a command and a parameter that is required is not encountered.

This inherits from [`UserInputError`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.UserInputError "discord.ext.commands.UserInputError")
valid niche
#

that's how you spell it

sick talon
#

ohh ok

slate swan
#

thoughts ?

maiden fable
#

Good

brave vessel
stark bobcat
#

is it possible to make a argument optional

brave vessel
slate swan
#

=None

brave vessel
untold token
slate swan
#

if member is None

brave vessel
#

You can also use typing.Optional

untold token
#
async def func(ctx,* ,args=None): 
   ...```
stark bobcat
untold token
stark bobcat
untold token
#

Argument args would be optional so if you don't pass any thing, it would be None

stark bobcat
#

oh

#

ok thanks

untold token
#

So if an user types the command sui

#

You want to make user say F ?

#

Oh you want to pay respect to someone? Like another user?

#

So you need to use context for this

ctx.author aka Context.author returns the Member object of who ever invoked the command

#

So

#

For example

#
@bot.command()
async def somecommand(ctx):
  await ctx.send(f"{ctx.author} used this command")```
#

The first argument of the function takes ctx aka context object
.author attribute returns member object of who invoked the command and in an f string it shows their name and tag and the message where command was invoked ctx.send()

#

Hm np

boreal ravine
#
  await ctx.send(f"{ctx.author} payed respects to {member.name}")
untold token
#

It would raise a syntax error

boreal ravine
#

define if then

untold token
#

That means you didn't define bot

boreal ravine
#

!d discord.ext.commands.Bot

unkempt canyonBOT
#

class discord.ext.commands.Bot(command_prefix, help_command=<default-help-command>, description=None, **options)```
Represents a discord bot.

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

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

help????

import psutil
class about(discord.ui.View):
    @discord.ui.button(label='About', style=discord.ButtonStyle.blurple)
    async def func(self, button: discord.ui.Button, interaction: discord.Interaction):
        owner = self.bot.get_user(862906093373751337)

        total_memory = psutil.virtual_memory().total >> 20
        used_memory = psutil.virtual_memory().used >> 20
        cpu_used = str(psutil.cpu_percent())
        chnl_count = Counter(map(lambda ch: ch.type, self.bot.get_all_channels()))
        total_members = sum(g.member_count for g in self.bot.guilds)
        cached_members = len(self.bot.users)
        guild_value = len(self.bot.guilds)
        

        i = discord.Embed(description=f"**Running since:** {discord.utils.format_dt(self.bot.user.created_at, style = 'R')}\n**Uptime since:** <t:{int(self.bot.launch)}:R>",timestamp=datetime.utcnow(),colour=0xffffff)
        i.add_field(name="System",value=f"**RAM**: `{used_memory} MB`/`{total_memory} MB`\n**CPU:** `{cpu_used}%` used")
        i.add_field(name="Members",value=f"Total `{total_members:,}`\nCached `{cached_members:,}`")
        i.add_field(name="Servers", value=f"Total `{guild_value}` guilds")
        i.add_field(name="Channels",value=f"Total `{chnl_count[discord.ChannelType.text] + chnl_count[discord.ChannelType.voice]:,}`\nText `{chnl_count[discord.ChannelType.text]:,}`\nVoice `{chnl_count[discord.ChannelType.voice]:,}`",)
        i.add_field(name=f"Version", value=f":python: Python `{str(sys.version).split(' ')[0]}`\n:dpy~1:  Discord.py `{discord.__version__}`")

        i.set_author(name=ctx.author, icon_url=ctx.author.display_avatar)
        i.set_thumbnail(url=self.bot.user.display_avatar)
        i.set_footer(text=f"Made with :heart: by {owner}",icon_url=owner.display_avatar)
        await interaction.response.send_message(embed=i, ephemeral=True)
await ctx.send("tt",view=about())
#
Ignoring exception in view <about timeout=180.0 children=1> for item <Button style=<ButtonStyle.primary: 1> url=None disabled=False label='About' emoji=None row=None>:
Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ui/view.py", line 359, in _scheduled_task
    await item.callback(interaction)
  File "<repl>", line 6, in func
AttributeError: 'about' object has no attribute 'bot'
hasty iron
#

overload the __init__ and add the bot argument to it and set it as an attribute

dapper cobalt
hasty iron
#

and when you instantiate the view, do about(bot=self.bot) or whatever

dapper cobalt
#
class about(discord.ui.view):
  def __init__(self, bot):
    self.bot = bot
untold token
#

Yeah you didn't add the bot argument

hasty iron
#

nice spoonfeed

dapper cobalt
untold token
#

Eh it's not really spoonfeed lol

boreal ravine
hasty iron
#

cross post lol

untold token
#

Crossposting 🍋

drifting arrow
#

@boreal ravine

#

i crossposted your crosspost

rancid light
#

Hello

drifting arrow
boreal ravine
rancid light
boreal ravine
#

shitpost= ban ez

rancid light
rancid light
drifting arrow
#

@rancid light you spelled extension wrong

boreal ravine
#

extension

reef shell
high flame
rancid light
#

ohhh

high flame
#

if you want a list of strings you should do *args

rancid light
#

mb sry for the trouble

drifting arrow
# rancid light ohhh

dw happens to us all. we're cruising on by when we forget we have to know how to spell good and suddenly boom. mispell the word

#

this is why i use aliases.

untold token
#

,* ,

#

Is called consume rest operator

high flame
hasty iron
#

("x", "y")

untold token
#

If you pass multiple strings, it will take them all

hasty iron
#

*args is a tuple

untold token
high flame
#

but *, args is not a list

rancid light
high flame
#

self.bot == bot

#

um or no

#

show code

hasty iron
#

== is for comparision

rancid light
#

ok

valid perch
#

should be just 1

high flame
#

use =

hasty iron
#

= is for assignment

rancid light
#
import discord
from discord.ext import commands
import os

bot = commands.Bot(command_prefix = '-')

@bot.command()
async def load(ctx, extension):
    bot.load_extension(f'cogs.{extension}')

@bot.command()
async def unload(ctx, extension):
    bot.unload_extension(f'cogs.{extension}')    

for filename in os.listdir('D:\Coding\Python\Cogs_test\cogs'):
    if filename.endswith('.py'):
        bot.load_extension(f'cogs.{filename[:-3]}')  ```
high flame
#

show the cog

rancid light
#

in cogs

high flame
#

following youtube tutorials

rancid light
#
import discord
from discord.ext import commands

class Example(commands.Cog):

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

    @commands.Cog.listener()
    async def on_ready(self):
        print("Bot Ready!")    



    @commands.command()
    async def ping(self, ctx):
        await ctx.send("pong")

def setup(bot):
    bot.add_cog(Example(bot))      ```
drifting arrow
#

yeah

high flame
#

self.bot = bot

rancid light
drifting arrow
#

probs tech with tim

rancid light
#

ok

drifting arrow
#

"self.bot == bot" first error. single = is assigning, double is comparison

untold token
#

tech with Tim tuts are old

high flame
#

read the docs

rancid light
rancid light
drifting arrow
rancid light
#

i tried from this ^

drifting arrow
#

oh right yeah thats good too

hasty iron
#

docs have examples for cogs

#

you dont need vids

untold token
#

Lucas is old too

hasty iron
#

and if you couldnt understand the examples, you lack python knowledge

high flame
#

or use vcokltfre.dev

untold token
#

If you really want updated tutorials go watch carberra tutorials

untold token
warm terrace
#

how to make the song queue in the music discord bot, like if i want to play a song then queue another song, how do i do that ?

untold token
hasty iron
#

class*

#

!d asyncio.Queue

unkempt canyonBOT
#

class asyncio.Queue(maxsize=0)```
A first in, first out (FIFO) queue.

If *maxsize* is less than or equal to zero, the queue size is infinite. If it is an integer greater than `0`, then `await put()` blocks when the queue reaches *maxsize* until an item is removed by [`get()`](https://docs.python.org/3.10/library/asyncio-queue.html#asyncio.Queue.get "asyncio.Queue.get").

Unlike the standard library threading [`queue`](https://docs.python.org/3.10/library/queue.html#module-queue "queue: A synchronized queue class."), the size of the queue is always known and can be returned by calling the [`qsize()`](https://docs.python.org/3.10/library/asyncio-queue.html#asyncio.Queue.qsize "asyncio.Queue.qsize") method.

This class is [not thread safe](https://docs.python.org/3.10/library/asyncio-dev.html#asyncio-multithreading).
untold token
#

Ye this

#

You need to use the .getand .put methods to add / remove your songs

untold token
hasty iron
#

actually now i want to make my own Queue class lol

untold token
#

Good luck lol