#Basic Pycord Help (Quick Questions Only)

1 messages · Page 28 of 1

round rivet
#

I have my website in a Website directory on the root account so I'd be using WORKDIR /Website

vapid pumice
shell hornet
#

issue.

Traceback (most recent call last):
  File "/home/eniuu/Desktop/Stuff/discordbotyIpyton/ppts bot/ppts bot.py", line 12, in <module>
    client = discord.Bot()
AttributeError: module 'discord' has no attribute 'Bot'
shell hornet
round rivet
#

And install py-cord not pycord

vapid pumice
#

So when attempting to define my worker directory - I simply need to consider the path in which my main.py resides, no?

#

Because that shit doesn't seem to be working >.<

proud mason
young bone
#

uninstall pycord

silver moat
silver moat
proud mason
young bone
vapid pumice
silver moat
proud mason
young bone
#

k

round rivet
silver moat
proud mason
vapid pumice
proud mason
vapid pumice
#

pwd tells me my path is C:\LocalCode>

#

I specify that and get the same error

proud mason
vapid pumice
#

C:\LocalCode\kidsoftheapocalypse\main.py

round rivet
#

make sure Dockerfile has a capital D

proud mason
#

and use that.

#

try C:\LocalCode\kidsoftheapocalypse ig

vapid pumice
#

this is the code:

FROM python:3.10-alpine

WORKDIR C:\LocalCode\kidsoftheapocalypse\

COPY requirements.txt ./
RUN pip3 install -r requirements.txt

COPY . .

CMD [“python3”, “main.py”] 
proud mason
#

dk then. havent done docker before. i wanna use it but idk where to start and what guides to use

round rivet
#

it's named Dockerfile not dockerfile right

vapid pumice
vapid pumice
#

I have no clue where I went wrong, and I've been back through the process 5 times. I get the same result every time

proud mason
# silver moat google

yeah but looking for some basic stuff. last time i got stuff for more advanced things. will see again tho

vapid pumice
#

Tried changing path - changing drives - changing images

round rivet
vapid pumice
proud mason
#

must be the issue

round rivet
#

try using a normal terminal

vapid pumice
#

okay, so I'm so sorry I'm such a noob..what is considered a "normal terminal"?

round rivet
#

like

#

command prompt

vapid pumice
#

got it! Will try!

round rivet
#

hit win+r and type in cmd

proud mason
round rivet
proud mason
#

mhm that thing

vapid pumice
#

Yea, no still jack shit from the CMD Prompt. I'm stuck on this one 🥹

proud mason
#

did you go to the directory your files are in?

vapid pumice
#

I THINK IT'S WORKING

proud mason
#

cd C:\LocalCode\kidsoftheapocalypse iirc. i have forgotten how windows does it

proud mason
#

👀

vapid pumice
#

omg a new error 🥲 pepechefkiss

proud mason
vapid pumice
severe dawn
#

is there a way to add "extra attributes" to a slash command? I'm creating my own help command, and I need a way to implement a usage argument which I would then display in said custom help command.

proud mason
vapid pumice
#

Now I can't get pipreqs to work omg XD

#

This has been a rough day, my friends

silver moat
#

this is basic python

#

you are making a comparison between two values. what is the comparator

#

did you mean select.values[0] == "4":?

proud mason
#

man really needs his own help channel

vapid pumice
proud mason
vapid pumice
#

Error: failed to build wheels for numpy which is required to install project.tmol

Yet my numpy is up to date

#

like wut

#

Updated numpy, checked location, downgraded python - to no avail.

#

I'm gonna have to call it for now...in the mean time, any other suggested methods of distribution to Digital Ocean other than Docker? It seems I may have to restart with a new distro :/

copper dew
copper dew
fiery tiger
#

How can i connect my postgresql database to an vps?

#

i forgot the command..

#

nvm another error now

#

the migrations failed tho bruh

#

How can i login?

copper dew
limber bison
#

if i have the numbers 1-10. How can i return all combinations of three numbers that add up to be less than 7?

limber bison
#

no its for a bot but im having an aneurism trying to figure out how to write it

silver moat
#
for i in range(1,11):
  for j in range(2, 11):
    for k in range(3, 11):
      if i + j + k < 7:
        print(i,j,k)
#

this is a brute force way

limber bison
#

what if instead of a range, i have 10 random numbers between 200-300 and need combinations of 3 that are less than 750?

#

thats closer to what im actually dealing with

silver moat
#
nums = [200, 250, 300, 350, 400...]

for i in nums:
  for j in nums:
    for k in nums:
      if i+j+k < 750:
        print(i,j,k)
#

nums is the list of numbers

limber bison
#

oh ok tyvm my squishy friend

silver moat
#

yw

#

This is O(n^3)

fringe socket
#

Some Discord bots like Crafty, have no bot status at all. No offline, no online, no idle, no do not disturb. Just. Nothing. How do I do this for my Discord bot?

copper dew
copper dew
rugged lantern
#

no

loud holly
#

Just paginator and their examples...

#

#help-rules

fringe socket
#

No one is going to spoonfeed you. Does anyone even read #help-rules ?

fringe socket
#

You know how some bots join servers FOR you when you add them to your server? How can I implement that into my bot?

cyan quail
fringe socket
#

Which section is it?

#

Sorry, got 0 hours of sleep last night, don't want to strain my eyes for too long.

cyan quail
#

well i just linked the scopes

#

probably guilds.join

fringe socket
#

OK will look into

#

For now my bot just DMs the owner of the guild in question with an embed including a link to the server

#

Also, how do I make a URL button?
For some reason mine isn't working.

I don't have access to the code rn.

rugged lantern
#

crazy

fervent cradle
#

i am trying to get an output like (Screenshot above) for the whitelist roles and this is my code

@inviteblocker.command(description='Shows the current status of the inviteblocker')
    async def status(self, ctx):
        check = await db.run_query(f'select exists(select * from inviteblocker where guild_id = {ctx.guild.id})')
        if check[0]['exists'] == True:
            rsrc = await db.run_query(f'select whitelist_roles from inviteblocker where guild_id = {ctx.guild.id}')
            if rsrc == None:
                rlist = 'none'
            else:
                rlist = rsrc[0]['whitelist_roles']
            ibsembed = discord.Embed(title=f'Inviteblocker status for {ctx.guild.name}', description=f'Status: true\n**Whitelist roles**\n{roles.mention for roles in rlist}')
            await ctx.respond(embed=ibsembed)
        else:
            ibsembed = discord.Embed(title=f'Inviteblocker status for {ctx.guild.name}', description=f'Status: false')
            await ctx.respond(embed=ibsembed)
#

but instead i am getting an output like this

cyan quail
#

Also you'd probably want to use string joining

simple canopy
#

light theme 💀

fervent cradle
fervent cradle
#

yes

#

extracted from a database

cyan quail
#

There are two main methods;

  • use guild.get_role(id) to get the object, then you can use .mention
  • just format the ID with an fstring like f"<@&{id}>"
fervent cradle
cyan quail
#

Uhh if you want a user it'd be bot.get_user or guild.get_member

fervent cradle
#

wait no i mean sorry to role types not user types

cyan quail
#

You'd have to use get_role on each ID in the list separately

reef ore
#

hello, got a question - is there any way to get a message (or its ID) from interaction coming from clicking a button on that message?

cyan quail
#

interaction.message

reef ore
#

thank you! 🙂

fervent cradle
fervent cradle
cyan quail
#

well yeah like using a for loop, or if you wanna be weird convert the entire list to string and use replace to remove brackets and commas

#

but there's not much reason to when join is designed for the task

vapid pumice
#

Hii - I'm trying to run my bot with VM2, but I'm receiving this error...

[PM2][ERROR] Interpreter python is NOT AVAILABLE in PATH. (type 'which python' to double check.)

I have double checked that python is up to date AND actually in PATH, but still receive this error. I'm in windows 10 and which python is not an executable command. Any ideas as to how I can fix this?

Note: I'm attempting to do this in CMD Prompt - is this a problem?

cyan quail
#

what about python3 instead of python

vapid pumice
cyan quail
#

yeah idrk much about pm2

#

might be best to google or maybe find a server that's dedicated to it

vapid pumice
cyan quail
#

rip

vapid pumice
thorny breach
#

Hi, does anyone know a way to get the client into a dynamic cooldown from a cog?

def cooldown_core(message:discord.Message):
    if message.author.id == client.owner.id: # I need client here
        return False
    return commands.cooldown(3,10)

# ...

AC = discord.ApplicationContext
class CoreCog(discord.Cog):
    def __init__(self, client:commands.Bot):
        self.client = client

    # ...

    @slash_command(name="test", description="Testing cooldowns")
    @commands.dynamic_cooldown(cooldown_core)
    async def test(self, ctx:AC):
        await ctx.respond("Message Sent!")
wary rover
#

Hi there!
Do you know how to retrieve the content of the response to a slash command?

#

