#discord-bots

1 messages Β· Page 15 of 1

silk fulcrum
#

lemon is watching 😳

slate swan
#

over 90% webs use js either solo or with some other languages

primal token
#

people use html and css for something static and then they just use JS or TS ofc with libs depending

cold tide
cold tide
rain olive
#

it was just a reminder so yall dont get spanked by mods

#

but sure do wtv u want

cold tide
#

Well i dont mind.

eternal fox
#

Ok lads is there anyway to keep my discordbot online or just basically host it(im coding it in termux for fun)

primal token
#

can we go back to topic?

white aurora
#

vps

silk fulcrum
rain olive
cold tide
#

i use replit

eternal fox
#

Oh well my bad my bad

white aurora
#

replit sucks

rain olive
#

replit is the worst option

slate swan
cold tide
#

whats wrong w that 😭😭😭

cold tide
primal token
#

More like whats wrong with this chat.

rain olive
#

rate limits
shared ip

slate swan
cold tide
#

i mean on my phone i use pydroid.

slate swan
#

it has a long messages describing why Not to use replit

cold tide
#

Thats okay ig

eternal fox
#

oki thanks guys

cold tide
#

Yw loool

slate swan
#

How can i make a command that can stop this?

cold tide
#

i think pydroid is good for mobile hosting.

cold tide
slate swan
#

Stop the loop

cold tide
#

In what way

silk fulcrum
slate swan
cold tide
#

uhm break

primal token
slate swan
#

!d discord.ext.tasks.loop

unkempt canyonBOT
#

discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
silk fulcrum
#

also this yeah ^^

cold tide
#

break is the easiest @slate swan

#

But use that ^^^

slate swan
silk fulcrum
slate swan
#

okay you wanna break it but how will you do that loooli you can't access a variable in other function's scope until you make it global

cold tide
primal token
#

because somethings easy doesnt mean it should be considered an option.yert

slate swan
#

but that will keep you limited to only one person using the command at a time

cold tide
slate swan
#

Yes

silk fulcrum
#

how do you think will stop command work

primal token
slate swan
silk fulcrum
#

i dont get you, gl, im gonna try to fix this shit

eternal fox
# slate swan How can i make a command that can stop this?

try


count = 0
cont = True
@client.command()
async def count(ctx):
 while True:
    if cont is False:
        break
    elif cont is not False:
     time.sleep(1)
     await ctx.send(f"Number {count}")
     count += 1

@client.command()
async def stop(ctx):
  cont = False
  await ctx.reply("stopped.")
primal token
#

Just, why.

slate swan
#

Good?

silk fulcrum
#

second wtf...

eternal fox
#

πŸ˜€

cold tide
#

Why would you use that 😭

slate swan
#

third, what's the point of that command.

cold tide
#

even im dumb and i wouldnt

#

Missing your ":" too lol

slate swan
#

you can just provide an argument to the command for how many times you want that message to be sent

silk fulcrum
#

or time

#

but time = harder

slate swan
#

So what im going to do im eating at CHOE KING

eternal fox
slate swan
unkempt canyonBOT
#
Nope.

No documentation found for the requested symbol.

slate swan
#

!pip time-str

unkempt canyonBOT
cold tide
#

Could that work??

cold tide
#

Or not at all

slate swan
#

it will work.

cold tide
#

Yay im smart.

#

😭

primal token
#

Whats the point of the command either way lol

eternal fox
silk fulcrum
slate swan
#

i can think of an use-case, ||being annoying||

silk fulcrum
#

oop = good

cold tide
silk fulcrum
#

also logs are good

cold tide
slate swan
#

i can think of 3-4 things when someone says "logs"

cold tide
#

Does x= False do anything?? would that stop a while in range loop or am i dumb ash

#

Im just playing random cenarios in my mind lool

slate swan
#

What has happened here lmao

white aurora
slate swan
#

;))

silk fulcrum
#

okimii, hii

slate swan
#

Heyyyypithink

dusky pine
#

heyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy

silk fulcrum
#

@slate swan you're genius can u understand is my bot trolling me, cus wtf is this

silk fulcrum
slate swan
silk fulcrum
slate swan
silk fulcrum
#

waht?

slate swan
slate swan
slate swan
silk fulcrum
slate swan
#

why is it a dunder anyways?

#

if you want the value not to change or in theory ofc, just use a constant

cold tide
#

@slate swan

#
@bot.command()
a=1 #whatever
async def start(ctx):
    embed=discord.Embed()
    while a in range(1,999):
     embed.add_field(name="here",value="here",inline=True)
       await ctx.send(embed=embed)
@bot.command()
async def stop(ctx):
    a=False
    await ctx.send("Stopped.")
#

that should work.

slate swan
#

im leaving

slate swan
#

you just typehinted it

cold tide
#

idk what they wanna value it

silk fulcrum
silk fulcrum
slate swan
#

you shoulndt be using dunder names for class variables at the first place thi

#

you should get bonked

silk fulcrum
#