I can edit it but I can't get the content of the message that the bot answers... I may have forgotten something

young bone
#

message = ctx.respond()
print(message)?

wary rover
copper dew
#

I used to use pm2 but it isn't the best way to use in docker images

spice oyster
#

Is there a way to edit a message as a response to an interaction and then, after x seconds, revert that change by making another edit within the same callback? Solved but still interested to know if there are better alternatives.

#

The only way I could think of is to rely on on_message_edit() and check if the message being edited needs to be edited back. Solved in a different way (see below).

#

I've managed to edit it back by using interaction.edit_original_response() but the file attached to the message (that I use as thumbnail for the embed) is either stopping the edit (if file is being passed as parameter) or incorrectly showing the old thumbnail outside of the embed (if file is not being passed as parameter). Any ideas? Solved by passing attachments = [].

thorny breach
cyan quail
thorny breach
vapid pumice
proud mason
#

or --interpreter=/path/to/bin/python

proud pagoda
#

If you have a credit card, then Railway is good as it gives you $5 of usage for free monthly with no hour limit

#

Oh, ok

#

Are you a student?

#

Yeah but that's paid

#

And github student dev pack only gives you 3 months free of that

#

But if you're a student, you could try out microsoft azure, although that can be a bit difficult to set up

#

Since that's a full vps that you're given with complete access

proud pagoda
#

Oh alright

undone falcon
#

is there a way to run a async function in a other thread than the main asynco loop where the bot is running ? That function takes a long time to execute, and I get bot not responding error while it run, so I want to run it in a other thread

vapid pumice
full basin
proud cargo
#

asking because theres all sorts of random features ive never heard of; is it possible to get a calendar ui in a slash command Option?

silver moat
cyan quail
proud cargo
#

Oh cool

cyan quail
proud cargo
cyan quail
#

well that'd be #discord-api-updates

rare ice
#

.tag noreplit

winter condorBOT
#

Why NOT to use Repl as a hosting platform

You should not use Repl.it to host your bot.
It may be a nice option as its "free" but you should use something else considering the major flaws.

  • The machines are super underpowered.
    • This means your bot will lag a lot as it gets bigger.
  • You'll need a web server alongside your bot to prevent it from being shut off.
    • This isn't a trivial task, and eats more of the machines power.
  • Repl.it uses an ephemeral file system.
    • This means any file you saved via your bot will be overwritten when you next launch.

IMPORTATNT

  • They use a shared IP for everything running on the service.
    This one is important - if someone is running a user bot on their service and gets banned, everyone on that IP will be banned. Including you.

Please avoid using repl.it to host your bot. It's not worth the trouble.

If you're looking for free options, consider using AWS/Google Cloud Platform/Azure and its respective free tiers or just pay for an actual VPS.

rare ice
#

Railway

#

I recommend imo

#

But you should just get a VPS

#

It’s worth it

#
Railway

Railway is an infrastructure platform where you can provision infrastructure, develop with that infrastructure locally, and then deploy to the cloud.

gleaming falcon
#

Having a brainfart. When loading the whole bot, cogs can have a listener() for on_ready to do any fun setup things.

When atomically reloading the cog, you can use self.bot.is_ready, but since it's the init, can't naturally call async methods. Are there any built-ins that handle this, or do I have to put in the boilerplate asyncio methods (asyncio.ensure_future? self.bot.loop.create_task?)

full basin
#

bot.dispatch("ready")

gleaming falcon
# full basin bot.dispatch("ready")

I initially thought that, but the dispatch from reloading one Cog would cause the on_ready listeners in all Cogs to fire, no? And I could personalize it per Cog, but that's janky.

#

I guess that's simple enough.

  def __int__(self, bot):
    # ...
    if self.bot.is_ready():
      self.bot.loop.create_task(self.on_ready())
silver moat
#

send requirements.txt

fringe socket
#

yep if you want to use pycord you need to install py-cord. crazy huh?

silver moat
#

well, discord.py and py-cord use the same namespace so conflicts

fringe socket
#

Which would you say is better, now that discord.py is back?

React with pycord for Py-cord
React with Python for discord.py

Opinions?

silver moat
#

add wikipedia==1.4.0 in requirements.txt

fringe socket
#

That pretty much goes for anything haha

#

YouTube Coding Videos are useless.

#

You can't understand anything.

silver moat
#

ikr imagine using replit after railway

fringe socket
#

Yeah. Sadly I live in Oceania, so I get an average of 82 Ping. But, lately I've been getting something like 1830 ping.

silver moat
#

iirc railway has servers on the east coast, while discord's servers are in virginia, so basically next door

#

it was just public info

#

but sure

vapid pumice
#

Feel like this is a MEGA basic question (I'm sorry :(), but..

how do I send a message after using interaction.response.defer since I cannot use interaction.response.send_message considering the interaction has already been responded to? 🥲

vapid pumice
silver moat
#

oops, just send

vapid pumice
# silver moat oops, just send

omg thank you thank you thank you!!!

If you have a moment, what would be the proper way to find out a question like that without bothering a human? Like, how to retrieve that from docs, if you might know?

silver moat
#

?tag ex

silver moat
#

?tag guide

obtuse juncoBOT
silver moat
#

?tag docs

obtuse juncoBOT
vapid pumice
# silver moat ?tag ex

ahh, the examples are what I needed! Thank you!!
( I try to read the docs, but my pea brain gets confused 1awkwardlaugh )

silver moat
#

but I think the less this channel is used, the better

vapid pumice
# silver moat but I think the less this channel is used, the better

Totally agree. I want to get better at utilizing the resources available so that time here for others can be minimal from the perspective of "let me assist the noob" which..unfortunately is me a lot right now, but I will grow and pass it along however I'm able.

I really really appreciate the kindness of the people here. I can't thank you all enough, actually...

undone falcon
#

I am new to database (using SQlite3) and I was wondering why when I delete a Guild(it was deleted correctly I checked) it does not delete all the 3 other rows in table that I reference with ON DELETE CASCADE

CREATE TABLE IF NOT EXISTS Guild ( 
    id                   INTEGER NOT NULL  PRIMARY KEY  ,
    timezone             TEXT
 );

CREATE TABLE IF NOT EXISTS Member_time_role ( 
    id                   INTEGER NOT NULL    ,
    creation_time        timestamp NOT NULL  ,
    deltatime            TIME NOT NULL    ,
    member_id            INTEGER NOT NULL    ,
    guild_id             INTEGER NOT NULL    ,
    CONSTRAINT pk_Member_time_role PRIMARY KEY ( id, member_id, guild_id ),
    FOREIGN KEY ( guild_id ) REFERENCES Guild( id ) ON DELETE CASCADE 
 );

CREATE TABLE IF NOT EXISTS Time_role ( 
    id                   INTEGER NOT NULL    ,
    guild_id             INTEGER NOT NULL    ,
    deltatime            TIME NOT NULL    ,
    CONSTRAINT pk_Time_role PRIMARY KEY ( id, guild_id ),
    FOREIGN KEY ( guild_id ) REFERENCES Guild( id )  ON DELETE CASCADE
 );

CREATE TABLE IF NOT EXISTS Global_time_role ( 
    id                   INTEGER NOT NULL    ,
    end_datetime         timestamp NOT NULL    ,
    guild_id             INTEGER NOT NULL    ,
    delete_from_guild    BOOLEAN NOT NULL    ,
    CONSTRAINT pk_Global_time_role PRIMARY KEY ( id, guild_id ),
    FOREIGN KEY ( guild_id ) REFERENCES Guild( id ) ON DELETE CASCADE 
 );
fringe socket
#

Hey! How do I make a discord bot grab a specific user's PFP?

I know that I can use

avatar = member.display_avatar.url

but I'm trying to make it get a pre-defined user's pfp.
when I use the user's actual pfp url, it means that if they change pfp, it will disappear

drifting sleet
#

🤔

#

There are like 3 attributes for avatar, never knew what's the actual difference

mental maple
#

how to send a embed with a view in a specified channel?
i use :py await self.current.source.channel.send(embed=self.current.create_embed(),view=MusicUI(MusicV2.get_voice_state(self._ctx)))
but it seems doesnt sending the embed, but dont threw error tho

spice oyster
tribal bough
#

while installing pycord i am getting this error ERROR: Could not build wheels for aiohttp, frozenlist, multidict, yarl, which is required to install pyproject.toml-based projects

cobalt tangle
#

why am I getting this error:

local variable 'x' referenced before assignment

#

My economy check function:

#
def check(user_id):
    result = collection.find({})
    for r in result:   
        print(r["user"])
        y = r["user"]
        if y == user_id:
            x = True
            return x
        else:
            x = False```
#

My beg command:

#
    @economy.command(description="Beg people for money!")
    @commands.cooldown(1, 360, commands.BucketType.user)
    async def beg(self, ctx):
        x = check(ctx.author.id)
        emoji = get_emoji(ctx.author.id)
        if x == True:
            gain = random.randint(0, 300)
            add_bal(gain, ctx.author.id)
            embed=discord.Embed(title="Beg", description=f"After a long day of sitting without food, you gained {emoji} {gain}")
            await ctx.respond(embed=embed)
        else:
            await ctx.respond("Please do `/setup` first!")
#

The cmd works for ppl verified

#

but doesnt send the error msg Please do setup for ppl not verified

spice oyster
cobalt tangle
#

Imagine if the order was as if:

id1 = False, id2 = True, id3 = False (By True, i mean the ID matches the guy im looking for)

#

It iterates through the ids

#

It changes x to True in the mid

spice oyster
#

You can use break there.

cobalt tangle
#

but x becomes False in the end

cobalt tangle
#

ty

#

@spice oysterstill getting the same issue

spice oyster
#

I had a suspect it wouldn't have been enough. I don't know what else is wrong. Can you share the full traceback?

cobalt tangle
#
0|main     |   File "/usr/local/lib/python3.10/dist-packages/discord/bot.py", line 1009, in invoke_application_command
0|main     |     await ctx.command.invoke(ctx)
0|main     |   File "/usr/local/lib/python3.10/dist-packages/discord/commands/core.py", line 359, in invoke
0|main     |     await injected(ctx)
0|main     |   File "/usr/local/lib/python3.10/dist-packages/discord/commands/core.py", line 127, in wrapped
0|main     |     ret = await coro(arg)
0|main     |   File "/usr/local/lib/python3.10/dist-packages/discord/commands/core.py", line 1201, in _invoke
0|main     |     await command.invoke(ctx)
0|main     |   File "/usr/local/lib/python3.10/dist-packages/discord/commands/core.py", line 359, in invoke
0|main     |     await injected(ctx)
0|main     |   File "/usr/local/lib/python3.10/dist-packages/discord/commands/core.py", line 135, in wrapped
0|main     |     raise ApplicationCommandInvokeError(exc) from exc
0|main     | discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: UnboundLocalError: local variable 'x' referenced before assignment
#

@spice oyster

pseudo glen
#

what's ur code now

cobalt tangle
#

also, x is not defined globally anywhere

#
def check(user_id):
    result = collection.find({})
    x = False
    for r in result:   
        print(r["user"])
        y = r["user"]
        if y == user_id:
            x = True
            break
    return x

fervent cradle
#

how send files like this

ctx.send(there file)
cobalt tangle
#

await ctx.send(file=file)

fervent cradle
#

ok i test

cobalt tangle
#

with the import

fervent cradle
#

yeah i know

cobalt tangle
#

discord.File()

fervent cradle
#

@cobalt tangle can you send etc

cobalt tangle
#

file=discord.File("file.txt")

fervent cradle
#

thanks

cobalt tangle
cobalt tangle
fervent cradle
#

ok

#

is eny way to randomize what its send(i want my bot send random videos what i added in)

spice oyster
spice oyster
cobalt tangle
young bone
spice oyster
#

Also that. I doubt they need to use the secrets module in this case but it's an option even with that.

simple canopy
#

Guilded

#

💀

fervent cradle
#

yeah too big file

spice oyster
fervent cradle
#
#code
import discord
import discord.ext
import random
from config import TOKEN
videolist = [discord.File("test.gif"),discord.File("pro.gif")]
tiedosto = random.choice(videolist)
bot = discord.Bot(command_prefix='>',intents=discord.Intents.all())

@bot.command(description = "mitä pitäis sanoo")
async def sano(ctx, sanominen):
    await ctx.send(sanominen)
    await ctx.respond(content = "nyt on lähetetty", ephemeral = True)
@bot.command(description = "heittä kivi")
async def kivi(ctx):
    await ctx.respond(file=tiedosto)
bot.run(TOKEN)

#help
#ephemeral = True tarkottaa että on vain sinä voit nähdä viesti
#miten lähettee file file=discord.File("file.")
#

cle : The term 'cle' is not recognized as the name of a cmdlet, function, script
file, or operable program. Check the spelling of the name, or if a path was inc
luded, verify that the path is correct and try again.
At line:1 char:1

  • cle c:; cd 'c:\Users\Nooa\Desktop\koodi\discord test'; & 'C:\Users\No ...
  •   + CategoryInfo          : ObjectNotFound: (cle:String) [], CommandNotFoundE  
     xception
      + FullyQualifiedErrorId : CommandNotFoundException
    
    

Ignoring exception in command kivi:
Traceback (most recent call last):
File "C:\Users\Nooa\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\commands\core.py", line 124, in wrapped
ret = await coro(arg)
File "C:\Users\Nooa\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\commands\core.py", line 974, in _invoke
await self.callback(ctx, **kwargs)
File "c:\Users\Nooa\Desktop\koodi\discord test\main.py", line 15, in kivi
await ctx.respond(file=tiedosto)
File "C:\Users\Nooa\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\commands\context.py", line 282, in

#

respond
return await self.interaction.response.send_message(
File "C:\Users\Nooa\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\interactions.py", line 825, in send_message
await self._locked_response(
File "C:\Users\Nooa\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\interactions.py", line 1090, in locked_response
await coro
File "C:\Users\Nooa\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\webhook\async
.py", line 213, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction

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

Traceback (most recent call last):
File "C:\Users\Nooa\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\bot.py", line 1088, in invoke_application_command
await ctx.command.invoke(ctx)
File "C:\Users\Nooa\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\commands\core.py", line 374, in invoke
await injected(ctx)
File "C:\Users\Nooa\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\commands\core.py", line 132, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction

#

beter the errpr

spice oyster
#

Are the files in the same folder as the file calling them?

fervent cradle
#

like this
ctx.defer()@bot.command(description = "heittä kivi")
async def kivi(ctx):
await ctx.respond(file=tiedosto)

fervent cradle
spice oyster
fervent cradle
#

like this @bot.command(description = "heittä kivi")
ctx.defer() async def kivi(ctx):
await ctx.respond(file=tiedosto)

spice oyster
#

Please, this is basic stuff. Inside the function.

#
async def kivi(ctx):
    await ctx.defer()
    await ctx.respond(file=tiedosto)
fervent cradle
#

@spice oyster thanks A LOT I think you should get some helpper role

sleek haven
#

how to i disable the button

#

because i can still click it but it wont edit but i want so its disabled "cant be clicked"

spice oyster
young bone
#

you first kick and then mention the member

#

thats why it doesn´t work

#

also at the 3. elif what is riceBot?

#

check for self.client

indigo badger
#

What could I use to alow prefix and slash to run with the ctx part.

#
@bridge.bridge_command()
    async def test3(self, ctx):
        await ctx.reply("Test")
young bone
#

ctx.respond()

#

?

indigo badger
#

As I tryed respond and it said that it was not a attabut of context.

young bone
#

do you have something else installed?

indigo badger
young bone
#

ctx.respond() should work with the bridge

indigo badger
# young bone ctx.respond() should work with the bridge
Ignoring exception in command test3:
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.9/site-packages/discord/ext/commands/core.py", line 181, in wrapped
    ret = await coro(*args, **kwargs)
  File "/home/container/cogs/slash.py", line 50, in test3
    await ctx.respond("Test")
AttributeError: 'Context' object has no attribute 'respond'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.9/site-packages/discord/ext/commands/bot.py", line 360, in invoke
    await ctx.command.invoke(ctx)
  File "/home/container/.local/lib/python3.9/site-packages/discord/ext/commands/core.py", line 927, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "/home/container/.local/lib/python3.9/site-packages/discord/ext/commands/core.py", line 190, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Context' object has no attribute 'respond'
#

It pops up this error when I have respond there.

young bone
#

can you show the pip list and also which version is installed?

indigo badger
young bone
#

yes

indigo badger
#
aiofiles==0.8.0
aiohttp==3.7.4.post0
aiosqlite==0.17.0
anyio==3.5.0
astunparse==1.6.3
Async-OAuthlib==0.0.9
async-timeout==3.0.1
attrs==21.4.0
blinker==1.4
braceexpand==0.1.7
cachetools==5.0.0
certifi==2021.10.8
cffi==1.15.0
chardet==4.0.0
charset-normalizer==2.0.12
click==8.0.4
colorama==0.4.4
h11==0.12.0
h2==4.1.0
hpack==4.0.0
httpcore==0.14.7
httpx==0.22.0
hypercorn==0.13.2
hyperframe==6.0.1
idna==3.3
import-expression==1.1.4
itsdangerous==2.1.1
Jinja2==3.0.3
jishaku==2.4.0
MarkupSafe==2.1.0
multidict==6.0.2
oauthlib==3.2.0
Pillow==8.4.0
pip==22.0.4
priority==2.0.0
py-cord==2.0.0b7
pycparser==2.21
PyJWT==2.3.0
PyNaCl==1.5.0
python-dateutil==2.8.2
requests==2.27.1
rfc3986==1.5.0
roblox==2.0.0
setuptools==58.1.0
six==1.16.0
sniffio==1.2.0
toml==0.10.2
typing_extensions==4.1.0
urllib3==1.26.9
Werkzeug==2.0.3
wheel==0.37.1
wsproto==1.1.0
yarl==1.7.2
easy-pil==0.1.9
#

That is all I have installed.

young bone
#

can you update it?

#

you still have b7, look at #library-updates

indigo badger
#

Is there a problum with those kind of commands in b7?

#

@young bone

young bone
#

update it and try it again

indigo badger
#
File "/home/container/.local/lib/python3.9/site-packages/discord/cog.py", line 733, in _load_from_module_spec
    spec.loader.exec_module(lib)  # type: ignore
  File "<frozen importlib._bootstrap_external>", line 850, in exec_module
  File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
  File "/home/container/cogs/slash.py", line 5, in <module>
    from discord import  Option, permission
ImportError: cannot import name 'permission' from 'discord' (/home/container/.local/lib/python3.9/site-packages/discord/__init__.py)
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
  File "/home/container/Bot.py", line 777, in <module>
    Client.load_extension(f'cogs.{filename[:-3]}')
  File "/home/container/.local/lib/python3.9/site-packages/discord/cog.py", line 869, in load_extension
    self._load_from_module_spec(spec, name)
  File "/home/container/.local/lib/python3.9/site-packages/discord/cog.py", line 736, in _load_from_module_spec
    raise errors.ExtensionFailed(key, e) from e
discord.errors.ExtensionFailed: Extension 'cogs.slash' raised an error: ImportError: cannot import name 'permission' from 'discord' (/home/container/.local/lib/python3.9/site-packages/discord/__init__.py)
#

It did not do that before.

#

Is import name 'permission' from 'discord' not part of the py-cord==2.2.0?

#

You still there?

indigo badger
#

Anyone?

indigo badger
#

?

indigo badger
#

?

young bone
#

commands.is_owner()?

indigo badger
#

?

#
@bridge.bridge_command()
    async def test3(self, ctx):
        await ctx.respond("Test")
#

That is the code that is with it.

young bone
#

if your bot a bridge bot?

#

client = bridge.Bot()

indigo badger
#

Will prefix commands still work in bridge bot?

young bone
#

yes

indigo badger
#

So all it will change is allowing bridge commands to work?

young bone
#

yes

indigo badger
#

Or is that all.

spice oyster
#

What do I need to know while creating a new instance to host my Discord bot on Oracle?

spice oyster
#

What's the easiest way to upload all my files? I'm a bit lost after creating the instance.

rugged lantern
#

google

proud pagoda
#

Um that's not how it works

#

You can't import modules to the requirements.txt file

#

And random is already built into python so you don't have to specify it in the file

rare ice
#

@fervent cradle Please don’t ping support members randomly.

rare ice
#

Slash command can’t have an alias

#

So remove aliases

#

.docslink discord.SlashCommand

winter condorBOT
rare ice
#

ooooo new docs

#

It shouldn’t

#

Make sure you have NO other slash commands with the same thing

#

Double check every file

full basin
#

The function name is irrelevant if you override the name on the decorator.

rare ice
#

The error wouldn’t be caused by anything else, so you must have it duplicated somewhere.

#

You can also try removing the slash command itself, start the bot, then add it back then restart it

#

good idea

spice oyster
#

With some editors you can open the project folder and easily search a string across all files.

rocky raft
#

I created a simple bot with slash commands in a COG but the CTX object is just the COG itself!? So my code fails at ctx.respond because obvjously the cog doesnt have that attribute.
So: HOW do you access the actual context of the command invoked like it usually works??

devout anvil
#

you dont need to do datetime.timedelta, just put 5 as the argument

silver moat
#

it takes a datetime.timedelta object

north tartan
#

why doesn't my discord bot work on other servers?

silver moat
#

define doesn't work

#

.tag idw

winter condorBOT
#

Saying it doesn't work or asking what's wrong with this code? is not helpful for yourself or others.
Describe what you expect and/or tried (with your code), and what isn't going right.
Please provide any errors you get for optimal assistance.

north tartan
#

added my bot to another server and it doesn't work

silver moat
#

define doesn't work

north tartan
#

When i start the bot i don't get the list of slash commands even when i have the server id specified

#

that's the problem

silver moat
#

remove the guild_ids parameter

#

will make the slash commands global

north tartan
#

Thank you

#

it was that thank you very much

#

and why does this appear

copper dew
north tartan
#

oops i saw the error

copper dew
#

ok

fiery skiff
#

how do you atcually program the bot?

#

like where do i code?

young bone
full basin
#

lmao

young bone
spare juniper
young bone
fast totem
#

I guess he's talking about the ide

fervent cradle
#

how do I go about creating a queue for my music command, it simply has to register a queue and play it as the user gives the command

this is what I've tried so far

async def play(ctx, search: str):
    await ctx.defer()
    try:

        vc = ctx.voice_client # define our voice client

        if not vc: # check if the bot is not in a voice channel
            vc = await ctx.author.voice.channel.connect(cls=wavelink.Player) # connect to the voice channel

        if ctx.author.voice.channel.id != vc.channel.id: # check if the bot is not in the voice channel
            return await ctx.respond("You must be in the same voice channel as the bot.") # return an error message
        global song
        song = await wavelink.YouTubeTrack.search(query=search, return_first=True) # search for the song


        if not song: # check if the song is not found
            return await ctx.respond("No song found.") # return an error message

        await vc.play(song) # play the song
        await ctx.respond(f"Now playing: `{vc.source.title}`") # return a message
        while True:
            await asyncio.sleep(30)

            if vc.is_playing() == False:
                await vc.disconnect()
                await ctx.respond("Left due to inactivity")
                break
            

    except Exception as e:
          #my error handler code```
#

I'm working on the example from the pycord examples^^

spice oyster
# fiery skiff how do you atcually program the bot?

In this video I am going to show How to Set Up Python Development environment in Visual Studio Code in windows 10. I am also going to show ow to debug your python code using vs code. This process will also cover How to Install Python and Visual Studio Code for Windows 10. You are goint to Learn how to use the Visual Studio Code which is a cros...

▶ Play video
fiery skiff
#

do i need to download smt?

#

like, where do i go to program my bot?

spice oyster
sage eagle
#

this is totally not the correct server to ask in, but do anyone know how i can make a function that, when called, knows if it was called using async or normal sync, and calls the appropriate function? This way you could do for example

async def example1():
  await hello_world()

#sync
def example2():
  hello_world()

Behind the scenes it actually calls two different functions.

I know this is possible in some way, as I've seen it with a library i've used, however when i tried checking the code on how they did it, I didn't really get very far as it was very confusing.

Any ideas?

pseudo dawn
#

Hi, dunno, if I should open my own thread, but I would like to add some prometheus metrics to my bot.
I don't know if the prometheus library does interfere with pycord, since both of them use webservers.

I just wanted to ask beforehand, so I don't continue developing the Bot and finding out months later, that something breaks in a weird way.

spice oyster
cosmic cobalt
#

why does this happen?

AttributeError: loop attribute cannot be accessed in non-async contexts. Consider using either an asynchronous main function and passing it to asyncio.run or using asynchronous initialisation hooks such as Client.setup_hook```
fervent cradle
#

how do I implement disconnect and cleanup for a vc?

rugged lantern
#

no, we will not do your homework

young bone
#

pls stay in one channel

wild socket
#
  File "/home/container/.local/lib/python3.9/site-packages/discord/client.py", line 377, in _run_event
    await coro(*args, **kwargs)
  File "/home/container/cogs/metrics.py", line 17, in on_guild_remove
    embed = discord.Embed(title = "Left a server", description = f"Server Name: {guild.name}\nServer ID: {guild.id}\nServer Owner: {guild.owner}\nServer Owner ID: {guild.owner_id}\nServer Member Count: {guild.member_count}", color = discord.Color.red())
  File "/home/container/.local/lib/python3.9/site-packages/discord/guild.py", line 1031, in member_count
    return self._member_count
AttributeError: _member_count

weird hmm

wild socket
#

and its version specific i suppose, as its fine for my development server

young bone
#

you could do len([member for member in guild.members if not member.bot])

wild socket
young bone
wild socket
young bone
#

that one works for me

wild socket
young bone
#

2.2.0

wild socket
#

i have 2.1.0 installed in development serv

#

hmm

#

guess i ll have to downgrade the version

young bone
#

do you have something else installed?

wild socket
#

nope

pseudo glen
#

or try it again?

spice oyster
#

Is there a way to squash commits that happened before a merge? I'm getting this error. eddaniSherlock

copper dew
cyan lark
#
import discord
from discord.ext import commands 
from discord.commands import Option
import asyncio


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

@bot.event
async def on_ready():
    print(f"bot loaded with {int(bot.latency*100)} ping")

@bot.slash_command(guild_ids = [not showing my id server], description = "Test 1")
async def hello(ctx,
    name:Option(str,"Enter your name"),
    age:Option(int, "Enter your age", default= "not added",required= False)):
    interaction = await ctx.respond("Done for you see!")
    await asyncio.sleep(1)
    await interaction.edit_original_message(content = f"your Name: {name}\nAge: {age}")
spare juniper
#

IDLE works too

full basin
#

You mean IDE.

spare juniper
#

The python ide

#

The not good one that comes with python

fervent cradle
#

how can i check if the author of the message is the client in an on_message event in a cog, without using the bot's id directly in the code?

if message.author.id == #bot id function:
                pass
timber skiff
#

Does does one programmatically add a reaction to a message?

spice oyster
fervent cradle
#

is it possible to have multiple on_message events in the same cog?

#
@commands.Cog.listener()
async def on_message(self, message):
    print('on message event #1')

@commands.Cog.listener()
async def on_message(self, message):
    print('on message event #2')
    
@commands.Cog.listener()
async def on_message(self, message):
    print('on message event #3')
#

i need all the listeners to be called and not just the last one

spice oyster
#

Just do everything in the same listener.

#

You can use ifs to check what you need.

#

You can call functions if the code is too long.

fervent cradle
#

with my code its too complicated for it, and i do not want to rewrite it, since each message event serves a different moderation purpose

#

like one of the event manages the blacklist word filter and the other manages advertisement filter

spice oyster
#

I don't think you have other alternatives.

fervent cradle
fervent cradle
cyan quail
#

because you called all your functions the same name

#

as i said, the docs shows how to do it with different names

fervent cradle
#

ok thank you

reef ore
#

hello, any idea how can i get the selectmenu selected option from interaction?

full basin
reef ore
#

from interaction

rare ice
#

select.values

#

a select callback takes (self, select, interaction)

full basin
#

You receive select ^ on the callback

fallow hawk
#

discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body In data.components: This field is required i keep getting this error on modals and idk why

#

class MyView(discord.ui.View): @discord.ui.button(label="Submit Display Name To Proceed with the Nuke", style=discord.ButtonStyle.danger, emoji="💣") async def button_callback(self, button, interaction): await interaction.response.send_modal(poopmodal(title="Modal via Button")) my code is correct right?

full basin
#

Full traceback

young bone
fallow hawk
#

and was working a bit ago

full basin
#

A full traceback would help to detect what you're missing

fallow hawk
#

ok here it is

#

had to giver the stuff that has my name konk

young bone
#

check the modal if something is only "" or '' without a text or something else

fallow hawk
#

i dont

#

In data.components: This field is required it says this so would it by any chance have new params?

tribal bough
#

while installing pycord i am getting this error ERROR: Could not build wheels for aiohttp, frozenlist, multidict, yarl, which is required to install pyproject.toml-based projects

silver moat
#

create __init__ and put super().__init__

silver moat
fiery skiff
copper dew
silver moat
fiery skiff
#

i know how to use python, i just dont know how i integrate a discord bot in this mess

#

@silver moat ^

copper dew
tribal bough
barren elk
#

Has anyone been able to record using pycord?

#

I tried using the library, but I get errors when I try to record

#

I think the issue was raised earlier here: #998272089343668364 message

#

I get a similar error

#

This is what my error looks like

#
Exception in thread DecodeManager:
Traceback (most recent call last):
  File "/nix/store/2vm88xw7513h9pyjyafw32cps51b0ia1-python3-3.8.12/lib/python3.8/threading.py", line 932, in _bootstrap_inner
    self.run()
  File "/home/runner/Birdy-can-record-audio/venv/lib/python3.8/site-packages/discord/opus.py", line 547, in run
    data.decoded_data = self.get_decoder(data.ssrc).decode(
  File "/home/runner/Birdy-can-record-audio/venv/lib/python3.8/site-packages/discord/opus.py", line 568, in get_decoder
    self.decoder[ssrc] = Decoder()
  File "/home/runner/Birdy-can-record-audio/venv/lib/python3.8/site-packages/discord/opus.py", line 435, in __init__
    _OpusStruct.get_opus_version()
  File "/home/runner/Birdy-can-record-audio/venv/lib/python3.8/site-packages/discord/opus.py", line 362, in get_opus_version
    raise OpusNotLoaded()
discord.opus.OpusNotLoaded
reef ore
#

guys do you know if there is a snippet available anywhere for selectmenu callback usage?

barren elk
fiery skiff
#

i still do not know where i code the bot...

barren elk
# fiery skiff this did not really help me

Learn how to code a Discord bot using Python and host it for free in the cloud using Repl.it.
🚨Note: At 16:43, Replit now has a new method for environment variables. Check the docs: https://docs.replit.com/programming-ide/storing-sensitive-information-environment-variables

Along the way, you will learn to use Repl.it's built-in database and cr...

▶ Play video
copper dew
#

shared ips, poor specs, etc etc

barren elk
#

Oh ok, thanks for letting me know 😃

#

What would you suggest is the best option?

copper dew
barren elk
#

Oh ok

#

I will keep that in mind 😃

copper dew
#

ok

fringe socket
#

How do I make an argument not required? I don't see anything about it in the documentations.

fringe socket
autumn goblet
#

Hello!
I'm trying to create a module for multilingual translation of string . I'm new. Please tell me in which direction to move, maybe there is an example. Here is an example of how I want to implement this:

_(string)
...
    @classmethod
    def get_lang(cls) -> str:
      ...

_ = Local_Class.get_lang
tribal bough
#

while installing pycord i am getting this error ERROR: Could not build wheels for aiohttp, frozenlist, multidict, yarl, which is required to install pyproject.toml-based projects

tiny wagon
tribal bough
rugged lantern
rugged lantern
long latch
#

So i want to put the json data from this url into a paginator with the amount of pages as the amount of emails there are in the account

#

this is how the json looks

#

and how would i display the data on the page according to the data on the email

spare juniper
fiery skiff
#

i mean what website or program do i use to program my bot to do stuff

simple canopy
#

Brain and IDE

#

?tag lp

obtuse juncoBOT
#
simple canopy
#

Learn Python™️ ^

merry briar
#

Why don't slash commands appear? cog

@commands.slash_command(guild_ids=[GUILD_ID], description="test")

winter condorBOT
# merry briar Why don't slash commands appear? cog @commands.slash_command(guild_ids=[GUILD_I...

Checklist for Application Commands Not Showing Up:
• Does your bot have the application.commands scope?
• Are you loading cogs before on_ready and on_connect?
• Is on_connect not overridden?
• Did you update to the newest version of py-cord (tag: install)?
• Is User Settings > Accessibility > Chat Input > Use legacy chat input turned off?
• Did you share your code and errors?
• Do you still have libraries that conflict with the discord namespace (e.g. discord.py)?

merry briar
# spice oyster .tag commandnoshow
  1. yes

  2. yes

  3. No

  4. Just installed

  5. yes

  6. aiohttp==3.8.3, aiosignal==1.2.0, async_timeout==4.0.2, attrs==22.1.0, charset_normalizer==2.1.1, dnspython==2.2.1, frozenlist==1.3.1, fuzzywuzzy==0.18.0, idna==3.4, multidict==6.0.2, pip==22.2.2, py_cord==2
    .2.2, pymongo==4.3.2, python_dotenv==0.21.0, setuptools==65.3.0, wheel==0.37.1, yarl==1.8.1

  7. Minimal code

main

import discord
from discord.ext import commands

from dotenv import load_dotenv
import os

load_dotenv()

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

bot = discord.Bot(intents=intents)

@bot.event
async def on_ready():
    for filename in os.listdir("./cogs"):
        if filename.endswith(".py"):
            bot.load_extension(f"cogs.{filename[:-3]}")

bot.run(os.getenv("TOKEN"))

cogs

import discord
from discord.ext import commands

from dotenv import load_dotenv
import os

load_dotenv()

GUILD_ID = os.getenv("GUILD_ID")


class CogTest(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.slash_command(guild_ids=[GUILD_ID], description="test")
    async def testcmd(self, inter: discord.Interaction):
        await inter.respond("test")


def setup(bot):
    bot.add_cog(CogTest(bot))
spice oyster
merry briar
#

thanks

spice oyster
#

Mistakes happen. eddaniChromie

hollow heath
#

This can't be the best way to do it right?

#
string = ctx.author.name+"#"+ctx.author.discriminator
silver moat
#

what's wrong?

hollow heath
#

Is there any better way to do that?

silver moat
#

I don't think so?

#

doing str(discord.Author) will return the same thing

vague plover
#
import discord
from discord.ext import commands

from datetime import datetime, timezone

from dao import UserActivityDAO

class MemberImportCog(commands.Cog):
    def __init__(self, bot: commands.Bot):
        self.bot = bot

    @commands.slash_command(name='memberImport', description='Import missing members into activity database', guild_ids=[839673797066096660])
    async def memberImport(self, interaction: discord.Interaction):
        activity_timestamp_ids = [
            (str(member.id), datetime.now(timezone.utc)) for member in interaction.guild.members]

        UserActivityDAO.insertMany(activity_timestamp_ids)
        await interaction.response.send_message("Members imported", ephemeral=True)

def setup(bot: commands.Bot):
    bot.add_cog(MemberImportCog(bot))
#

Where am I going wrong in syntax here? It's not hitting the setup when I put a debug point in there and I've been wracking my brain for hours

#

I've tried both @discord.slash_command and @commands.slash_commands. If I indent the command chunk it hits the setup just fine, but then obviously doesn't register the slash command

#

And there's no errors in the console

vague plover
#

pycord

young bone
#

you should use (self, ctx)

#

can you show the pip list?

vague plover
#
aiohttp            3.8.1
aiosignal          1.2.0
async-timeout      4.0.2
attrs              21.4.0
autopep8           1.6.0
certifi            2020.6.20
chardet            4.0.0
charset-normalizer 2.1.0
frozenlist         1.3.0
httplib2           0.18.1
idna               2.10
multidict          6.0.2
pip                20.3.4
psycopg2           2.9.3
py-cord            2.0.1
pycodestyle        2.9.1
pycurl             7.43.0.6
PySimpleSOAP       1.16.2
python-apt         2.2.1
python-debian      0.1.39
python-debianbts   3.1.0
reportbug          7.10.3+deb11u1
requests           2.25.1
setuptools         52.0.0
six                1.16.0
toml               0.10.2
urllib3            1.26.5
wheel              0.34.2
yarl               1.7.2```
#

changing to applicationcontext didn't do it either

#

Been a little while since I updated pycord, not sure if .2 is out yet

#

Welp I probably should've just updated it from the start 🙃 Updated it now and got an error message LMAO

#

TL;DR message names have to be all lowercase, I completely spaced on that

merry briar
#
@option("test", description="test", required=True)

How to make a mandatory text field?

#

so that the number could not be entered

merry briar
tribal bough
#

while installing pycord i am getting this error ERROR: Could not build wheels for aiohttp, frozenlist, multidict, yarl, which is required to install pyproject.toml-based projects

tall palm
#

I did something dumb with my code and have since fixed it, but the channel is still stuck trying to send the command 20+ minutes later. Is there anything I can do to clear this?

copper dew
tribal bough
#

Version i am using of pycord

copper dew
tribal bough
copper dew
tribal bough
copper dew
# tribal bough here the full error

Might be something to do with the current platform that u have rn. It should work fine on Windows iirc. It's aiohttp that's having the issue

tribal bough
copper dew
tribal bough
fervent cradle
#

how do i create a custom check for blacklisted users which has a decorator like this ig

@checks.is_blacklisted()
serene spindle
#

How do you get a username without the tag behind it?

serene spindle
reef ore
#

its important for some more complex architectures, when you have several cogs with limited responsibility and you want to create a select menu in one, but intercept the selection in the other

gleaming falcon
#

Basic question. Is there any function that lets me know if a character is an emoji? For visual instance, if an argument to a slash command is “🎉 yes”, I could test that the first character is an emoji.

reef ore
#

in terms of string representation it is not a single character

#

try it - just print it out

copper dew
gleaming falcon
#

Yes, I know that technically it isn’t. I was being simplistic for the sake of assumption. I should still be able to separate it from the rest of the text and determine if it’s a valid emoji

#

Like, could I stuff it into PartialEmoji?

reef ore
reef ore
gleaming falcon
#

Check for it. So I could ask someone to use “<emoji> <text>” as an argument to, say, a poll command, and it would use the emoji when creating the Button (if it was provided)

tall palm
#

Emoji are represented by a long string of numbers: - in Dev mode on Discord you can right-click to Copy the ID. 🎉 is 1032752525809561731, 😅 is 1032720935138111488, etc.
So you could put code to extract the first piece of the entered string and evaluate if it's a number 19 characters long.

(Yeah I was wrong, and had mis-remembered something where some emoji are represented with numbers but many are not. [:eight_spoked_asterisk:876920313080848404, for example])

cyan quail
#

unicode emojis on discord don't have IDs

fiery tiger
#

If a members gives us the premission guilds.join is there a code example of how we can make the user join a guild?

pallid token
#

Is there any way to get the name of the slash command group from the command context? When getting the name of the command, I get the sub-command's name (without the slash command group's name in front). Which makes sense as its just a command registered under the group, but it would be nice to be able to get the group name.