:(((

slate swan
#

making me have a brain fart πŸ˜’

slate swan
silk fulcrum
#

uhhh im dumbass

slate swan
#

dubstep

silk fulcrum
#

lol

slate swan
#

im out of ideas. what would be a good name for a decorator used to add a command to a Bot object
Bot.command most common way
Bot.slash_command/Bot.user_command diff decorator for each command type
Bot.with_command seems a bit nice
Bot.register ( ive been using this till now )

slate swan
#

i got it from the topic of memory allocation

silk fulcrum
#

finally it worked:)

slate swan
#

now fix your file naming or else

slate swan
slate swan
#

i'd name it Bot.okimii

#

why would youyert

#

because that decorator does nothing

#

but add a dict key-pair value

#

i hope you stub your toe at night you piece of cutenessπŸ˜’

slate swan
#

did i ever finish my discord api wrapper, no, reason: im lazy.

silk fulcrum
slate swan
#

thats a sqlite table Okimii

#

no, there was another file

silk fulcrum
#

MySQL

slate swan
#

ah

#

your folders were also in CamelCase you monster

#

πŸ”ͺ

silk fulcrum
#

Why My DB Package Can't Be CamelCased

slate swan
#

i name my files with -

slate swan
slate swan
silk fulcrum
#

_.txt.py

slate swan
silk fulcrum
slate swan
#

camelCase <= this is camelCase btw
CamelCase is PascalCase

silk fulcrum
#

everyone except this is not cameled

silk fulcrum
slate swan
silk fulcrum
#

or he is sumb

#

😳 im really scared now

slate swan
#

no hes right, camelcase has variants lol

slate swan
silk fulcrum
#

this gud? @slate swan

slate swan
#

you have poo naming skillslemon_pensive

silk fulcrum
#

Yes:(

paper sluice
#

conventions for module names is flat case right?

silk fulcrum
#

I absolutely agree

#

my names are complete garbage

slate swan
#

back off

vocal snow
#

what

slate swan
#

hes mine tf

slate swan
#

stealing my husbandπŸ”ͺ

vocal snow
#

???

slate swan
#

Tf?

vocal snow
slate swan
#

why is this channel always weird

#

Because its discord

#

Were bots

slate swan
#

exactly, i dont say anything there

#

i need an angel shot

#

Who?

slate swan
#

hes getting aggressive 😨

#

But im in blue...

#

exactly

#

How do you know??!

#

i know everything😳

#

pithink 😳

#

Wait i think its purple

#

anyways gotta goooo to my husbands dms i gopithink

#

!ot and i think its OT

unkempt canyonBOT
slate swan
#

looking for someone to help me with python code, "bot commands", dm pls

#

just ask in here

#

ok

slate swan
#

😳

#

error:
Ignoring exception in command None:
discord.ext.commands.errors.CommandNotFound: Command "randomgif" is not found

silk fulcrum
slate swan
#

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

client = commands.Bot(command_prefix=">", intents=intents)
bot = commands.Bot(command_prefix=">", intents=intents)

async def giphy(ctx, *, trending) -> None:
    session = aiohttp.ClientSession()
    response = await session.get("https://api.giphy.com/v1/gifs/trending?api_key=0wht0K4drtVOM4tZOJCK2iwqNkAND5HJ&limit=25&rating=g").json()
    embed = discord.Embed()
    urllist = []
    for event in response['data']:
        urllist.append(event['images']['original']['url'])
    embed.set_image(url=random.choice(urllist))
    await session.close()
    await ctx.send(embed=embed)```
swift pumice
slate swan
#

here

#

well, you add the command to bot and run client maybe?

slate swan
swift pumice
#

🧐

vocal snow
slate swan
#

is that not ok?

vocal snow
slate swan
#

I wonder if i can cook Pikachu aka electric ill

slate swan
silk fulcrum
#

bye

vocal snow
#

they're the same

slate swan
#

client or bot better?

#

i want use both then

vocal snow
#

bot is a more accurate variable name

vocal snow
slate swan
swift pumice
#

some use client and some use bot

vocal snow
#

yes but why does he want to use both

#

makes no sense

swift pumice
#

idkπŸ—Ώ

slate swan
#

so if i choose either one and delete the other, will my code work?

#

with both on_message and bot commands

swift pumice
slate swan
#

will it work?

slate swan
#

Gtg

#

bro idk which one to use

swift pumice
slate swan
swift pumice
slate swan
#

then will i still be able to use on_message?

white aurora
#

yes

#
async def on_message(message)```
vocal snow
#

i would use bot.listen() so it doesn't disable commands

slate swan
#

mhm kk

vale wing
#

Yeah and with listen you can listen to the same event in many functions

slate swan
#

NameError: name 'client' is not defined

slate swan
#

pls help

vale wing
#

Define your client or rename the variable

#

It's simple man

slate swan
#

#on_ready
@client.event
async def on_ready():
print(f'{client.user} has connected to Discord!')
send_message.start()

vocal snow
#

you removed client... so now you use bot

slate swan
#

oh

#

does bot support @tasks.loop ?

vocal snow
#

what does that mean

#

!ytdl

unkempt canyonBOT
#

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

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

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

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

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

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

ahh

#

is there any other way to do it then

vocal snow
#

not really

slate swan
#

even if you could you would have licensing issues

#

ahhh

#

ight iam a little new to all this so my bad

#

iam working on my first discord bot right now and getting the hang of things

#

error:
discord.ext.commands.errors.MissingRequiredArgument: trending is a required argument that is missing.

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

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

async def giphy(ctx, *, trending) -> None:
    session = aiohttp.ClientSession()
    response = await session.get("https://api.giphy.com/v1/gifs/trending?api_key=myapikeyhere&limit=25&rating=g").json()
    embed = discord.Embed()
    urllist = []
    for event in response['data']:
        urllist.append(event['images']['original']['url'])
    embed.set_image(url=random.choice(urllist))
    await session.close()
    await ctx.send(embed=embed)```
#

pls help, this is giphy api

#

command not working

#

you really shouldnt make a session on each call of the command and use context managers

#

then how?

vocal snow
slate swan
#

randomgif

cold tide
#
discord.ext.commands.errors.MissingRequiredArgument: trending is a required argument that is missing.
intents = Intents.default()
intents.members = True

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

@bot.command(name="randomgif")
async def giphy(ctx, *, trending) -> None:
    session = aiohttp.ClientSession()
    response = await session.get("https://api.giphy.com/v1/gifs/trending?api_key=0wht0K4drtVOM4tZOJCK2iwqNkAND5HJ&limit=25&rating=g").json()
    embed = discord.Embed()
    urllist = []
    for event in response['data']:
        urllist.append(event['images']['original']['url'])
    embed.set_image(url=random.choice(urllist))
    await session.close()
    await ctx.send(embed=embed)
vocal snow
cold tide
#

@slate swan yw ^

vocal snow
#

async def giphy(ctx, *, trending)

#

i think he was just formatting it

cold tide
#

Idk the format was triggering me

#

Easier to read too.

slate swan
#

ahhh, well you did a favor for my eyes

cold tide
#

lol

slate swan
#

i should be thanking you lmfao

cold tide
#

Nahh your good.

vocal snow
cold tide
#

Dw i had 3 ppl shouting at me earlier trying to convince me im new to py

#

lol

vocal snow
#

not >randomgif value_of_trending_param

slate swan
#

what even does that mean?

vocal snow
#

just for funsies or?

slate swan
#

why i cant put?

vocal snow
#

oh my god

#

im done

slate swan
#

bro-

#

so i just put it as
async def giphy (ctx) -> None:

#

yes or no? @vocal snow

#

or how?

#

This is like 1 h conversation

#

😳

#

so how??

limber bison
#
@commands.Cog.listener()
    async def on_message(self , message):
        bucket = self.message_cooldown.get_bucket(message)
        retry_after = bucket.update_rate_limit()

        if message.author.id == 990358952632021043:
            return
        else:    
          if retry_after:
            pass
          else:
            await economy.update_one({"id": message.author.id}, {"$inc": {"PAODs": +10}})```
i want to fix this to a channel and a role !! i know check.has_role but wot about channel ?
paper sluice
#

@slate swan when you define a command like:

@bot.command()
async def foo(ctx, arg1, arg2):
      ...

and then you call it in discord using >foo 1 2
what your library basically does internally is foo(ctx, 1, 2)
its exactly like how you call a normal python function so you can set default values to make it optional

slate swan
#

so how esactly do i change it?

limber bison
#

Ryuga's foo examples >>>>> , hahahahha

paper sluice
#

!e

def foo(a, b=1):
  print(f'{a = } {b = }')

foo(1, 2)
foo(2)
slate swan
#

pls would u teach me how to make this command work
have been working on it for hours

unkempt canyonBOT
#

@paper sluice :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | a = 1 b = 2
002 | a = 2 b = 1
paper sluice
#

the thing is, you are not using the trending param inside your function, why do you have it there? are you going to use it later on?

slate swan
#

if i remove it, it doesnt work?

paper sluice
#

are you asking me if it doesn't work or ...?

#

it would work because you don't use it anywhere

slate swan
#

then how do i remove it?

paper sluice
slate swan
#
async def giphy(ctx, *) -> None:
    session = aiohttp.ClientSession()
    response = await session.get("https://api.giphy.com/v1/gifs/random?api_key=0wht0K4drtVOM4tZOJCK2iwqNkAND5HJ&limit=25&rating=g").json()
    embed = discord.Embed()
    urllist = []
    for event in response['data']:
        urllist.append(event['images']['original']['url'])
    embed.set_image(url=random.choice(urllist))
    await session.close()
    await ctx.send(embed=embed)```

is it like this?
paper sluice
#

remove the * as well

slate swan
#

k

paper sluice
#

if you want to, python doesn't care

slate swan
#
async def giphy(ctx) -> None:
    session = aiohttp.ClientSession()
    response = await session.get("https://api.giphy.com/v1/gifs/random?api_key=0wht0K4drtVOM4tZOJCK2iwqNkAND5HJ&limit=25&rating=g").json()
    embed = discord.Embed()
    urllist = []
    for event in response['data']:
        urllist.append(event['images']['original']['url'])
    embed.set_image(url=random.choice(urllist))
    await session.close()
    await ctx.send(embed=embed)```

is it like this?
#

so much error:
Warning (from warnings module):
File "/Users/bai/Documents/Personal Things/Do not delete/Only viewable by me/Aww Pika Discord Bot/aww pika discord bot.py", line 71
response = await session.get("https://api.giphy.com/v1/gifs/random?api_key=0wht0K4drtVOM4tZOJCK2iwqNkAND5HJ&limit=25&rating=g").json()
RuntimeWarning: coroutine 'ClientSession._request' was never awaited
Ignoring exception in command randomgif:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "/Users/bai/Documents/Personal Things/Do not delete/Only viewable by me/Aww Pika Discord Bot/aww pika discord bot.py", line 71, in giphy
response = await session.get("https://api.giphy.com/v1/gifs/random?api_key=0wht0K4drtVOM4tZOJCK2iwqNkAND5HJ&limit=25&rating=g").json()
AttributeError: '_RequestContextManager' object has no attribute 'json'

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

Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: '_RequestContextManager' object has no attribute 'json'
Unclosed client session
client_session: <aiohttp.client.ClientSession object at 0x7f818b724070>

paper sluice
#

you need to await session.get, then use .json on it

slate swan
#

im dumb which part do i need to await?

heavy folio
#

i'd recommend using async with for creating a ClientSession since it closes once its done

slate swan
#

show how?

heavy folio
#

or just make a bot variable and use it throughout when its running then override Bot.close() and close the session there

slate swan
#

no

slate swan
#

k

#

thxs u

#
async def giphy(ctx) -> None:
    async with aiohttp.ClientSession() as session:
        session = aiohttp.ClientSession()
        response = await session.get("https://api.giphy.com/v1/gifs/random?api_key=0wht0K4drtVOM4tZOJCK2iwqNkAND5HJ&limit=25&rating=g").json()
        embed = discord.Embed()
        urllist = []
        
        for event in response['data']:
            urllist.append(event['images']['original']['url'])
        embed.set_image(url=random.choice(urllist))
        
        await session.close()
        await ctx.send(embed=embed)```

is it like this?
slate swan
slate swan
slate swan
#

the json coroutine is being awaited not the session.get

#

then how do i await session.get?

#

use parethesis to execute the request first and then use the coroutine on the obj the method returns which is the payload the api returned

#

show how

#

code*

#
await (await session.get("https://api.giphy.com/v1/gifs/random?api_key=0wht0K4drtVOM4tZOJCK2iwqNkAND5HJ&limit=25&rating=g")).json()
#

ok

#

and what else do i need to fix? or thats it?

#

and why are you using context managers but you're starting a session inside of the sessionyert

cold tide
#
@bot.command()
async def report(ctx, user: discord.User, *,message=None):
    embed=discord.Embed()
    embed=discord.Embed(title="Report from {ctx.author}",description=message,color=0xffff00)
    embed.set_footer(text="Report Command !")
    await ctx.author.send(embed=embed)
#

Any way you can make it so you can old send a message to a mod??

#

like certain role

slate swan
cold tide
#

My bad

slate swan
#

Ignoring exception in command randomgif:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "/Users/bai/Documents/Personal Things/Do not delete/Only viewable by me/Aww Pika Discord Bot/aww pika discord bot.py", line 77, in giphy
urllist.append(event['images']['original']['url'])
TypeError: string indices must be integers

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

Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: string indices must be integers
Unclosed client session
client_session: <aiohttp.client.ClientSession object at 0x7f85a4f6f580>
Unclosed connector
connections: ['[(<aiohttp.client_proto.ResponseHandler object at 0x7f85a51487c0>, 21.886284383)]']
connector: <aiohttp.connector.TCPConnector object at 0x7f85a4f6f550>

error

cold tide
#

Ill add it but can u help?

slate swan
#

Code:

async def giphy(ctx) -> None:
    async with aiohttp.ClientSession() as session:
        session = aiohttp.ClientSession()
        response = await (await session.get("https://api.giphy.com/v1/gifs/random?api_key=0wht0K4drtVOM4tZOJCK2iwqNkAND5HJ&limit=25&rating=g")).json()
        embed = discord.Embed()
        urllist = []
        
        for event in response['data']:
            urllist.append(event['images']['original']['url'])
        embed.set_image(url=random.choice(urllist))
        
        await session.close()
        await ctx.send(embed=embed)```
cold tide
#

Send a private dm to a certain user that has a certain role

#

@slate swan

cold tide
#
Code:
@bot.command(name="randomgif")
async def giphy(ctx) -> None:
    async with aiohttp.ClientSession() as session:
        session = aiohttp.ClientSession()
        response = await (await session.get("https://api.giphy.com/v1/gifs/random?api_key=0wht0K4drtVOM4tZOJCK2iwqNkAND5HJ&limit=25&rating=g")).json()
        embed = discord.Embed()
        urllist = []
        
        for event in response['data']:
            urllist.append(event['images']['original']['url'])
        embed.set_image(url=random.choice(urllist))
        
        await session.close()
        await ctx.send(embed=embed)
#

There u go

paper sluice
slate swan
cold tide
#

Then do what?

#

i have 0 clue on how to tbh @slate swan

paper sluice
#

and dont close connection manually, thats what the contextmaanager is for

cold tide
slate swan
cold tide
#

someone help.

#
@bot.command()
async def report(ctx, user: discord.User, *,message=None):
    member=988844917163954266
    embed=discord.Embed()
    embed=discord.Embed(title=f"Report from {ctx.author}",description=message,color=0xffff00)
    embed.set_footer(text="Report Command !")
    await ctx.member.send(embed=embed)
cold tide
cold tide
#

I just figured lol

vocal snow
#

are you trying to message the mentioned user or

cold tide
#

yeah but make it so u can only dm a user w a certain role

paper sluice
#

!d discord.ext.commands.has_role

unkempt canyonBOT
#

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

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

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

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

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

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

use this decorator

vocal snow
#

I don't think that's what he wants

vocal snow
paper sluice
#

oh, you want all mods or whatever to get a dm?

left idol
#

in pycord can i give context to my view?

#

like if i wanted to see if interaction user id was the same as ctx.author.id

slate swan
#

with bots whats the best way to get a category id/ create a channel in a category without creating the category each time

#
category = await guild.create_category("JOBS")
await guild.create_text_channel(jobid,Permissions=perms,category=category)``` currently using this
#

creates a new category each time whereas i want to create the channel in the existing category

unkempt canyonBOT
#

get_channel(channel_id, /)```
Returns a channel with the given ID.

Note

This does *not* search for threads.

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

if you have the category id

slate swan
#

Get channel works on categories as well

#

Damn thanks a bunch google πŸ˜‚πŸ˜‚πŸ˜‚

vocal snow
#

the class is CategoryChannel so I believe so

slate swan
#

I'll give it a go thanks

mellow cave
#

May I ask what's difference if I use discord.py and discord.js?

tidal hawk
#

I feel like Python bots are much easier to make and maintain

placid skiff
#

that javascript is ||shit||

tidal hawk
#

tried creating js bot and had to do slash commands in seperate files D:

vocal snow
slate swan
#

what is um how to fix 404too many requests error,how long am i blocked for

vocal snow
slate swan
#

help

mellow cave
slate swan
#

please

vocal snow
mellow cave
#

like i cant make music bot with python or something?

vocal snow
#

storing conversations, other stuff

slate swan
#

ignored

vocal snow
tidal hawk
#

imagine music bot where you say "pause" or "next-song" it does accordingly

mellow cave
#

danm

#

but it would be pretty unaccurate and buggy to use since not a lot of people has good mics

vocal snow
vale wing
#

I am currently making a dashboard for my bot with django and I still gotta use js for frontend (I copypaste it πŸ˜‚)

vocal snow
#

if you're using repl.it you can kill the container and pray that it goes away

slate swan
vale wing
#

Damn you got cloudflare ban

slate swan
#

my hopes πŸ“‰

vale wing
#

Idk if cloudflare bans are stricter than common ratelimit but discord mentions it specially in the docs

#

I never got ratelimited myself so I have no idea what that is

mellow cave
slate swan
#

What can i replace for time.sleep()?

#

For discord py

tidal hawk
#

await asyncio.sleep()?

vale wing
limber bison
#
message_cooldown = commands.CooldownMapping.from_cooldown(1.0, 60.0, commands.BucketType.user)

@commands.Cog.listener()
    async def on_message(self , message):
        if message.author.id == 990358952632021043:
            return

        bucket = self.message_cooldown.get_bucket(message)
        retry_after = bucket.update_rate_limit()

        if retry_after:
          pass
        else:
          bal = await economy.find_one({"id": message.author.id})
          if bal is None:
            await self.open_account(message.author.id)
          else:  
           amount = random.choices([random.randint(0, 10) , random.randint(11, 20) ] ,weights = (0.9, 0.1) )[0]
           await economy.update_one({"id": message.author.id}, {"$inc": {"PAODs": +amount}})
           await message.channel.send(f'{message.author} gets {amount} in PAODs bank')```

how can i make this same thing for vc so i can give tham some paods/xp ????
#

this is for chat hmm 😳

#

any idea any one or suggestion ?

quasi sparrow
#

Hi im struggling with something. Im new to python trying to build a discord bot using pycharm and python

quasi sparrow
#

Should i type that where

limber bison
quasi sparrow
#

I did install this

vale wing
limber bison
quasi sparrow
#

No its ||my discord bot.py||

limber bison
#

πŸ€”

vale wing
#

Also could you like use screenshots

quasi sparrow
limber bison
vale wing
limber bison
#

i want same for vc's like a user is in vc for 1 min he get 10 xp

vale wing
#

Interesting how you used the bucket for cooldowns

#

Personally I have a sort of dict with datetimes

limber bison
limber bison
#

?

vale wing
#

And uh what's +amount

limber bison
quasi sparrow
limber bison
quasi sparrow
#

Ok

#

Just took out my token

#

But thats the code

quasi sparrow
quasi sparrow
vale wing
#

Tf is wrong with your fonts

quasi sparrow
vale wing
#

It's supposed to look like this (don't pay attention to code itself)

quasi sparrow
#

I didn't change anything. It is just liked i downloaded it

vale wing
#

And did you take any tutorial

quasi sparrow
paper sluice
vale wing
#

Discord bot

vale wing
quasi sparrow
vale wing
#

This is the default font so it is supposed to look like this

#

They have either some font issues or installation issues

limber bison
vale wing
vale wing
quasi sparrow
limber bison
paper sluice
limber bison
quasi sparrow
paper sluice
vale wing
#

@limber bison go to the settings and find this thing for python extension, choose whatever formatter you want, then right click in your code and choose "Format Document" it should do the thing

limber bison
#

for chats we know on_message hahaha

slate swan
#

or you can just pip install black and use python -m black file/directory/.

paper sluice
unkempt canyonBOT
#

discord.on_voice_state_update(member, before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") changes their [`VoiceState`](https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceState "discord.VoiceState").

The following, but not limited to, examples illustrate when this event is called...
limber bison
#

and can i put check for an catagory ?

slate swan
#

note that it just stated the connection, nothing related to the users voice activity

limber bison
vale wing
#

Just count the time they have been in vc ig?

limber bison
vale wing
#

For example save the time when the user joined a vc and when they leave the vc add some score based on the time they have been there

#

Or use some kind of loop that would add score to every member in vc

#

The second approach is better because user doesn't have to leave vc to get score assigned but is slightly more expensive cause of the loops

slate swan
#

Why it saying that something is missing

@client.command()
async def guess(ctx, variable: int):
  await ctx.send(variable)

zealous jay
#

need to pass the command name

#

@client.command(name="guess")

#

@slate swan

slate swan
#

Thank you!

zealous jay
#

no problem, let me know if it still gives an error

vale wing
vale wing
vale wing
slate swan
#

Im confused

zealous jay
#

oh πŸ€¦β€β™‚οΈ

#

im sleepy

#

sorry lol

vale wing
slate swan
#

Idk

#

What is invoke

vale wing
#

I mean what message do you send to execute it

slate swan
#

.guess

vale wing
#

Is variable argument supposed to be optional or

#

As long as it is not optional you gotta provide it to the command

slate swan
vale wing
#

Yeah ik read what I said

#

You gotta invoke the command like .guess 30

slate swan
#

Ohhh

#

I forgot about that

#

Im such a dum dum

#

@vale wing

#

@vale wing

vale wing
#

?

slate swan
#

How can i start first the command start

vale wing
#

Em what

slate swan
#

To prevent member guessing without saying .guess

vale wing
#

You need an error handler

slate swan
#

Idk that

#

Le me study

vale wing
#

So basically you need to listen for on_command_error event

#

!d discord.ext.commands.Bot.on_command_error

unkempt canyonBOT
#

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

The default command error handler provided by the bot.

By default this logs to the library logger, however it could be overridden to have a different implementation.

This only fires if you do not specify any listeners for command error.

Changed in version 2.0: `context` and `exception` parameters are now positional-only. Instead of writing to `sys.stderr` this now uses the library logger.
vale wing
#

And then check if exception is an instance of some error class, in your case commands.MissingRequiredArgument

#

A very basic error handler looks like this

@bot.listen()
async def on_command_error(ctx, error):
    if isinstance(error, commands.MissingRequiredArgument):
        text = "You are missing a required argument for this command"
    elif isinstance(error, commands.CommandOnCooldown):
        text = "This command is on cooldown, try again later"
    else:
        raise error

    await ctx.send(text)```
#

@slate swan

slate swan
#

Thank you for the code

kind trellis
#

If anyone is able to help me in #help-potato that would be awesome

limber bison
#

!d discord.ext.commands.MemberConverter

unkempt canyonBOT
#

class discord.ext.commands.MemberConverter(*args, **kwargs)```
Converts to a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member").

All lookups are via the local guild. If in a DM context, then the lookup is done by the global cache.

The lookup strategy is as follows (in order)...
storm rose
#

Requirement already satisfied: discord.py in /Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages (1.7.3)
Requirement already satisfied: aiohttp<3.8.0,>=3.6.0 in /Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages (from discord.py) (3.7.4.post0)
Requirement already satisfied: attrs>=17.3.0 in /Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages (from aiohttp<3.8.0,>=3.6.0->discord.py) (22.1.0)
Requirement already satisfied: multidict<7.0,>=4.5 in /Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages (from aiohttp<3.8.0,>=3.6.0->discord.py) (6.0.2)
Requirement already satisfied: typing-extensions>=3.6.5 in /Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages (from aiohttp<3.8.0,>=3.6.0->discord.py) (4.3.0)
Requirement already satisfied: async-timeout<4.0,>=3.0 in /Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages (from aiohttp<3.8.0,>=3.6.0->discord.py) (3.0.1)
Requirement already satisfied: chardet<5.0,>=2.0 in /Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages (from aiohttp<3.8.0,>=3.6.0->discord.py) (4.0.0)
Requirement already satisfied: yarl<2.0,>=1.0 in /Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages (from aiohttp<3.8.0,>=3.6.0->discord.py) (1.8.0)
Requirement already satisfied: idna>=2.0 in /Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages (from yarl<2.0,>=1.0->aiohttp<3.8.0,>=3.6.0->discord.py) (3.3)
WARNING: You are using pip version 22.0.4; however, version 22.2.1 is available.
You should consider upgrading via the '/Library/Frameworks/Python.framework/Versions/3.9/bin/python3 -m pip install --upgrade pip' command.

#

Anyone know what this is about?

slate swan
#

!command

#

you already have the libraries you were looking for installed and a new pip version is available

storm rose
slate swan
#

how to disable the spammy effect?

        await message.channel.send("hi")```
storm rose
#

does it install globally on your comp?

#

What is this about?

vocal snow
# storm rose

Navigate to your Applications/Python 3.6/ folder and double click the Install Certificates.command

slate swan
storm rose
#

Yes works

#

thx

silent portal
shrewd barn
#

how can i type like this

silent portal
#

test

silent portal
shrewd barn
#

thanks

silent portal
#

Idk if that will work, Iβ€˜m on my phone rn but something like this:

```py

# Text here
#

at the bottom ` 3x again

slate swan
#

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

shrewd apex
#

the effort he took to explain

#

lmfao

slate swan
#

kills me

silent portal
slate swan
#

await message.channel.send("HELLO )

#

i want hello {user} so it plugin it

cosmic agate
#
@bot.command()
async def attack(ctx, user: nextcord.Member=None):
 if user == ctx.author:
  stupidityem = nextcord.Embed(title ="bruh :smh:", description = "HOW DA HELL ARE YOU GONNA ATTACK YOURSELF???? :stopit:", colour = nextcord.Colour.random())
  stupidityem.set_footer(text = "Two things are infinite: the universe and human stupidity; and I'm not sure about the universe ~ Albert Einstein")
  stupidityem.set_image(url="https://c.tenor.com/-YrgmiDmNTsAAAAC/toy-story-stupid-people.gif")
  await ctx.reply(embed = stupidityem)
 if user == bot.user:
   botem = nextcord.Embed(title= "⚠⚠⚠WARNING⚠⚠⚠", description = "You have Initiated Skynet's Artificial Intelligence. Nukes are there all around the world and terminators surrounding.", colour = nextcord.Colour.red())
   botem.set_footer(text = "Should have left me alone >:)")
   botem.set_image(url = "https://c.tenor.com/HQnsUe-_ig4AAAAC/robot-tech.gif")
   await ctx.reply(embed = botem)
 else:
   
#
  attackem1 = nextcord.Embed(title= f"You tried to Attack {user}, but...",description=f"{ctx.author.name} tried to punch {user.name}, but he caught it and kicked {ctx.author.name}!:kekw:", colour=nextcord.Colour.random())
 attackem1.set_image(url="https://cdn.discordapp.com/attachments/905019001757892620/953280072834486312/spider-man-green-goblin.gif")
 attackem2 = nextcord.Embed(title= f"You tried to Attack {user}, but....", 
    description=f"{ctx.author.name} tried to attack {user.name}, but he dodges it smooth as heck:kekw:", colour=nextcord.Colour.random())
 attackem2.set_image(url="https://c.tenor.com/VzpuZphq0EgAAAAd/doc-ock-spider-man2.gif")    
 attackem3 = nextcord.Embed(title = f"You attacked {user} and...", description = f"{ctx.author.name} TURNED {user} INTO ***SPAGETTI***")
 attackem3.set_image(url="https://c.tenor.com/IaTH9agWDIoAAAAd/doctor-strange-in-the-multiverse-of-madness-illuminati.gif")
  
 embeds = (attackem1, attackem2, attackem3)
           
 await ctx.reply(embed=random.choice(embeds))
#

I get both responses for some reason

tepid dagger
outer parcel
#

Using discord.ui.View how can i keep my buttons always on

#

and not going into interaction failed after a while

torn sail
#

!d discord.ui.View

unkempt canyonBOT
#

class discord.ui.View(*, timeout=180.0)```
Represents a UI view.

This object must be inherited to create a UI within Discord.

New in version 2.0.
outer parcel
#

what is max timeout

torn sail
#

timeout=None

outer parcel
#

wait does that actually fix it

#

if it does then im kinda mad ngl

torn sail
#

It won’t stay after bot restarts tho

outer parcel
#

ye ye

#

omg ty so much

torn sail
#

πŸ‘

#

Try putting an r in front of the string that is a path

slate swan
#

how to reset shards?

vale wing
slate swan
waxen ruin
#

Hello..anyone know why my interaction is failing again and again?

here is the code:

`await ctx.send(embed=embed, components=[Button(label="Report", style=3,custom_id="button-startreport")])

interaction = await client.wait_for("button_click", check=lambda i: i.custom_id=="button-startreport")
await interaction.response.send_message("Button clicked.")`
vale wing
#

!e ```py
n = 50
if n > 40:
print("N > 40")
if n > 30:
print("N > 30")

a = 50
if a > 40:
print("A > 40")
elif a > 30:
print("A > 30")```

unkempt canyonBOT
#

@vale wing :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | N > 40
002 | N > 30
003 | A > 40
slate swan
vale wing
magic pond
#
    @commands.command()
    @commands.guild_only()
    async def sync(self, ctx: commands.Context, sync_globally: bool = False) -> None:
      async with ctx.channel.typing():
        if ctx.channel.permissions_for(ctx.author).manage_guild:
            if sync_globally:
              
                await self.bot.tree.sync()
                await ctx.reply('Slash commands have been synchronized globally')
            else:
                self.bot.tree.copy_global_to(guild=ctx.guild)
                await self.bot.tree.sync(guild=ctx.guild)
                await ctx.reply('Slash commands have been synchronized on this server')
        else:
          embed = discord.Embed(title='Action Error', description='You don\'t have the permission to use this command.',color=0x2f3136)
          embed.set_thumbnail(url='https://cdn.discordapp.com/emojis/971007299038621727.webp?size=128&quality=lossless')
          embed.set_footer(text=f'Requested by {ctx.author}')
          await ctx.reply(embed=embed)

is this correct ?

vale wing
slate swan
vale wing
#

Library automatically reconnects it once gateway is available

slate swan
#

is there a way to see all the shard status?

vale wing
#

And uh how many guilds is your bot in

slate swan
#

64

vale wing
#

You clearly don't need sharding

slate swan
#

but what about the too many requests error

vale wing
#

It's recommended to do it when bot is in at least 1k guilds and is slower than expected

slate swan
#

oih

vale wing
slate swan
#

im poor

#

i cant buy pc

cold sonnet
vale wing
#

Even if you shard it you can't avoid that error

slate swan
#

will command cooldown help it

vale wing
#

Get a VPS or smth, amazon AWS offers you 1 year of free tier and I can help with that

vale wing
slate swan
#

oh

slate swan
#

i have no idea what is that

#

and 1 year is less

vale wing
#

"I can help with that"

slate swan
#

alt accounts

vale wing
#

Meaning I will explain all the stuff

slate swan
#

ooh

vale wing
slate swan
#

idk

#

how do i do that thing where its enabled and disabled for specific guilds

vale wing
#

Checks ig?

slate swan
#

and people can toggle it on and off

vale wing
#

Or you mean slash commands

slate swan
#

i mean a command

vale wing
#

Prefix?

slate swan
#

yes

vale wing
#

That's kinda complicated, you gotta have a database

#

And as I am thinking about its structure it's complex

slate swan
#

is json okay for it

vale wing
#

Json is not okay for data storage generally

slate swan
#

<= dumb

vale wing
#

Config files and network data transmission is ok but storage no

vale wing
#

Rows for guilds and columns for commands?

#

Ig it's better to use a database which supports arrays like postgres

slate swan
#

what about a variable

#

for every guild

#

like um

#

toggle = on
toggle = off

#

and um yeah

vale wing
#

You gotta have a toogle for every command in every guild

#

Or for every guild in every command

slate swan
#

okay so what if i have to use it in only command

#

a command which is like available for some servers

#

and others not

#

how do i do it

vale wing
#

You may hardcode it and use a check

#

Do you mean sort of system command

slate swan
#

noo like a hm

#

lemme explain

vale wing
#

Or like server admins can toogle it on and off

slate swan
#

server admins]

vale wing
#

Then hardcoding won't work

slate swan
#

i hvave this thing in on_message

vale wing
#

Oh I have an idea about the database structure for that stuff

#

So uh guild_id | command_name | is_enabled

#

It's much simpler than I was thinking

#

You can actually put only disabled commands to there not to create useless rows

#

Otherwise you are going to have guilds amount * amount of commands rows and that's useless

#

And if a command is not present in a table you just consider it enabled

slate swan
#

nooo not thattt

vale wing
#

In postgres you could actually do guild_id | disabled_commands and it would be better imo

vale wing
slate swan
#

forget about it ,its hard to explainn

vale wing
#

Ok

#

If you say so

limber bison
#

its off now but on one refresh it become on

slate swan
#

ngl logo looks amazing

limber bison
#

thanks

tired notch
#
    def add_buttons(self):
        moves = iter(self.moves)

        async def move(interaction: Interaction):
            print(f'You used {button.label}')
            await interaction.response.send_message(f'you used {button.label}')

        for i in range(6):
            button = Button(label=next(moves, "Empty"))
            print(button)
            button.callback = move
            self.add_item(button)``` why always say empty when i press button in discord py 2
vale wing
#

Is it a just created bot

limber bison
#

long time

vale wing
#

Does it have tags and "add bot" button configured

limber bison
#

i dont think πŸ€”

vale wing
#

This button

limber bison
#

thing

#

i want to remove it

#

like

vale wing
#

Disable this thing in oauth2 tab

maiden fable
vale wing
maiden fable
#

They check if a bot has any of the 3 application commands command(s)

vale wing
#

I have a suspect that it actually depends on amount of commands

limber bison
maiden fable
#

iirc according to their announcement u need at least 1 app command

vale wing
#

Because I had a bot that had like 5 app commands but recently I rewrote it to around 30 of them and now it has that badge

maiden fable
#

Weird

vale wing
#

Yeah

maiden fable
craggy parcel
#

I am having a problem with my discord bot
bot = commands.Bot(command_prefix = ".")
@bot.command()
async def lobstercage(ctx, arg1, arg2):
await ctx.send(f' You sent {arg1} to the lobster cage for {arg2} minutes')
however this isn't working

vale wing
# maiden fable

They key word is testing, probably discord doing that on random bots like they once were doing with animated banners for users

tired notch
#

whats not working

zealous jay
#

It may need to be verified?

magic pond
#

how to sync the slash commands ??

craggy parcel
tired notch
#

look in the pins

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.

tired notch
#

does the bot turn on? any error messages

craggy parcel
#

bot turns on fine, got some bot.event code running just fine

zealous jay
#

do you have an on_message event?

craggy parcel
#

yes

tired notch
#

does your bot have the correct permisisons

zealous jay
#

and do other commands work fine?

craggy parcel
#

it has admin prems

maiden fable
craggy parcel
zealous jay
#

May I see your on_message event?

craggy parcel
#

no

#

jk

zealous jay
#

you may need to add this at the end of it

await client.process_commands(message)
craggy parcel
#

@bot.event
async def on_message(message):
print(f'{message.author} has said {message.content}')

zealous jay
#

yeah add what I just sent at the end of it

#

and try your command

craggy parcel
#

wdym at the end of it

zealous jay
#
@bot.event
async def on_message(message):
        print(f'{message.author} has said {message.content}')

        await client.process_commands(message)β€Š

#

cant get the indent right but make sure its inside the function

slate swan
#

How can i make currency game?

#

And how can i save data?

zealous jay
craggy parcel
#

TabError: inconsistent use of tabs and spaces in indentation

zealous jay
#

yeah try fixing the tabs, im on a phone rn and its kinda hard

#
await client.process_commands(message)β€Š
#

just add that below the print

#

and be sure its inside on_message function

tired notch
#

can someone help me with discord interaction buttons

stiff gorge
#
  File "/home/runner/mv/venv/lib/python3.8/site-packages/discord/ext/tasks/__init__.py", line 398, in start
    self._task = asyncio.create_task(self._loop(*args, **kwargs))
  File "/nix/store/p21fdyxqb3yqflpim7g8s1mymgpnqiv7-python3-3.8.12/lib/python3.8/asyncio/tasks.py", line 381, in create_task
    loop = events.get_running_loop()
RuntimeError: no running event loop```
#
bot.changeable_activites = (
    "Call of Duty: Warzone",
    "Fall Guys",
    "Fortnite",
    "Call of Duty: Black Ops IV",
    "Sea of Thieves",
    "League of Legends",
    "GTA V",
    "Valorant")


@tasks.loop(minutes=1)
async def change_activity():
    await bot.wait_until_ready()
    new_activity = random.choice(bot.changeable_activites)
    await bot.change_presence(activity=discord.Streaming(new_activity))

change_activity.start()
torn sail
craggy parcel
zealous jay
#

yes

#

oh

craggy parcel
#

gives me a taberror still

zealous jay
#

huh

tired notch
#

gladiator colette

zealous jay
#

would be easier if I was on a computer

#

!paste

unkempt canyonBOT
#

Pasting large amounts of code

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

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

torn sail
tired notch
#
class Moves(View):
    def __init__(self, ctx, moves):
        super().__init__()
        self.moves = moves
        self.ctx = ctx
        self.add_buttons()

    def add_buttons(self):
        moves = iter(self.moves)

        async def move(interaction: Interaction):
            print(f'You used {button.label}')
            await interaction.response.send_message(f'you used {button.label}')

        for i in range(6):
            button = Button(label=next(moves, "Empty"))
            print(button)
            button.callback = move
            self.add_item(button)``` i have this code and i am trying to make a list of moves appear as buttons and it works but when i press the buttons it always prints empty even if the button is called something else
craggy parcel
zealous jay
#

nice!

#

i was looking for a way to use tab key on my cellphone

craggy parcel
#

lol

#

so the problem def is that print

zealous jay
#

i may be wrong but on_message event kinda overwrites how the bot processes commands

craggy parcel
#

well that stinks

zealous jay
#

so you need to add that thing i sent to fix it

hasty loom
#

if im using digitalocean which droplets plan should i use? my bot is in less than 100 servers and doesnt really do any heavy duty tasks

vale wing
#

Pick the cheapest one

#

1gb ram is totally enough

#

But if you got free credits get the one you can use for free until they expire πŸ˜‰

zealous jay
vale wing
tired notch
#

i did from discord.interactions import Interaction

zealous jay
#

oh ok

vale wing
#

If you use @bot.event you overwrite the default listener

craggy parcel
zealous jay
#

good

craggy parcel
#

goose

zealous jay
vale wing
vale wing
zealous jay
#

yeah

#

didn't know about that

vale wing
#

That's a pretty useful thing

zealous jay
#

yep

vale wing
#

Allows you to create several listeners for one event

zealous jay
#

You avoid having 100 lines in one event

vale wing
#

Yeah and you do stuff asynchronously which is an advantage too

zealous jay
tough lance
#

Imagine making discord bots

eternal fox
zealous jay
#

imagine not

#

making discord bots

vale wing
#

I once thought of that thing

#

The bot for hosting bots

#

For making bots there is already one and it is cringe as many say

zealous jay
#

mee6 has something that's similar

#

You can get a custom mee6

#

or something like that

vale wing
# vale wing The bot for hosting bots

You could actually clone bot's github repos, add dockerfile and compose and just launch the container (some volumes stuff and secrets too ofc) but if many people wanted to host their bots you would need a whole data center

#

Or you could limit the ram usage but you'd still need a lot of computing power to host that many bots

#

And yeah ratelimits

#

So not good

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

    if message.content == 'hello':
        await message.channel.send('Welcome to the server!')

    if message.content == 'cool':
        await message.add.reaction('\U0001F60E')

Whenever I type hello I get a response message from the bot but when I type cool the bot won't respond with an emoji

vale wing
#

You made a small typo: not add.reaction, it's add_reaction

craggy parcel
#

how do I remove logging certain messages from certain people
@bot.event
async def on_message(message):
await bot.process_commands(message)
if message.author == 'SpookyBot#0745':
return
else:
print(f'{message.author} said {message.content}')
I have this line of code but it still prints to my cmd

zealous jay
#

better to use user's id

#

because name and tag can be changed

craggy parcel
#

I just want to silent my bots

zealous jay
craggy parcel
#

thanks It works

zealous jay
#

no problem

tired notch
#

in discord py 2 how do i set a button label to be a variable

sick birch
tired notch
#

im not sure how to do that

tired notch
#

i did something simlar like this

#
    def add_buttons(self):
        moves = iter(self.moves)



        for i in range(6):
            test = Button(label=next(moves, "Empty"))
            print(test)
            async def move(interaction: Interaction):
                print(test)
                print(f'You used {Button.label}')
                await interaction.response.send_message(f'you used {Button.label}')

            test.callback = move
            self.add_item(test)1```
#

it works but i cant get the button name after i make the buton

#

i tried a lot o diferent things

sick birch
#

You might want to subclass both view and button

tired notch
#

class TicTacToeButton(discord.ui.Button['TicTacToe']): what do the brackets mean

sick birch
#

It's not necessarily but hints to your IDE/linter what the type of self.view is

weary dragon
#

Hey so i was wondering if it is still possible to make discord bots with python, I haven't kept up with it and I heard there has been a lot of changes.

sick birch
tired notch
#

wait why i need to subclass if i can do this test = Button(label=next(moves, "Empty"))

sick birch
weary dragon
#

So i want to get back into it but Ever youtube vid i find is outdated and old and not sure if it would still work.

sick birch
#

It's not very pythonic, and disoragnized, if you ask me

tired notch
#

oh ok

sick birch
limber bison
#

@guild_only() is this correct check ?

tired notch
#
class Move(Button):
    def __init__(self):
        super().__init__()

    async def callback(self, interaction: Interaction):
        await interaction.response.send_message(self.label)``` something like this will work\
tough lance
#

You want to change the label?

tired notch
#

i want print label

tough lance
#

Yup that will work

sick birch
tired notch
#

can you just do Move(label='a')

sick birch
#

That would throw an error

quaint epoch
#

!d io.BytesIO

unkempt canyonBOT
#

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

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

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

why can't you just go b''?

#

or use a bytesarray?

tough lance
#

off topic for here i think

tired notch
#
class Move(Button):
    def __init__(self, label):
        super().__init__()
        self.label = label

    async def callback(self, interaction: Interaction):
        await interaction.response.send_message(self.label)```
sick birch
#
class MyButton(discord.ui.Button):
  def __init__(self, label: str) -> None:
    super().__init__(label=label, ...)
    self.label = label
  async def callback(self, interaction: discord.Interaction, button: discord.ui.Button) -> None:
    await interaction.response.send_message(self.label)

class MyView(discord.ui.View):
  def __init__(self) -> None:
    super().__init__(...)
    self.add_item(MyButton("Button #1"))
    self.add_item(MyButton("Button #2"))
    self.add_item(MyButton("Button #3"))

@bot.command()
async def my_command(ctx: commands.Context, ...) -> None:
  view = MyView()
  await ctx.send(view=view)

This, for example, will send a view with 3 buttons, and when the user clicks on it, it will respond with the button they clicked on

tired notch
#

oh ok

#
    def add_buttons(self):
        moves = iter(self.moves)

        async def move(interaction: Interaction):
            print(f'You used {test.label}')
            await interaction.response.send_message(f'you used {test.label}')

        for i in range(6):
            test = Button(label=next(moves, "Empty"))
            test.callback = move
            self.add_item(test)
``` i am wonder why this not work and always sends Empty even when label is something else
sick birch
#

Not sure. The code is hard to follow and there may be an error anywhere

#

Which is why I suggested subclassing it

tired notch
#

ok is working now thank you very much

#

can the callback function return something

#

actually i can just test that

sick birch
tired notch
#

ok thank you for your ehlp

craggy parcel
#

I want to create a command to where it takes in two inputs (username, time) and gives that user a role for that amount of time would anyone know how to do this

slate swan
#

I am trying to test something for Betterdiscord could someone check the code for me?

scarlet pond
#

Does anybody know why this code isn't working?

@client.event
async def on_guild_join(guild):
    for channel in guild.text_channels:
        print(channel.name)

output:

e

channels in the server:

slate swan
#

I am trying to test something for Betterdiscord could someone check the code for me?

unkempt canyonBOT
#

Hey @slate swan!

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

sick birch
slate swan
sick birch
#

!rule 5

unkempt canyonBOT
#

5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.

slate swan
scarlet pond
#

in my code?

slate swan
#

nvm I read half the thing

slate swan
#

so either the text channels arent cached properly

vale wing
#

@sick birch thanks for the review on that PR, now it got 3 more reviews and I am waiting for 2 of them to re-review cause they requested changes, but after they approve the changes what is going to happen before the PR gets merged?

scarlet pond
#

oh shoot I forgot to save file

slate swan
scarlet pond
#

yeah its just "e"

swift pumice
#

where did i do an indentation error?

scarlet pond
swift pumice
scarlet pond
#

wait

#

oh its a parsing error

#

I've gotten that a lot

#

inconsistency in spaces and intentdations?

swift pumice
#

no isn’t because of bot

#

what?

scarlet pond
#

sometimes its because you are using both spaces and indentations

swift pumice
#

oh ok

#

works thank you :D

scarlet pond
#

yw

slate swan
scarlet pond
#

f

swift pumice
#

ok

silk fulcrum
#

i guess i don't even have to make my own help command, this looks good enough :lemao:

scarlet pond
#

I think that is cogs?

silk fulcrum
#

cog description?

scarlet pond
#

do you also need to enable intents in your code

shrewd apex
#

u can either use a docstring or u can set up some custom kwarg either way works

scarlet pond
#

ah ok

slate swan
unkempt canyonBOT
#

Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.

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

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

from discord import Intents
from discord.ext import commands

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

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

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

craggy parcel
#

I want to create a command to where it takes in two inputs (username, time) and gives that user a role for that amount of time would anyone know how to do this

vale wing
#

Yeah sure you just need a database in which you will store the time at what to take the role off and a loop that will periodically check for those roles

#

I could link an example but it's kinda complicated so I won't

slate swan
#

File "C:\Users\Ibrah\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "C:\Users\Ibrah\Desktop\discordbot-main\main.py", line 15, in on_ready
await bot.change_presence(activity=discord.Game('Sky Craft'))
File "C:\Users\Ibrah\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 1062, in change_presence
await self.ws.change_presence(activity=activity, status=status, afk=afk)
AttributeError: 'NoneType' object has no attribute 'change_presence'

#

ah

#

!error

#

!error File "C:\Users\Ibrah\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "C:\Users\Ibrah\Desktop\discordbot-main\main.py", line 15, in on_ready
await bot.change_presence(activity=discord.Game('Sky Craft'))
File "C:\Users\Ibrah\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 1062, in change_presence
await self.ws.change_presence(activity=activity, status=status, afk=afk)
AttributeError: 'NoneType' object has no attribute 'change_presence'

slate swan
#

IDK

#

nvm, ah on_ready, just dont

#

wdym

slate swan
#

O

#

Ok Then

#

Thank You!

#

either change it in the bot constructor or a task

slate swan
# slate swan either change it in the bot constructor or a task
Traceback (most recent call last):
  File "C:\Users\Ibrah\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\Ibrah\Desktop\discordbot-main\main.py", line 24, in on_message
    await bot.change_presence(activity=discord.Game('Sky Craft'))
  File "C:\Users\Ibrah\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 1062, in change_presence
    await self.ws.change_presence(activity=activity, status=status, afk=afk)
AttributeError: 'NoneType' object has no attribute 'change_presence'
#

haha if message.content.startswith("!hi"): await message.delete() await message.channel.send("Hello Friend How I Can Help You? :blush: ") await bot.change_presence(activity=discord.Game('Sky Craft'))

#

what evemt

slate swan
#

wdym

#

i so dumb RainbowChest

#

Wtf

#

I Don't understand

#

Sorry today is frist day me in python

#

i know java :)

#

but not python

slate swan
#

IDK

unkempt canyonBOT
#

Hey @slate swan! I noticed you posted a seemingly valid Discord API token in your message and have removed your message. This means that your token has been compromised. Please change your token immediately at: https://discordapp.com/developers/applications/me

Feel free to re-post it with the token removed. If you believe this was a mistake, please let us know!

slate swan
#

and why not just make a bot in java πŸ’€

#

WAit I SEND THE TOKEN

slate swan
#

import discord
from discord.ext import commands

import json
import os
key = "e"
bot = commands.Bot(command_prefix='!')
client = discord.Client()

random = ['MayBe' , 'Yes' , 'No' , 'Probbly' , 'Likey' , 'unlikey']
@client.event
async def on_ready():
print("BOT ONLINE")
channel = client.get_channel(1004036302594920508)
await channel.send("I Am Online βœ…")
@client.event
async def on_message(message):
if message.author == client.user:
return

if message.content.startswith("!hi"):
    await message.delete()
    await message.channel.send("Hello Friend How I Can Help You? 😊 ")
    await bot.change_presence(activity=discord.Game('Sky Craft'))
if message.content.startswith("!user"):
    await message.delete()
    await message.channel.send(f"Hello {message.author}")
if message.channel.id == 1004054901787201646:
    channel = client.get_channel(1002154446442209393)
    await message.delete()
    await channel.send(f"Test bot Server Β» {message.author} Β» **{message.content}**")
if message.channel.id == 1002154446442209393:
    channel = client.get_channel(1004054901787201646)
    await message.delete()
    await channel.send(f"Sky Craft Β» {message.author} Β» **{message.content}**")
if message.channel.id == 1002154446442209393:
    channel = client.get_channel(100215444644220939)
    await channel.send(f"{message.author} Β» **{message.content}**")
if message.channel.id == 1004054901787201646:
    channel = client.get_channel(1004054901787201646)
    await channel.send(f"{message.author} Β» **{message.content}**")
limber bison
#
@commands.Cog.listener()
@commands.guild_only()

will this word ?

slate swan
#

e

limber bison
#

like its not working

#

any alternative ?

slate swan
#

idk

#

anyone wants to help me to create a modmail discord bot please?

sick birch
slate swan
#

WTF

sick birch
#

You can practically make a discord bot in any language these days

#

Excluding esoteric ones, of course

odd mango
#

how can i remove a member from a channel?
read_messages=False, send_messages=False dosent actually "remove" the member

slate swan
#

idk

limber bison
#

@sick birch how can i make @commands.Cog.listener() guild only

#

sir

sick birch
#

What type of listener?

slate swan
#

wait

#

let me read step by step

slate swan
slate swan
limber bison
slate swan
#

for example, for on_message, check if message.guild is not None.

keen talon
#

I am back again 😎

slate swan
#

message.guild will be None if there is no guild, just go by this assumption

sick birch
slate swan
limber bison
#
    @commands.Cog.listener()
    async def on_message(self , message):
        if message.author.id == 990358952632021043:
            return

        bucket = self.message_cooldown.get_bucket(message)
        retry_after = bucket.update_rate_limit()

        if retry_after:
          pass
        else:
          bal = await economy.find_one({"id": message.author.id})
          if bal is None:
            await self.open_account(message.author.id)
          else:  
           amount = random.choices([random.randint(0, 10) , random.randint(11, 20) ] ,weights = (0.9, 0.1) )[0]
           await economy.update_one({"id": message.author.id}, {"$inc": {"PAODs": +amount}})
           await message.channel.send(f'{message.author} gets {amount} in PAODs bank')```
i want to make this command guild only
slate swan
#

yes.

limber bison
slate swan
#

not a command

#

and just add a conditional as I said

limber bison
#
@commands.Cog.listener()
    async def on_message(self , message):
      if message.guild != None:
        if message.author.id == 990358952632021043:
            return

        bucket = self.message_cooldown.get_bucket(message)
        retry_after = bucket.update_rate_limit()

        if retry_after:
          pass
        else:
          bal = await economy.find_one({"id": message.author.id})
          if bal is None:
            await self.open_account(message.author.id)
          else:  
           amount = random.choices([random.randint(0, 10) , random.randint(11, 20) ] ,weights = (0.9, 0.1) )[0]
           await economy.update_one({"id": message.author.id}, {"$inc": {"PAODs": +amount}})
           await message.channel.send(f'{message.author} gets {amount} in PAODs bank')```
#

this will work i think

#

gimme a sec

slate swan
#

Just a tip to write better code: you can also avoid the extra indentation for the entire listener if you aren't adding an else: clause by inverting the boolean logic and adding a return statement. That was probably a confusing sentence, so here's an example:

async def on_message(message):
    if message.guild is not None:
        ...
        # unnecessary indentation
async def on_message(message):
    if message.guild is None:
        return
    ... # no extra indent
austere vale
#

is it possible to put video/audio files in an embed? or do they have to be sent outside of it?

austere vale
# slate swan it is possible
@commands.Cog.listener()
  async def on_message_delete(self, message):
    if not message.author.bot:
      embed=nextcord.Embed(title="Message delete", description= f"Deleted by {message.author.mention} in {message.channel.mention}",color=0xfd9fa1, timestamp=datetime.datetime.utcnow())
      fields=[("Content",message.content,False)]
      for name, value, inline in fields:
        embed.add_field(name=name,value=value,inline=inline)
        if value is None:
          value="_ _"
      i=1
      try:
        embed.set_image(url=message.attachments[0].proxy_url)
        await self.bot.get_channel(933978399280599080).send( embed=embed)
        while i<len(message.attachments):
          await self.bot.get_channel(933978399280599080).send(message.attachments[i].proxy_url)
          i+=1
        return

this is my message to log deleted messages. how can i make it work for video and audio files too instead of just pictures?

slate swan
slate swan