#

Sorry, I'm blind lol.
For anyone wondering the same thing, its SlashCommand#parent

spark lantern
#

Well this is a really stupid question but how does ctx.author work for bridge. It works fine if i use it as a prefixed command but shits itself if i use it as a slash command.

   @bridge.bridge_command(description="Adds a user to our verification system.")
    async def verify(self, ctx):
        member = ctx.author```

```bash
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'NoneType' object has no attribute 'author'
spark lantern
#

it works fine for prefixed commands but only breaks for slash commands which is pretty weird

silver moat
#

where did you load the cogs?

spark lantern
silver moat
#

I haven't seen that error before

#

does this happen every time for slash commands?

spark lantern
#

only if its ctx.author and its sub attributes, all the other context related things work, ctx.respond or ctx.guild etc all work

#

ill make a help ticket

silver moat
spark lantern
#

sure

wary rover
#

Heyyyy,
I wanted to get the ctx in my class so I could get the right language to display on my buttons. Obviously it doesn't work, do you have an idea?

class setupView(discord.ui.View):
    def __init__(self, context):
        self.ctx = context

        @discord.ui.button(label=getLocale(self.ctx, viewAddToken), row=0, style=discord.ButtonStyle.secondary, disabled=False)
        async def addToken(self, button, interaction):
            ...
full basin
wary rover
full basin
#

You can't access self on decorators

wary rover
#
view=setupView(context=ctx)
full basin
#

You either subclass the button instead. Or there was some other way I don't remember.

#

I think by not making it a self. attribute

cerulean drum
wary rover
cerulean drum
wary rover
#

I'm going to need more information because I admit I'm a little lost...

#
class setupView(discord.ui.View):
    def __init__(self, context):
        super().__init__(self, context)
        
        self.ctx = context

        self.add_item(discord.ui.button(label=getLocale(self.ctx, viewAddToken), row=0, style=discord.ButtonStyle.secondary, disabled=False))
        async def addToken(self, button, interaction):
            ...
silver moat
#

addToken should be in-line with __init__

#

and the button is missing a callback

#

so something like:

button = discord.ui.Button(label=getLocale(self.ctx, viewAddToken), row=0, style=discord.ButtonStyle.secondary, disabled=False)
button.callback = addToken
self.add_view(button)
cerulean drum
#
super().__init__()

means you construct the parent class, since you were subclassing View, what you pass to super is the parameter needed for View class

wary rover
#

@silver moat @cerulean drum

I really can't understand...
Every change gives me an error, although what you are telling me makes sense but the code doesn't accept it

silver moat
#

If you gave us the actual errors and traceback you encountered from our suggestions, this will help you and us.

wary rover
#

I am already convinced that I have misused the code you gave me

class setupView(discord.ui.View):
    def __init__(self, context):
        super().__init__()
        
        self.ctx = context

        button = discord.ui.Button(label=getLocale(self.ctx, viewAddToken), row=0, style=discord.ButtonStyle.secondary, disabled=False)
        button.callback = addToken()
        self.add_view(button)
#

AttributeError: 'setupView' object has no attribute 'add_view'

wary rover
#

I think it's time for me to go to sleep....

cerulean drum
wary rover
#

it work

cerulean drum
wary rover
#

button.callback = self.addToken I don't really understand this point

cerulean drum
#

if you define your callback as a local function (defined under init ), you can access it directly without self

wary rover
# cerulean drum if you define your callback as a local function (defined under init ), you can a...

I've done this, it "works".
The function executes without me clicking on the button

class setupView(discord.ui.View):
    def __init__(self, context):
        super().__init__()
        
        self.ctx = context

        button = discord.ui.Button(label=getLocale(self.ctx, viewAddToken), row=0, style=discord.ButtonStyle.secondary, disabled=False)
        button.callback = addToken()
        self.add_item(button)

def addToken():
    print("OK")
    return
silver moat
#

you called addToken

cerulean drum
#

adding parenthesis means you call them

cerulean drum
wary rover
#

addToken() takes 0 positional arguments but 1 was given

cerulean drum
silver moat
#

it should take one parameter: interaction

wary rover
wary rover
# cerulean drum <:this:908087405540687902>

I was asking you how to send other arguments, here is an example of what I am asking you.```py
class setupView(discord.ui.View):
def init(self, context):
super().init()

    self.ctx = context
    self.one = "one"
    
    button = discord.ui.Button(label=getLocale(self.ctx, viewAddToken), row=0, style=discord.ButtonStyle.secondary, disabled=False)
    button.callback = addToken(self.one)
    self.add_item(button)

async def addToken(interaction, numberOne):
await interaction.response.send_message("OK " + numberOne)
return

#

addToken() missing 1 required positional argument: 'numberOne'

#

If I don't give an argument to my function it works fine

#

But I will need to give arguments

cerulean drum
#

then add only 2 param (self, interaction)

#

with that you can access any data under your view class with self

cerulean drum
wary rover
#

It's not what I wanted to do but that's okay I'll go with that.
Thanks for your time @cerulean drum @silver moat

fringe socket
#

How do I make {member.roles} return a list of roles instead of this ugly little thing:

#

@silver moat ?

fringe socket
spice oyster
fringe socket
#

WDYM?

spice oyster
fringe socket
#

This is what I'm using rn

#

@spice oyster

spice oyster
#

And? It's easy to continue now.

fringe socket
#

Ok i think i know what you mean

fringe socket
#

So @spice oyster now I have this. I'd like it to just appear like this

Roles

Tester, Early Supporter, Moderator, Administrator, Developers, 👑 Lead Developer, Azumi Staff

umbral island
#

Looking for some help with timestamps.

I'm using this in the footer of an embed.

em.set_footer(text=f"{message.guild.name} | {message.guild.owner} | <t:{timestamp}:f>")

returns the image below. However if you copy paste the timestamp it provides, the timestamp is working.

fringe socket
umbral island
fringe socket
#

Also. Here's the OTHER reason why it won't work. Footers don't support formatting.

#

So. If you want to do a timestamp, you'll have to do it elsewhere. @umbral island

umbral island
fringe socket
#

You can use timestamps anywhere else in the embed though.

umbral island
spice oyster
fringe socket
#

where do i use it?

spice oyster
woeful spindle
#

define ur time stamp where you define the embed?

#

embed = discord.Embed(timestamp = …)

fringe socket
#

TYYYYYYYYYYYYYYY

spice oyster
umbral island
spice oyster
woeful spindle
#

^

fringe socket
#

How do I use an @mention as a prefix?

cyan quail
fringe socket
#

Also, what's the @bot.event for the bot shutting down?

#

Cause I want the bot to send a message right before it closes the connection

cyan quail
cobalt tangle
#

why is guild_ids not working

#

I just realized my CC cmds were public to all servers

#
    @fantasy.command(description="Remove invites from someone", guild_ids=[880634782856388678])
    @commands.is_owner()
    async def invite_rem(self, ctx, member: Option(discord.Member, "Member to remove invites"), amount: Option(int, "Amount of invites")):
        rem_invites(amount, member.id)
        await ctx.respond(f"Removed {amount} invites from {member}")  
#

one of my cc cmds

#
    cc = discord.SlashCommandGroup("cc", "Custom Commands")
    fantasy = cc.create_subgroup(name="fantasy", description="Fantasy server custom commands!")
cyan quail
#

you can't do it on specific subgroups/subcommands

cobalt tangle
#

thats fine with me

cyan quail
#

just put it in SlashCommandGroup

cobalt tangle
#

can i put in subgroup?

#

if possible

cyan quail
#

has to be the entire group, sorry

#

that's just how discord handles it

cobalt tangle
#

rip okay

cobalt tangle
#

it makes sense

#

discord enters groups as one cmd

#

@cyan quaildo i have to remove the guild_ids parameter from every cmd?

cyan quail
#

you don't have to remove it, but just know that it gets ignored

cyan quail
#

either way works

cobalt tangle
cobalt tangle
#

can i do @commands.has_role(role=False)

cyan quail
#

Not built in

#

Just make a custom check

cobalt tangle
#

better to use if since its only one cmd

fringe socket
cyan quail
#

Well there's so many ways for it to close so there's no event for before closing

#

It only exists after closing because of how the loop works

fringe socket
#

Darn

fervent cradle
#

how do i fetch a guild with its id within a cog

guild_check = self.bot.get_guild(guild_id)
                print(guild_check)
#

just returns none though the bot is in the server i entered

indigo kettle
#

Hi, I would like to know how can I get the list of users who have clicked the reaction from the message

cyan quail
#

server settings > integrations to manage roles/users/channels
on the bot's end, you can only set default permissions as per https://docs.pycord.dev/en/master/api/application_commands.html#discord.commands.default_permissions
alternatively there are internal checks that only apply locally

loud holly
#

is there a way to mention subcommands?

#

using

bot.get_application_command('subcommand').mention

like that shortcut

cyan quail
loud holly
#

Another quick question, I presume there's no way to move this button right?

The only way I can think of is using the decorator, however I'm using self to create the disabled button

#

like the 3rd button being in the middle

#

forgot to add arrows 😔

cyan quail
#

like pop the middle item and append it again

loud holly
#

👍

cyan quail
#

yes

young bone
#

what?

full basin
#

There's no interactions.

#

Everything is under the py-cord library

simple canopy
young bone
#

you use ctx inside of the button

#

remove ctx inside of the button and change it to interaction.response.send_message("text")

simple canopy
#

docs for the discord.Interaction.response

#

also, arguments in button decorated methods are positional

#

first is button second is interaction

#

you have them swapped

fervent cradle
#

🤔 anyone know how to send two local images in an embed?

f = discord.File(blahblah)
sf = discord.File(blahblah)
embed.set_thumbnail(url='attachment://stats_rank.jpg')
embed.set_image(url='attachment://stats.png')
await ctx.respond(file=f, embed=embed)

what am i meant to put for the last line if i have multiple files?
doing [f, sf] doesn't work
appending to a list before creating the embed doesn't work...

pls help! 🙏

fervent cradle
#

thank you!

lost lodge
#

Hey

#

I use some modals but i get an error in discord but not in my code

#

Something like that: "Ups, something went wrong!"

#

code:

class ReportUserModalView(discord.ui.Modal):
    def __init__(self, *args, **kwargs) -> None:
        super().__init__(*args, **kwargs)

        self.add_item(discord.ui.InputText(label="User (UserId or UserNameTag"))
        self.add_item(discord.ui.InputText(label="Why do you reported him/her?", style=discord.InputTextStyle.long))
        self.add_item(discord.ui.InputText(label="Do you have some evidences?", style=discord.InputTextStyle.long))

    async def callback(self, interaction: discord.Interaction):
        channel = discord.utils.get(interaction.guild.text_channels, id=1028611830769262732)
        embed = discord.Embed(title=f"A user was reported by {interaction.user}!")
        embed.add_field(name="User:", value=self.children[0].value, inline=False)
        embed.add_field(name="Reason:", value=self.children[1].value, inline=False)
        embed.add_field(name="Evidences:", value=self.children[2].value, inline=False)
        await channel.send(embed=embed, view=ReportCloseView())```
round rivet
#

you aren't sending an interaction response

lost lodge
#

ah

#

thx

pseudo dawn
#

I think I remember adding things to the context variable in the past, but I don't recall, if that was in python or javascript tho. So is there some Way to pass information down from a command group to the subcommands. or nested groups?

I am trying to remove duplicate code. Currently I got about 15 different subcommands that all access the database and query for objects. I would rather distribute that a little more, so that the groups do the querying and report an error to the user, if the desired Object is not present.

I already tried the serach functiuon in the docs, but did not find what I wanted....

full basin
#

You could also add a function to your cog class where the commands group is

errant craneBOT
#

Here's the custom context example.

pseudo dawn
white wadi
#

is it possible to reset/disable timeout on interaction.edit_message?

#

bcs when i edit the message i wanna give it a different view

rugged lantern
#

timeout is reset if you interact with it

white wadi
#

its not

rugged lantern
#

it is

young bone
rugged lantern
#

ig it depends on how poorly you code it

white wadi
wary rover
#

Hello!
I am trying to execute a very slow function.
If I enter my command again it does not respond.
What would be the best solution according to you?
We have already tried several threading tools but the threads open one after the other instead of all running at the same time.

white wadi
white wadi
wary rover
rugged lantern
white wadi
pseudo dawn
#

Is it safe to just delete a role while there are still Members that posess this role?

rugged lantern
rugged lantern
pseudo dawn
#

Maybe I'm too tired rn...
I should go to sleep and continue tomorrow.
I don't know what I imagined that should happen. Maybe I was thinking discord was weird or something.... Some other unnamed Messenger had some really strange things, that required you to manually clean up if a bot wanted to delete it, but a normal client could do that directls and he server took care of everything...

wary rover
#

Do you know how to run a function in a thread and get the output?

silver moat
wary rover
silver moat
#

what is the use case for this?

wary rover
# silver moat what is the use case for this?

We make a call to an API of an artificial intelligence. This one takes between 1 and 30 seconds to answer.

We noticed that on very large requests the bot becomes unable to respond to other commands or API calls.

silver moat
#

there is no need to overcomplicate it

wary rover
#
def openaiRequestAPI(ctx, max_length, question):    
    check = getToken(ctx.guild.id, ctx.author.id)
    
    if check == []:
        return "You need to add a token first!"
    
    
    openai.api_key = check[0][0]
    response = openai.Completion.create(
        model="text-davinci-002",
        prompt=question,
        temperature=0,
        max_tokens=max_length,
        frequency_penalty=0,
        presence_penalty=0
    )
    
    response = str(response['choices'][0]['text'])[2:]
    
    return response
silver moat
pseudo dawn
#

The docs don't mention if removing a role that the user does not have is an error. so is it okay to do that?

silver moat
pseudo dawn
#

Okay, thanks. Thats what I expected.

west pebble
#

why is there a connect method... but there isn't a disconnect method in discord.VoiceChannel

silver moat
unborn veldt
#

how can only admin see the slash command

#

anyone can help me

wary rover
rare ice
wary rover
#

Re,
I would like to be able to close the previously opened ThreadPoolExecutor to avoid too many open threads.

        loop = asyncio.get_event_loop()
        apiResponse = await asyncio.gather(
            loop.run_in_executor(executor, openaiRequestAPI, ctx, max_length, question)
        )  
unborn veldt
#

@wary rover

#

owo

rare ice
#

You can’t have bots edit integrations that I know of.

unborn veldt
#

qwq

silver moat
#

which pycord doesn't have an implementation for

wary rover
#

Don't implement this, it's used to do stupid things

bitter lance
#

If I reboot bot, can't I interaction view like buttons that sent before reboot??

bitter lance
rugged lantern
bitter lance
#

oh wow I'll try

bitter lance
#

I don't how to using this with lavalink FalseFacePalmLaugh

rapid geode
#
Ignoring exception in on_member_join
Traceback (most recent call last):
  File "C:\Users\Baban\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 382, in _run_event
    await coro(*args, **kwargs)
  File "c:\Users\Baban\Desktop\Folders\code playground\ceres-development\cogs\welcome_sys_.py", line 15, in on_member_join
    self.bot.dbcursor.execute(f"SELECT title FROM welcome_embeds WHERE guild_id = ?",(g_id))
ValueError: parameters are of unsupported type
#
    @commands.Cog.listener()
    async def on_member_join(self,member):
        g_id=member.guild.id
        self.bot.dbcursor.execute(f"SELECT title FROM welcome_embeds WHERE guild_id = ?",(g_id))
        title=self.bot.dbcursor.fetchone()
round rivet
rapid geode
#

k

#
Ignoring exception in on_member_join
Traceback (most recent call last):
  File "C:\Users\Baban\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 382, in _run_event
    await coro(*args, **kwargs)
  File "c:\Users\Baban\Desktop\Folders\code playground\ceres-development\cogs\welcome_sys_.py", line 44, in on_member_join
    await channel.send(embed=e)
AttributeError: 'NoneType' object has no attribute 'send'
#
        cha_id=self.bot.dbcursor.fetchone()
        self.bot.db.close()
        e=discord.Embed()
        channel=self.bot.get_channel(cha_id)
await channel.send(embed=e)  
#

help plz^^

#

for some reason it is returning a None type object

#

i tried printing it aswell

wild socket
#

Hi, So i am trying to make a log where if we change a channel's role permissions, the bot tells what perms were changed and for which role, but i am not able to find how i can do that

cosmic cobalt
#

yo guys

#

whats the method to get all the synced commands?

fervent cradle
#

Hey, quick question. Why am I getting an error with this class:

#

But not with this one:

#

It's nearly the same thing, just a different function

woeful spindle
#

after and before are already member objects

fervent cradle
merry briar
#

Is there a role selection in the Model via Select?

#

or something similar to choosing a role

lost lodge
#

Hey, how can i get a list of all the reactions of a message?

#

code:

    @commands.command()
    async def end_poll(self, ctx):
        msg = await ctx.channel.fetch_message(ctx.channel.last_message_id)
        print(msg.reactions())
        for r in msg.reactions():
            print(r)```
cyan quail
cyan quail
cyan quail
#

idk then, either you got the wrong ID or you disabled intents so that channels aren't cached

rapid geode
#

self.bot.dbcursor.execute("INSERT INTO welcome_embeds(guild_id,channel_id) VALUES(?,?)",(ctx.guild.id,int(channel.id)))

rapid geode
#

doesnt this cover it...

cyan quail
#

then you managed to screw up elsewhere GuraShrug the snippet alone you showed looks fine to me

rapid geode
#

my brain hurts cry

#

thanakyou i will check the code.

cyan quail
#

actually

lost lodge
cyan quail
cyan quail
rapid geode
cyan quail
#

doesn't fetchone return a tuple

rapid geode
#

return None

cyan quail
#

... then you found your issue

lost lodge
cyan quail
#

oh you messed up

lost lodge
#

oh

cyan quail
#

ctx.channel.last_message_id will return your command message lol

lost lodge
#

ah

#

haha

#

and how to get the 2nd last message xD

rapid geode
cyan quail
cyan quail
rapid geode
#

i dont even know how

cyan quail
#

so now what does it print

rapid geode
#

new error

Traceback (most recent call last):
  File "C:\Users\Baban\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 382, in _run_event
    await coro(*args, **kwargs)
  File "c:\Users\Baban\Desktop\Folders\code playground\ceres-development\cogs\welcome_sys_.py", line 26, in on_member_join
    channel=self.bot.get_channel(int(cha_id))
TypeError: int() argument must be a string, a bytes-like object or a real number, not 'tuple'
cyan quail
#

right

#

think of a tuple as similar to a list

#

how do you access stuff in that

rapid geode
#

??

#

dint quite get ya

cyan quail
#

...please tell me you know how to access items in a list

rapid geode
#

variable.stuff

#

somthing like this?

#

not worked with lists much

cyan quail
#

i am going to cry you access them with an index using square brackets like list[0] for the first item

rapid geode
lost lodge
rapid geode
#

uh hey

#

when i am storing stuff in a databse

#

its not appearing

#

but when i am printing it its there

cyan quail
# lost lodge ?

this isn't built in, but either;

  • channel.history with limit=2
  • make it slash so that your command won't count as a message until after it responds
lost lodge
cyan quail
#

not quite

lost lodge
cyan quail
cyan quail
rapid geode
lost lodge
lost lodge
# cyan quail no, see the 2nd example

so i made a tiny code that sends every emoji but how can i get the count of the emoji? ```py
[<Reaction emoji='👍' me=False count=2>, <Reaction emoji='👎' me=False count=1>, <Reaction emoji=<PartialEmoji animated=True name='loading' id=958386148957368360> me=False count=1>]````

cyan quail
#

read

lost lodge
cyan quail
#

your message contains the answer

lost lodge
cyan quail
lost lodge
cyan quail
#

ok so

#

reactions is a list

#

how do you access stuff in a list

lost lodge
cyan quail
#

ok

#

so a Reaction object has the count attribute

cyan quail
#

how do you get it then

lost lodge
#
print(stuff[count])````
cyan quail
#

attribute

#

like

#

you've probably done ctx.author before

lost lodge
cyan quail
#

or ctx.guild, ctx.message, self.bot

lost lodge
#

ye

cyan quail
#

it's all the same

#

so how would you get count

lost lodge
#

ahhhhh

#

stuff.count

cyan quail
#

congratulations

lost lodge
# cyan quail congratulations

bonk, error:

        r = msg.reactions
        print(r)
        counter = 0
        for rc in r:
            print(r.count[counter])
            counter += 1````

```py
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'builtin_function_or_method' object is not subscriptable````
cyan quail
#

what's with [counter]

lost lodge
#

it's to choose the thing in the list

cyan quail
#

but

#

count is an int

lost lodge
full basin
#

It means when you do r.count you receive an int

#

You don't receive a list

lost lodge
#

ah

lost lodge
full basin
#

Should be rc.count

#

Not r.count

lost lodge
#

thx

#

it works now totaly fine

pseudo dawn
#

Hi, would you have one databse session per cog, or should I try to have one globally for the whole bot that is stored inside the bot object?

I will need to subclass the bot anyways....

cyan quail
#

if it's the same db then yeah have it globally

halcyon thistle
#

guys what the equivelent of this in pycord?

@bot.event
async def on_slash_command(inter):```
sleek haven
#

so i have this to check if the user has the booster role but i have the role but it dosent print the thing or add the extra 1

rapid geode
edgy kiln
#

is there a way to make slash commands that are owner only only show for the bots owner?

rapid geode
#

i think the commnds are still visible

#

to other people

#

i would suggest you to have a dedicated server for this

#
    @slash_command(guild_ids=[989370159154233375,883180896038027336])
    @commands.is_owner()
edgy kiln
#

so like set the command to only work in one guild and then use that for owner commands?

rapid geode
#

owner only^^

edgy kiln
#

ty

halcyon thistle
rapid geode
sleek haven
#

kk

sleek haven
rapid geode
#

yeh

sleek haven
rapid geode
#

uh

#

remove the""

#

in roe_id