#Basic Pycord Help (Quick Questions Only)

1 messages · Page 44 of 1

somber frost
#

i really cant solve this shit please help me 😭 XD

rare ice
#

import the cog

brittle cove
# rare ice import the cog

Yeah they don't show up as valid things to access though, I got around it by making a function that just returns it

full widget
#

Remember that the bot creates an instance of the cog Classes, the class itself contains no information

brittle cove
#

That's what I needed thank you

full widget
#

np

brittle cove
#

I was trying to make static instances cause I couldn't figure it out

full widget
#

remember that if the cog is not loaded, bot.get_cog() returns None, and thus will error

somber frost
#

please help me

brittle cove
#

I load them sequentially but I'll add a check

somber frost
#

still didnt fix that

#

im crying

full widget
#

though

#

if your original code isn't working, it's likely the category var isn't getting filled at all

somber frost
#

the category is just a NoneType

full widget
#

yea

somber frost
#

it doesnt recognize it as a category

full widget
#

that means you're not correctly retrieving the category

somber frost
#

can you tell me how to do it

#

20 google searches i didnt find anything

#

"how to get a category by the id"

#

XD

full widget
#

guild.get_channel(categorychannelid)

brittle cove
#

I'm using the class name

full widget
#

the name should be the class name

brittle cove
#

Yeah just throwing modulenotfound

full widget
#

try to set your list copy in an on_ready listener

#

the module must not be loaded yet. This can happen if you try to load info in the init

#

or use await bot.wait_until_ready()

somber frost
full widget
#

my guy

#

interaction.guild

#

Variables don't just appear out of thin air

somber frost
#

i declared the guild var

full widget
#

why are you using both interaction.guild and bot.get_guild?

somber frost
#

wtf

#

am i stupid?

#

wait ill remove the one line

#

same error still

#

:((

full widget
#

ok, so you're not retrieving the guild correctly

#

is your bot in the guild you're trying to make a channel in?

somber frost
#

yes

limber urchin
#

Why are you using get_guild at all when you have the guild in the interaction object?

somber frost
#

thats a good question

full widget
somber frost
#

i think that should work now

full widget
#

sure

#

if not, throw a print(category) in there to check what you're getting from that call

somber frost
#

omg

#

it works ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️

limber urchin
#

get_channel only works if the channel is cached

full widget
#

also remember you will need to respond to the interaction to get it to not error out

limber urchin
#

which it won't always be

somber frost
#

@limber urchin @full widget thank you very much

#

do i just need to respond with a message to close the modal?

#

oh you dont even know my code, i opened a modal and the channel gets created when the modal submit button is pressed

full widget
#

ok

somber frost
#

when i then respond with an ephemeral message, will the modal close?

full widget
#

the modal will close when you hit submit

#

but you need to respond with something to avoid "the application did not respond"

somber frost
#

ah yeah

#

right

full widget
#

also as spaxter said, consider changing to category = interaction.guild.get_channel(....) or await interaction.guild.fetch_channel(....)

#

to avoid issues with caching

somber frost
#

i already did that 👍

#

again, tysm ❤️

full widget
#

np gl

peak chasm
#

How would it be so that only numbers are allowed?

young bone
#

Modal?

peak chasm
young bone
peak chasm
#

Oh :c

#

Oki, thanks por help

grizzled sentinel
#

Hopefully discord will add more eventually

young bone
#

and the Dropdown ^^

grizzled sentinel
# young bone Also more fields

I need this. I have no idea why thay don't allow model chaining. If someone gets "trapped" they can hit cancel or the x and it would exit.

young bone
limber urchin
#

I'm sure they're holding back since modals are pretty new

young bone
full widget
#

Is editing the guild specific integration permissions through a bot possible?

#

I have a couple commands that I want only a specific role to be able to use, and while setting a limit in the server integration settings is the cleanest way to do this, every time I restart the bot, these commands get reloaded which resets the server specific permissions

royal pulsar
#

How do you send an ephemeral followup? I tried putting in the ephemeral argument in ctx.send_followup, and it doesn't work. What is the alternative?

proud mason
vale heath
#

error

Ignoring exception in command ping:
Traceback (most recent call last):
  File "C:\Users\Zalama\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\commands\core.py", line 124, in wrapped
    ret = await coro(arg)
          ^^^^^^^^^^^^^^^
  File "C:\Users\Zalama\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\commands\core.py", line 980, in _invoke
    await self.callback(ctx, **kwargs)
  File "c:\Users\Zalama\OneDrive\Documents\GitHub\Grinder_Co\main.py", line 89, in ping
    await msg.add_reaction("🏓")

code

@bot.bridge_command(description ="check bot's ping")
@commands.cooldown(3, 10, commands.BucketType.user)
async def ping(ctx):
    embed = discord.Embed(title = "Pong! :grinning:", description =f"`Ping is : {round(bot.latency*1000)}ms`", colour= 0xFE6000)
    msg=await ctx.respond(embed=embed)
    await msg.add_reaction("🏓")

is there a way to use add_reaction for a bridge cmd as it work ok with prefix but slash gives error

proud mason
#

.rtfm discord.Interaction

proud mason
#

Last one

vale heath
#

so i need to put in try and except heh

proud mason
#

Get the original message and add reaction to that

proud mason
silver moat
#

.rtfm bridgecontext.is_app

winter condorBOT
proud mason
#

On the ctx

proud mason
vale heath
summer harness
#

i need help on editing an embed that my bot sends

proud mason
#

What do you need help with

copper dew
summer harness
#

basically i created an embed and the bot sends it, but i want the bot to edit the embed
i looked at this page that has the edit function but i don't realy understand how to use it :/
https://docs.pycord.dev/en/stable/ext/pages/index.html#discord.ext.pages.Paginator.edit

@bot.slash_command(name = "start", description = "Start a game of Mario")
async def hello(ctx):
  asyncio.sleep(4)
  mario = [":mario1:", ":mario2:"]
  costume = 0
  embed = discord.Embed(title = mario[costume])
  await ctx.respond(embed=embed)
proud mason
#

Where do you plan on editing the embed?

#

If you have the embed object, you can simply edit it as if it is a new embed

embed.description = smth
embed.title = smth

Like that

summer harness
proud mason
#

.rtfm discord.Message.edit

winter condorBOT
proud mason
#

1st one. Use that

#

Set embed=your_embed

summer harness
#

oh thx i will try that

#

uhh i tried this

await discord.message.edit(embed=discord.embed(title="edited!"))

and it gave the error discord.commands.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: module 'discord.message' has no attribute 'edit'

summer harness
copper dew
silver moat
#

?tag oop

obtuse juncoBOT
#

https://www.digitalocean.com/community/tutorials/understanding-class-and-instance-variables-in-python-3
https://docs.python.org/3/tutorial/classes.html

There's a difference between a class and an instance. Think of it like this:

  • A class is like a blueprint, or a concept. It defines what something should have, but it's not the same as actually having it.
  • An instance is the 'realized' version of the class, it contains everything that the class defines should be on it, but you can actually access and interact with these features.

Let's consider the Cat. We know a Cat has a name and an age, but Cat.age won't work, because Cat isn't an actual cat, it just represents the concept of a cat. It's like asking "What is the age of a cat?" - it doesn't make sense, because we need to have an actual cat.

mimi on the other hand is an instance of a Cat - it has everything a Cat should have. Maybe mimi was constructed, like mimi = Cat("Mimi", age=4), or maybe mimi was retrieved from somewhere else, like house.cats[0], but in any case, it has everything we need, and mimi.age will rightfully give us 4.

There are many situations in Object Oriented Programming where you will need an instance instead of a class to perform an operation properly (in fact, you almost always need an instance instead of a class), and these cases will usually be documented.
You should learn a good amount about Object Oriented Programming before working extensively with Pycord.

summer harness
# copper dew Capitalize Message

now i am getting this error
discord.commands.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: edit() missing 1 required positional argument: 'self'

proud mason
#

Use the message object

summer harness
silver moat
#

given that message is defined

summer harness
#

so it would be like

  msg = await ctx.respond(embed=discord.Embed(title="mario") 
  
  await msg.edit(embed=discord.Embed(title="luigi")```
silver moat
#

that returns an interaction/message. you should handle it accordingly with is_app

summer harness
silver moat
#

oh wait I mixed you up with another person

summer harness
silver moat
#

you can use ctx.interaction.original_response the receive the response message

meager mango
#

Question, I recently started working on an older bot again, I switched the commands over to slash commands and am using pycord. The button I have is not providing an interaction object to work with. Before I switched to pycord it was giving me an interaction that I could for example access interaction.user

Now it is telling me "button doesnt have attribute user"

#

if this is not a quick question let me know ill make a post

silver moat
meager mango
#

so switch button / interaction in the args?

silver moat
#

yes

meager mango
# silver moat yes

blessed thank you, going forward does button or other components come first now?

silver moat
#

yeah

undone mulch
#

What is the default timeout for buttons (PyCord) ? Couldn't find it in the Docs.

silver moat
summer harness
sand siren
#

how do i have dropdown menu that when a option is selected it gives you permission to view a specific channel but when unselected removes that permission?

silver moat
#

.nohelp

winter condorBOT
#

Nobody helps you? See #help-rules #4, then you know why.

sand siren
#

sorry. How do i give a user permissions to view a channel?

proud mason
undone mulch
proud mason
#

.rtfm interaction.edit_original_response

winter condorBOT
vale heath
sand siren
vale heath
vale heath
quartz thunder
#

yes you can, you have to keep the interaction object return on ephemeral creation

#

just made it work !

undone mulch
#

Uh

#

I forgot how to convert ['banana', 'apple'] to banana, apple in Python.

#

Anyone remember lol? Without using .replace

undone mulch
young bone
#

#help-rules 2

undone mulch
#

I just forgot how to get a random sample of something without getting it as a list.

#

I'm using random.sample, but it returns a list. Is there a way to do random.choice in multiple sets without it returning to a list.

#

I'm dumb.

#

Got it.

tired goblet
#

Hello, I want to create a bot that fetches new posts from reddit. Can someone point me in the right direction as to how to go about it? I have used praw before

fringe socket
#

Use a Reddit API?

#

its not hard ¯_(ツ)_/¯

#
drowsy hound
#

hello, I'm trying to get the privileged intent message_content to true, anyone can help me?

fervent cradle
drowsy hound
#

they are. but I think I'm using the wrong handler or sth

fervent cradle
drowsy hound
#

ok, just a minute

#

import discord

bot = discord.Bot()
bot.intents.message_content = True
print("INTENTS:",bot.intents)
print("MESSAGE_CONTENT", bot.intents.message_content)
@bot.event
async def on_message(ctx: discord.Message):
if ctx.author == bot.user:
return
print(f'[{timestamp(ctx.created_at)}] {ctx.author}: {ctx.content}')

f = open("token", "r")
token = f.read()
bot.run(token)

#

the "print("MESSAGE_CONTENT", bot.intents.message_content)" line returns false somehow

fervent cradle
#

bot = discord.Bot()
bot.intents.message_content = True
print("INTENTS:",bot.intents)
print("MESSAGE_CONTENT", bot.intents.message_content)
@bot.event
async def on_message(ctx: discord.Message):
    if ctx.author == bot.user:
        return
    print(f'[{timestamp(ctx.created_at)}] {ctx.author}: {ctx.content}')

f = open("token", "r")
token = f.read()
bot.run(token)
the "print("MESSAGE_CONTENT", bot.intents.message_content)" ```
#

just so I can see it.

#

How are you getting the token?

#

.json?

drowsy hound
#

from a file

#

nah, just a blank file

fervent cradle
#

ok

drowsy hound
fervent cradle
#

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

bot = discord.Bot(intents=discord.Intents.all())


@bot.event
async def on_message(ctx: discord.Message):
    if ctx.author == bot.user:
        return
    print(f'[{timestamp(ctx.created_at)}] {ctx.author}: {ctx.content}')

f = open("token", "r")
token = f.read()
bot.run(token)```
#

there.

drowsy hound
#

let's try!

#

IT WORKED! Thank you so much!!

#

didn't know I could pass the bot the intents as args

fervent cradle
digital storm
#

How do I get a discord.User object from a username? (name+discriminator)

fervent cradle
#

code please

vale heath
fervent cradle
#

so I did it a way he can learn and see other ways.

frail matrix
#

Could someone help me get slash command options working? When I type the slash command in, no field for any options appears

class SelfRole(Cog):
    @discord.slash_command(name="create", description="Create selfrole dropdown menu")
    @discord.option("text", description="just some text", required=True)
    async def create(self, ctx):
        await ctx.respond(view=RoleSelector())```
serene spindle
frail matrix
serene spindle
#

Yw

full basin
vale heath
#

.rtfm get_member_named

winter condorBOT
real frost
#

Hi, Does Select Menus work only for one user?

proud mason
#

No

fervent cradle
real frost
#

oh, i couldn't figure out why my Select don't work, but i've just sending it with a paginator which works only with a author

tired goblet
# fringe socket Use a Reddit API?

Yeah, like i said, I've used praw before which is a reddit api wrapper for python. I am having trouble with integrating it with a discord bot. Like, where should the code that fetches new posts go? Should i create a new function for it and call it with async task, or use pycords task extension or some other way?

fringe socket
#

stack overflow...

#

youtube...

#

you have the internet on your side, brave one!

proud mason
fervent cradle
#

Is it possible to have an eval command with discord.Bot?

frail matrix
#

I'm doing fetch_roles in a slash command to print all the roles in a server, and whenever I run it I get a 'command is outdated' error. It's been 20 minutes now, is that normal?

vale heath
#

Code pls 🤔

frail matrix
#
    @discord.slash_command(name="update", description="Update menu")
    async def update(self, ctx, guild: discord.Guild):
        await ctx.respond("`Updated menu`")
        roles = await guild.fetch_roles()
        print(roles)
tired goblet
#

the code works

#

but is this the right way to do it? thanks for your time

proud mason
#

Don't use a while True loop

#

Use the tasks ext

sand siren
#

.rtfm Channel

proud mason
sand siren
#

sry

tired goblet
#

thanks i'll try that

young bone
#

;3

serene spindle
tired goblet
proud mason
#

Cuz weird perms setup

young bone
#

K

tired goblet
proud mason
#

Mhm

#

LGTM

tired goblet
#

thanks

somber remnant
#

Hey, how to set an image in a embed object, without assign it ? For example :

discord.Embed(
          title=f"Test" ,
          description=f"\u200b"
          ,color = 0xeb571c,fields=[     
discord.EmbedField(name=f"test",value="Test")])```

discord.Embed.set_thumbnail() require a "self" parameter. But what is this self if i put it into the discord.Embed() object
limber urchin
#

Huh?

#

You don't call the method directly on the class, you need an instance of the Embed object to set the thumbnail

somber remnant
#

So i can't set a thumbnail without create an instance ?

limber urchin
#

What's stopping you from creating an instance??

somber remnant
#

it is more practical and visual, and allows me to arrange them neatly in precise lists

limber urchin
#

I mean you do you, but I think that would look really messy and definitely not a pythonic coding style

somber remnant
#

well i need to make much embed so it's pretty cool to make them like this instead of embed = ...
embed.add .....
embedlist.append(embed)
for example

#

Also, allow me to put it into a async function with parameters and is easy to use

#

that's how i code, ik there's others ways but this one pretty good for me

limber urchin
#

You can still do that with loops and functions

#

Either way, you should read the docs

somber remnant
#

It would take longer than defining each embed by hand as they will all be different

somber remnant
limber urchin
#

I'm not talking about the set_thumbnail method

#

There are properties of the embed you can define in the constructor

somber remnant
#

hm

#

I don't see any thumbnail into vs

limber urchin
#

Exactly

#

So you have to use the method on an instance

somber remnant
somber remnant
#

Absolutely no way around it? I have 180 embeds to do rooBulli

#

Ho i have an idea

#

set_thumbnail on the discord.Embed directly

#

i'll try this

#

It's work !

#

Thanks for the help rooDuck

jaunty raft
fervent cradle
#

I need help connecting to a phpMyAdmin SQL database. Someone told me to use pymysql and then use connection = pymysql.connect(host="localhost", port=8889, user="root", passwd="root", database="SELECTION_DB")cursor = connection.cursor()
Would this work ?

jaunty raft
#
import pymysql

connection = pymysql.connect()

cursor = connection.cursor()

cursor.execute("INSERT blah b lah blah")
connection.commit()

cursor.close()
connection.close()
fervent cradle
#

okay then so when I need to get the info i need IE: Steam ID from the database how would I do so?

jaunty raft
#
SELECT steamID from table;
fervent cradle
#

perfect

jaunty raft
#
import pymysql

connection = pymysql.connect()

cursor = connection.cursor()

cursor.execute("SELECT streamID from tablename")
fetch = cursor.fetchall() # this will get all results from the query

fetchone = cursor.fetchone() # will get the first row
fetchmany = cursor.fetchmany(int) # this will get an amount of rows
cursor.close()
connection.close()
fervent cradle
#

then for putting that into an embed

jaunty raft
#

i suggest using aiomysql since it's asynchronous

fervent cradle
#

okay so how would i do all of this with aiomysql

jaunty raft
fervent cradle
# jaunty raft ^^

man i just need some basic connection and to get someones steam id when they make a ticket through my ticket bot

fervent cradle
# jaunty raft ^^

so i would put my connection stuff that I sent before in the pymysql.connect() correct?

fervent cradle
#

hold on

#

connection = pymysql.connect(host="localhost", port=8889, user="root", passwd="root", database="SELECTION_DB")

cursor = connection.cursor()

cursor.execute("SELECT streamID from tablename")
fetch = cursor.fetchall() # this will get all results from the query

fetchone = cursor.fetchone() # will get the first row
fetchmany = cursor.fetchmany(int) # this will get an amount of rows
cursor.close()
connection.close()```
fervent cradle
ionic hull
#

if my bot sends a response to a slash command like

@bot.slash_command()
async def example(ctx):
    await ctx.respond('text')

how can I get message_id of the message my bot has just sent?

proud mason
winter condorBOT
proud mason
#

That thing

ionic hull
#

thanks a lot

undone falcon
#

is there a way to run my own clean up code when the bot is closing

limber urchin
#

Override the close method of your bot

#

Don't forget to call super().close() as well, otherwise your bot won't close properly

fervent cradle
#

cursor.execute("SELECT * FROM `users` ORDER BY `users`.`steam_id` ASC") how would i get the persons steam id with the persons discord ID

limber urchin
#

what

jaunty raft
#

do you want one, or all, or in size

#

like an amount of rows that you want it to return

fervent cradle
#

1 steam id per discord id

#

the database has discord ids and steam ids

jaunty raft
#

so you want them all

limber urchin
#

You can use a simple WHERE in your SQL statement

jaunty raft
#
import pymysql

connection = pymysql.connect(host="localhost", port=8889, user="root", passwd="root", database="SELECTION_DB")

cursor = connection.cursor()

cursor.execute("QUERY HERE")
fetch = cursor.fetchall() # this will get all results from the query

cursor.close()
connection.close()
fervent cradle
#

cursor = connection.cursor()

cursor.execute("SELECT * FROM `users` ORDER BY `users`.`steam_id` ASC")
fetch = cursor.fetchall() # this will get all results from the query

fetchone = cursor.fetchone() # will get the first row
fetchmany = cursor.fetchmany(int) # this will get an amount of rows
cursor.close()
connection.close()```
limber urchin
#

why do you have fetch, fetchone and fetchmany in the same code?

jaunty raft
#

I wanted to show which one he can choose

#

but I see I made a mistake

#
connection = pymysql.connect(host="localhost", port=3306, user="opqfulkp", passwd="", database="users")

cursor = connection.cursor()

cursor.execute("SELECT * FROM `users` ORDER BY `users`.`steam_id` ASC")
fetch = cursor.fetchall() # this will get all results from the query -> will return an empty tuple if nothing is matching
cursor.close()
connection.close()
limber urchin
#

I guess spoonfeeding works too 🤷‍♂️

jaunty raft
#

works too anyways

limber urchin
#

???

jaunty raft
#

nevermind

limber urchin
#

If you're going to help in this channel, please actually help instead of just spoonfeeding people finished code

#

it's useless

jaunty raft
#

got it

fervent cradle
#

okay what i needed was how do i get the steam id and put in an embed when a person opens a ticket

limber urchin
#

Just fetch the ID from your database and write it out in the embed

summer harness
undone falcon
final fractal
#

does pycord work in replit?

limber urchin
#

?tag replit

obtuse juncoBOT
final fractal
royal pulsar
#

is member.history the same as channel.history except it gives only the member's results?

undone falcon
limber urchin
undone falcon
#

Like this

#

It work if I dont subclass the bot

limber urchin
#

And did you read the error?

undone falcon
#

yes and I dont get it, it is working without subclassing the bot, why would it not work when I overwrite the close method

limber urchin
#

So what do you think this means?

undone falcon
#

yeah but never created a Help command using class

#

I just always use the decorator without problem

limber urchin
#

If you're creating your own help command why are you trying to set the help_command parameter?

limber urchin
#

You are

undone falcon
#

how ?

limber urchin
undone falcon
#

oh, it autocompleted, I though it was optional parameter

#

in python when you put = with value it is not a defautl parameters that you dont need to fill?

limber urchin
#

what?

undone falcon
#

I though help_command was a kargs with default value

limber urchin
#

it is, but why do you even have it there if you're not going to set a value?

undone falcon
#

yeah I agree, I just got confused. Thanks you for your help !

limber urchin
#

Don't use code you don't understand

undone falcon
#

yeah I thought I understood it, but did not. I tough if you don't put any value I it will put the default one like None

#

but thanks you !

rare ice
#

Haven’t used discord.File objects in a while, I saw that the file object has an attribute fp which is a “*file-like object opened in binary mode *” (according to the docs). Is this what I use in open() to read it? My use case is a discord.File slash command option which is supposed to be a json file, and I want to get a dictionary from that json file.

#

.rtfm discord.File.fp

winter condorBOT
limber urchin
#

You can open a file in binary mode by adding 'b' to the mode parameter in the open function.
E.g

with open('myfile.txt', 'rb') as f:
    ...
#

Will read a files binary data

limber urchin
#

It will not, it's going to be a BufferedReader. If you want it as a dict you just need to read it normally and turn it into json

import json
with open('myfile.txt', 'r') as f:
     my_dict = json.loads(f)

or something.

#

I realize now you're asking how to turn a binary mode file into JSON, and not the other way around

rare ice
#

Oh I see. So I have file as the discord.File object (test.json). I can’t seem to use it in open(). How would I ago about making that eligible to use in `open()? Says it only takes str, bytes or os.PathLike object. I assume I need to turn it into a bytes object.

limber urchin
#

You should be able to call read() on the file object to turn it to text, and then just use json.loads on that

rare ice
#

👍

rare ice
#

Using jsk and got this error

msg = await _channel.fetch_message(1054931375599399024)
f = msg.attachments[0]
t = await f.read()
import json
j = json.loads(t)
j

Error:

#

This is what t printed

royal pulsar
#

I have a function with the decorator @commands.has_permissions(manage_messages=True). Whenever this function is called from a user who doesn't have the perms, it throws an error on stdout, but doesn't send a message to the user stating that they do not have perms. What is the correct way to handle this? I have tried using try and except, but since it's a decorator they do not run.

dry gazelle
#

I am building a bot that handles hidden messages, and one thing is that I want these messages to persist through the bot going down and coming back up. I already have a python database set up for all of this, but the only issue is that the buttons dont trigger the interaction after restart.... any ideas?

limber urchin
#

A "python database"?

limber urchin
rare ice
limber urchin
#

Oh wait, is that a valid json file? Properties need to use ", but in your string it's '

rare ice
#

Oh I see

dry gazelle
#

nothing crazy

frail matrix
#

is there any way to display the options in a dropdown menu as coloured text?

limber urchin
#

no

frail matrix
#

ok thanks

final fractal
vale heath
final fractal
#

so after doing pip install py-cord i can do

import discord
from discord.ext import commands```
instead of
```py
import pycord
from pycord.ext import commands```
??
vale heath
#

ye

final fractal
#

k

limber urchin
#

it has never been import pycord, that's in v3.0 which isn't out yet

vale heath
#

flexing hehe

final fractal
vale heath
rare ice
#

How would I take a dictionary and turn it into a discord.File object that is a json file?

final fractal
#

How make an slash cmd option a variable?

limber urchin
#

huh

summer harness
#

how do you add a reaction to an interaction?

@bot.slash_command(name="character", description="Choose between Mario and Luigi")
async def character(ctx):
  mario = ":mario:"
  luigi = ":luigi:"
  msg = await ctx.respond(
    embed=discord.Embed(title=str(ctx.author).split("#")[0] + ", choose your character!", color=discord.Colour.yellow()))
  for reaction in [mario, luigi]:
    await msg.add_reaction(reaction)

add_reaction() won't work

knotty surge
#

Hey all, I am getting an error with my first slash command:

import discord
import os # default module
from dotenv import load_dotenv

load_dotenv() # load all the variables from the env file
bot = discord.Bot()

@bot.event
async def on_ready():
    print(f"{bot.user} is ready and online!")

@bot.slash_command(name="test")
@discord.option("name", description="Enter your name")
@discord.option("gender", description="Choose your gender", choices=["Male", "Female", "Other"])
@discord.option(
    "age",
    description="Enter your age",
    min_value=1,
    max_value=99,
    default=18,
    # Passing the default value makes an argument optional.
    # You also can create optional arguments using:
    # age: Option(int, "Enter your age") = 18
)
async def hello(
    ctx: discord.ApplicationContext,
    name: str,
    gender: str,
    age: int,
):
    await ctx.send(
        "Hello World."
    )

bot.run(os.getenv('TOKEN'))# run the bot with the token

Works fine, 0 errors however when I run the command in discord I get the following error:

The application did not respond

limber urchin
#

ctx.respond

knotty surge
limber urchin
#

huh?

knotty surge
# limber urchin huh?

Sorry mate getting the same issue again this time with this:

import discord
import os # default module
from dotenv import load_dotenv

load_dotenv() # load all the variables from the env file
bot = discord.Bot()


def make_texture(name, collar, div):
    return (f'{name} | {collar} | {div}')

@bot.event
async def on_ready():
    print(f"{bot.user} is ready and online!")

@bot.slash_command(name="test")
@discord.option("name", description="Enter your name")
@discord.option("div", description="Choose your gender", choices=["Male", "Female", "Other"])
@discord.option(
    "collar",
    description="Enter your age",
    min_value=1,
    max_value=99,
    default=18,
    # Passing the default value makes an argument optional.
    # You also can create optional arguments using:
    # age: Option(int, "Enter your age") = 18
)
async def hello(
    ctx: discord.ApplicationContext,
    name: str,
    collar: int,
    div: str
):
    await ctx.respond(
        make_texture(name, collar, div)
    )

bot.run(os.getenv('TOKEN'))# run the bot with the token
meager mica
#

i recently installed pycord on server and i get spammed with this error every time emssage is ent but i only have slash commands

#

TypeError: Iterable command_prefix or list returned from get_prefix must contain only strings, not tuple

copper knot
meager mica
#

bot = commands.Bot(discord.Intents.all())

#

is it discord floosh

copper knot
#

if you arent using prefixed commands

meager mica
#

o

#

thanks

knotty surge
#

How would I go about sending 3 images at once?

fringe socket
#

First, upload one image, then upload another, then another, and then send the message.

#

… ¯_(ツ)_/¯

knotty surge
#
    allImages = []

    with open(str(test) + "_shirt.png", 'rb') as f:
        picture = discord.File(f)

        allImages.append(picture)

    with open(str(test) + "_black_vest.png", 'rb') as f:
        picture = discord.File(f)
        
        allImages.append(picture)

    await ctx.send(
        files=allImages
    )
#

Well I created an array thinking that would work, how does one go about doing it?

copper knot
#

files is supposed to be a list of discord.Files

knotty surge
#

So how would I combine them together

#

to send them?

copper knot
#

a list

sand siren
#

i am trying to have a command that changes a user's permission but its not working could somebody pls help me.

async def perms(ctx: discord.message):
    await ctx.respond("perms changed?")
    await message.channel.set_permissions('1054749066325655552', read_messages=True, send_messages=False)```
copper knot
sand siren
#

the guild id?

copper knot
#

in setting perms

sand siren
#

so like this?
message.channel.set_permissions(1054749066325655552, read_messages=True, send_messages=False)

copper knot
#

im not on pc but that was something i saw immediately

#

actually the id needs to be a discord.Member

sand siren
#

oh

copper knot
sand siren
#

a bit

copper knot
#

just got on pc and my eyes hurt

copper knot
copper knot
sand siren
#

thx it works

young bone
#

?tag idw

obtuse juncoBOT
#

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.

vale heath
#

Where are you getting role ID from to add 🤔

proud mason
#

Where did you define role

#

That isn't your command

#

I mean it is not this ^ cmd

vale heath
#

Where are you storing or getting the role ID from this cmd 😑

proud mason
#

.nojson

winter condorBOT
#

JSON is a convenient and easy-to-read data storage protocol that's widely accepted by most programming languages. However, we caution against its use for storing and retrieving data in an asynchronous environment like a Discord bot. Don’t use json!

  • It's a file-based data storage, which makes it vulnerable to race conditions
  • You'll need to implement your own synchronization primitives to avoid corrupting data
  • If you're not careful, you could accidentally wipe your entire JSON file.

Solution? Use a database. Recommended schema are SQLite, PostgreSQL, and MongoDB.

  • Async libraries exist on pypi for each of these
    sqlite -- aiosqlite (or Danny's wrapper, ?tag asqlite)
    postgresql -- asyncpg
    mongodb -- motor
  • Databases organize your data into tables, and are fast at inserting, retrieving, and removing records
  • You can impose uniqueness constraints to ensure against duplication
  • The Python libraries enforce synchronization for you
  • The query language is intuitive, you can get running with simple queries in just a few hours!
proud mason
#

Use motor wrapper

#

For mongodb

#

That's async

#

Also you haven't defined role in this command

fringe socket
#

.tag nojson

winter condorBOT
#

JSON is a convenient and easy-to-read data storage protocol that's widely accepted by most programming languages. However, we caution against its use for storing and retrieving data in an asynchronous environment like a Discord bot. Don’t use json!

  • It's a file-based data storage, which makes it vulnerable to race conditions
  • You'll need to implement your own synchronization primitives to avoid corrupting data
  • If you're not careful, you could accidentally wipe your entire JSON file.

Solution? Use a database. Recommended schema are SQLite, PostgreSQL, and MongoDB.

  • Async libraries exist on pypi for each of these
    sqlite -- aiosqlite (or Danny's wrapper, ?tag asqlite)
    postgresql -- asyncpg
    mongodb -- motor
  • Databases organize your data into tables, and are fast at inserting, retrieving, and removing records
  • You can impose uniqueness constraints to ensure against duplication
  • The Python libraries enforce synchronization for you
  • The query language is intuitive, you can get running with simple queries in just a few hours!
proud mason
#

This will be out of scope for the other command

fringe socket
#

Oh haha

#

My messages were not loading

#

om deletes failed command attempt

somber remnant
#
     
        @discord.ui.button(style=discord.ButtonStyle.primary, emoji="🛒",row=0)
        async def third_button_callback(selfBUTTON, button3, interaction):
            await interaction.response.edit_message(view=selfBUTTON)

        @discord.ui.button(style=discord.ButtonStyle.gray, emoji="◀️",row=1)
        async def first_button_callback(selfBUTTON, button1, interaction):
            await interaction.response.edit_message(view=selfBUTTON)
            await selfBUTTON.crate_page(message=interactionMessageCrate,contents=contents,emote="◀️")

        @discord.ui.button(style=discord.ButtonStyle.gray, emoji="▶️",row=1)
        async def second_button_callback(selfBUTTON, button2, interaction):
            await interaction.response.edit_message(view=selfBUTTON)
            await selfBUTTON.crate_page(message=interactionMessageCrate,contents=contents,emote="▶️")



        async def crate_page(self,message,contents,emote):
            message = await message.original_response()
            if emote == "▶️" and self.cur_page != self.pageTotal:
                self.cur_page += 1
                await message.edit(embed=contents[self.cur_page-1])


            elif emote == "◀️" and self.cur_page > 1:
                self.cur_page -= 1
                await message.edit(embed=contents[self.cur_page-1])

            elif emote in ["◀️","▶️"]:
                if self.cur_page == self.pageTotal :
                    self.cur_page = 1
                elif  self.cur_page == 1:
                    self.cur_page = self.pageTotal
                await message.edit(embed=contents[self.cur_page-1])```

Hello, i made a page button system, and i want that if i use ▶️ emote to change page for exemple, the 🛒 button get disabled. How to do this ?
young bone
somber remnant
#

I heard about that but never take a look

somber remnant
#

It looks a bit complicated, I've been doing the pages like that for a year, I'll see if I can change later

fervent cradle
#

Hey I'm hosting a bot through sparkhosting and my entire bot just went offline and has been for over 6 hours. Claiming I was exceeding the rate limits too often. My bot maybe sends 10 requests every 10 minutes. Is this because this host is sharing ips between instances?

somber remnant
obtuse juncoBOT
#

dynoError No tag motor found.

#

dynoError No tag motor found.

winter condorBOT
#

Tag not found.

young bone
#

what is that even?

dry cove
#

How to remove category from slash command option? It shows up if i use discord.TextChannel

rare ice
#

How would I take a dictionary and turn it into a discord.File object that is a json file?

proud mason
proud mason
#

.rtfm slashcommandoptiontype

proud mason
#

Find something in there

#

Ig try the 8th one

real frost
#

Hello, How to make a slash command in message like this

proud mason
#

.slashcommandmention

winter condorBOT
#

</full name:ID>

proud mason
#

@real frost

real frost
#

appreciate it

final fractal
#

I'm new to slash commands; the code looks fine to me.

@bot.slash_command()
@option("url", description = "Enter the url for the text you want to be scraped.")
@option("summarize", description="Would you like the text summarized?", choices=["Yes", "No"])
async def scrape(
    ctx, 
    url: str, 
    summarize: str
    ):```
Here is the error:
```async def scrape(ctx, url: str, summarize: str):
TypeError: ApplicationCommandMixin.slash_command() takes 1 positional argument but 2 were given```
I saw something similar to this in https://github.com/Pycord-Development/pycord/blob/master/examples/app_commands/slash_options.py and I thought this code would work. Lmk if u know how to fix this.
GitHub

Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - pycord/slash_options.py at master · Pycord-Development/pycord

#

wait... i think its working... wtf

limber urchin
#

Please explain your solutions instead of just spoonfeeding code

blissful hazel
#

How to get a message by id?
I tried bot.get_message(id) but it returned None. The id matches with a message in a guild.

limber urchin
#

use fetch_message if get_message returns None, get_message only retrieves from the bots cache

#

fetch_messages makes an API call

gusty trail
#

Hey guys i have a problem when im try to make connect my discord code to the discord bot its showing me this

limber urchin
#

Read the error

gusty trail
#

i read but where i nedd to use intents

limber urchin
#

You need to define the intents kwarg where you initialize your bot

blissful hazel
silver moat
rare ice
#

AttributeError: 'dict' object has no attribute 'encode'

#
buffer = BytesIO(FORM.encode('utf-8'))
file = discord.File(buffer, filename=f"{FORM['name']}_export.json")

FORM is a dictionary

limber urchin
#

You can juse json.dumps to encode a dict

rare ice
#

god im starting to hate dealing with discord.File

rare ice
silver moat
rare ice
#

a bytes-like object is required, not 'str'

buffer = BytesIO(json.dumps(FORM))
file = discord.File(buffer, filename=f"{FORM['name']}_export.json")

don't even know if this is correct, i don't use the json module a lot :/

rare ice
blissful hazel
silver moat
#

i don’t think that’s a good sign on the day of finals notlikeduck

limber urchin
#

Is there a reason you don't have access to the channel when fetching the message?

rare ice
#

rip squid on finals

rare ice
#

f* json

blissful hazel
proud mason
limber urchin
proud mason
#

Also you might need to initialise the Bytesio first and then use the write method on it

#

Ayye i found an example

blissful hazel
limber urchin
#

huh?

proud mason
#

Use mongodb. It is just as easy as json

#

But safer and many times faster

limber urchin
#

?tag nojson

obtuse juncoBOT
#

Why not to use json files for data storage
JSON files are commonly used to store data that is read by a program, however, they are unsuitable for storing dynamic data due to a number of reasons.
It is recommended to use a DBMS (Database Management System) as they come with optimized technologies for storing and retrieving information.

Advantages of using a database:
- Database tables can be related, making it easy to separate your information into multiple tables and only fetch what you need
- Databases allow you to use a query/data processing language to make complex data operations easier with less code
- One misplaced character will corrupt an entire file. A database very rarely experiences corruptions due to their automatic handling of data integrity
- Transactions in SQL databases allow you to revert unwanted changes and prevent data corruption in the case of an error
- Databases have support for indexes, allowing retrieval of some data to be extremely fast
- It is very easy to update existing data in a database, as opposed to re-writing a file
- Databases are reliable

Popular database management systems:

  • SQLite3 (File based, no need for a server setup, SQLite is the most used database engine in the world)
  • MongoDB (Stores data in documents a similar manner to JSON format, easy for beginners)
  • PostgreSQL (Very popular and robust SQL based database management system)
  • MySQL (Another popular SQL based system, good start for learning SQL)
blissful hazel
#

And maybe a little bit of lazyness

#

Ill do it when i release it or smth

limber urchin
#

I mean you do you, but that sounds very inefficient

blissful hazel
#

It probably is

#

Idk if this is a bug but:

print(a.id)```
gives the wrong id but
```a = ctx.send()
print(a.id)```
gives the right one
rare ice
#

thanks

proud mason
#

Np!

#

||and i still wonder why I'm not yet a helper||

limber urchin
proud mason
#

ctx.respond.send_message is the same as ctx.interaction.response.send_message which returns an Interaction

ctx.send is the same as ctx.channel.send which returns a message

#

.rtfm interaction.response.send_message

winter condorBOT
#

Target not found, try again and make sure to check your spelling.

proud mason
#

Ugh

#

.rtfm InteractionResponse.send_message

winter condorBOT
proud mason
#

.rtfm context.send

blissful hazel
#

I feel stupid now

proud mason
#

To get the message id from interaction, use interaction.original_response

#

.rtfm interaction.original_response

winter condorBOT
blissful hazel
#

Thanks for all your help!

full basin
#

What the hell

limber urchin
#

First of all, just sending code without any explanation or question is completely useless.
Second, use codeblocks
Third, you have been told multiple times to learn Python before making a bot

#

No you have not

#

?tag codeblock

obtuse juncoBOT
#

Please put your code in a code block:
```py
Here is your Code
```

That makes reading code in Discord a lot easier:

print("This is an example.")
limber urchin
#

???

#

What does that even mean?

#

Are you reading your own code?

#

You've clearly missed a closing parenthesis

queen prism
#

Does anyone know why slash commands aren't showing in just one server? My bot is on many servers and slash commands are visible in all of these servers except for one server, any idea how to fix this? I invited the bot with applications.commands scope and waited over 1 hour.

proud mason
#

In that server

#

Or the server has 50 bots added

queen prism
#

I can use other bots' commands.

#

There's less than 50 bots in the server.

proud mason
queen prism
#

Yep.

proud mason
#

Hmm that's weird

queen prism
#

Hold on I think there are 50 bots.

proud mason
queen prism
#

Only 26 of them have app commands.

proud mason
#

Kick bots until there are less than 50 bots, add your concerned bot and then add the rest of them again

queen prism
#

I'll try that, thanks!

proud mason
#

Np 👍👍

hollow drum
#

hey guys how can i use the api command to fast search something?

full basin
#

Fast search what

hollow drum
#

.rtfm

#

.rtfm context.send

#

.rtfm avatar

limber urchin
#

If you're going to spam commands do it in #app-commands

hollow drum
#

but, i cant use that command

#

or is possible in other way?

limber urchin
#

??

hollow drum
#

i cant use .rtfm in bot commands

limber urchin
#

Then use #883236900171816970

hollow drum
#

thanks

limber urchin
#

You're clogging up this channel for no reason

hollow drum
#

srry

rare ice
#

what do you mean by "match the input"?

#

if you want a default value already in there you can use the value parameter

#

this then #998272089343668364 message ?ref

winter condorBOT
rare ice
#

.rtfm discord.ui.InputText.value

winter condorBOT
silver moat
#

.rtfm discord.ui.InputText.placeholder

winter condorBOT
silver moat
#

something else to look for

final fractal
#

If my bot is going to send something of 2000 characters what do I do?

silver moat
final fractal
#

Is there a way is can split my messages into groups of 2000 characters?

round rivet
#

embed description is like 2048

final fractal
#

I think it would be easier to send multiple messages instead.

#

How do I do that?

round rivet
#

i stand corrected

#

desc is 4096

round rivet
fervent cradle
#

im pretty damn confused
Error:

Traceback (most recent call last):
  File "c:\Users\XXXXXX\Documents\XXXXXX\main.py", line 36, in <module>
    async def keycheck(ctx, service):
TypeError: ApplicationCommandMixin.slash_command() takes 1 positional argument but 2 were given

Code:

@bot.slash_command
@option("service", str, description="2captcha OR capmonster")
async def keycheck(ctx, service):
    # Some code ...
#

(please dont say its anything obvious id off myself 💀)

limber urchin
#

it's @bot.slash_command()

fervent cradle
#

😭

#

that threw me off so hard

#

yeah

#

i forgot that

#

thanks rooSob

#

asked chatgpt and it didnt help at all

final fractal
#

ChatGPT is an unreliable source code because it is unfamiliar with Pycord. OpenAI is more familiarized with discord.py.

young bone
#

there is no listener

full basin
#

That's not a listener

young bone
#

^

#

#help-rules

obtuse juncoBOT
young bone
#

do you know basic python?

peak vector
#

Pong?

full basin
#

Do you know what premium_guild_subscription is?...

peak vector
#

I cannot

#

I’m not good at helping

full basin
#

You tell me

#

.rtfm Guild.premium_guild_subscription

winter condorBOT
#

Target not found, try again and make sure to check your spelling.

full basin
#

.rtfm premium_guild_subscription

winter condorBOT
#

Target not found, try again and make sure to check your spelling.

young bone
obtuse juncoBOT
full basin
#

It's not a context attribute

limber urchin
#

You have conflicting libraries, uninstall everything that has to do with discord other than py-cord

#

?tag install

obtuse juncoBOT
#
  1. Uninstall discord.py or any other forks of discord.py you might have with the namespace discord.
    python -m pip uninstall discord.py discord -y

2a. Install py-cord
python -m pip install py-cord

2b. Update py-cord
python pip install -U py-cord

Installing other builds:
Note: You need to have git installed. Use ?tag git to find out how to install git.

Updating the module to master branch (unstable):
pip install -U git+https://github.com/Pycord-Development/pycord

limber urchin
#

Then that's an issue with replit

winter condorBOT
#

Tag not found.

Did you mean...
noreplit

silver moat
#

reinstall py-cord.

#

then restart IDE

#

uninstall, install

#

it basically is, but Bob, the owner, likes the partner badge better for color scheme I think.

errant craneBOT
#

[AFK] just a squid is AFK: No reason specified.

silver moat
#

you are getting ratelimited

limber urchin
#

You're getting rate limited

silver moat
#

replit?

#

run kill 1 in the shell

#

and run

#

repeat until it works

rare ice
#

Don’t use replit :/

#

I use a really cheap host, $1/month. There are other hosts like it too.

#

Very good uptime and performance

silver moat
full basin
#

Man got roasted by a squid

rare ice
#

The fastest ping I’ve seen for my bots was 5ms

#

when discord didn’t have bugs

zinc cloak
#

Is there a way to have slash commands separated in different files?

#

If so, how would you do that?

limber urchin
#

The same way you do with any commands, cogs

zinc cloak
#

What's a cog?

zinc cloak
#

thx!

zinc cloak
proud mason
#

You can use discord.Bot if you only want Slash cmds and not prefix cmds

#

You have to use discord.Cog instead of commands.Cog then

#

Rest of the stuff is almost the same

vale heath
#

hey can i use ctx.defer() multiple times in one cmd or once its sufficient thenking

vale heath
#

ok thanks ok_fidget

fervent cradle
vale heath
#

is there a way to able to type message with shift+Enter in a suggestion slash cmd thenking

limber urchin
#

No

winter condorBOT
#

Why NOT to use Repl.it 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.

IMPORTANT

  • 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/Railway and its respective free tiers or just pay for an actual VPS.

novel jay
#

Actually you can.

#

i don't need help but just pointing out you can

vale heath
#

.rtfm modal

drowsy hound
#

Hello! Is there any kind of tutorial about the discord.ui ? Docs don't give much info tho...

civic jayBOT
drowsy hound
#

.rtfm button

vale heath
blazing tide
#

hello

#

can u guys help me with this problem

raw gust
#

No clue what your Problem is tbh. #help-rules

blazing tide
#

when i type

#

interaction.response.send_message its dont send any message

young bone
blazing tide
#

the problem is with response.send_message

blazing tide
raw gust
#

Sorry i dont understand. I dont see any interaction.response.send_message in your code.

blazing tide
#

sorry

#

wait

#

whats the problem here

young bone
#

Why is the name empty?

blazing tide
#

where

young bone
#

Of the fields?

blazing tide
#

oh

#

bc i dont want the bold text of fields

raw gust
#

You send the message before making the embed?

blazing tide
#

i put invis msg

raw gust
#

Do you have any Error message?

blazing tide
#

no

vale heath
blazing tide
young bone
blazing tide
#

bruh

raw gust
# blazing tide true?

Can be but as far as i know send_message does not have a embed1 keyword argument. Aswell as it actually should throw an error if it would have run up until this point.
I am not sure if your callback is actually connected with your button. I always make custom calsses, so i can not help you with that sorry.

vale heath
#

Ok will try

young bone
blazing tide
young bone
#

For what?

blazing tide
#

if i send my source code an u fix it im newin python
PLS?

blazing tide
young bone
#

#help-rules 3

blazing tide
#

um okay

#

np

vale heath
#

Is it possible to use same modal in two different cmds sending output in 2 different channels ?

blazing tide
#

yooooo

#

i fix that problem

vale heath
#

Noice ok_fidget

blazing tide
#

and can anybody say me how can i connect this buttons to my response message

#

PLS

blazing tide
raw gust
#

You need to learn basic python. Your class does not have a init.
This is not to shame on you or anything but knowing Object Orientation is important for using pycord.
The answer would be you need to add func init to your Button class.

blazing tide
#

NICE I DIDNT UNDRESTAND ANYTHING

#
class MyButton(Button):
    async def callback(self, interaction):
       embed1=discord.Embed(title=f"Server Rules",description="ما قوانین سرور رو به دو زبان فارسی و انگلیسی نوشتیم با استفاده از دکمه های زیر یکی رو انتخاب کنید، و بخونید", color= 5793266)
       embed1.add_field(name=f"ㅤ", value="ما قوانین سرور رو به دو زبان فارسی و انگلیسی نوشتیم با استفاده از دکمه های زیر یکی رو انتخاب کنید، و بخونید", inline=False)
       embed1.set_image(url="https://media.discordapp.net/attachments/1052540239668846592/1053629574329671690/rules-concept-people-letters-icons-flat-vector-illustration-isolated-white-background-rules-concept-people-139612137.jpg?width=1260&height=546")
       buttonfa = buttonfa(label="Persian", style=discord.ButtonStyle.green )
       buttonus = buttonus(label="English", style=discord.ButtonStyle.blurple,)
       
       view = View()
       view.add_item(buttonfa)
       view.add_item(buttonus)
       await interaction.response.send_message(embed=embed1)
blazing tide
#

?

raw gust
#

I will not be able to explain Python to you.

class MyButton(Button):
  def __init__(*args, **kwargs):
    super().__init__(*args, **kwargs)
  async def callback(self, interaction):
    ...

This would fix it I think. I did not test it so i am not sure. But i highly encourage you to learn Python.

blazing tide
#

HEHE OKAY THANKS

#

IYS WORKEDDDDD

proud mason
vale heath
#

i am trying to use it as suggestion cmd but i need two different cmd for two different role holder heh

proud mason
#

You are at the wrong place my friend. This is a pycord server. This is where people build bots

I'll help you anyways. You can disable the Slash command from server settings

delicate jolt
#

wait

#

ctx.respond?

#

I'm not sure

vale heath
#

ctx.respond

delicate jolt
#

^

#

There's your answer

winged zephyr
#

gives error

delicate jolt
#

what error?

#

you need to define ctx in your function

winged zephyr
#

application did not respond

winged zephyr
vale heath
#

message.respond

delicate jolt
#

message.respond

vale heath
#

lol they not using ctx checked now kekw

delicate jolt
#

xddddd

winged zephyr
#

i know basics

#

the tab var takes more than 5 secs and app should respond in under 3 secs else discord shows no respond error

delicate jolt
#

is your latency high?

winged zephyr
#

i tab is an api req so

#

it takes time

delicate jolt
#

hmmm i would just cry at this point

winged zephyr
#

please any pro guy help me 😦

#

Application Command raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction

vale heath
# proud mason Oh yeah that's fine. You can do that. You would need to pass ctx.command to the ...
import discord
from discord.ext import commands,bridge
from datetime import datetime


class MyModal(discord.ui.Modal):
    def __init__(self) -> None:
        super().__init__(title="test")
        self.add_item(discord.ui.InputText(label="Short Input", style=discord.InputTextStyle.short,required=True))
        self.add_item(discord.ui.InputText(label="Longer Input",style=discord.InputTextStyle.long,required=True))

    async def callback(self, interaction: discord.Interaction):
        print(self.cmd)
        uid= interaction.user.id
        avatar=interaction.user.display_avatar
        authorm=interaction.user.mention
        authorn=interaction.user
        tym =datetime.utcnow()
        embed = discord.Embed(title = "Suggested By", description =f"{authorm} / {authorn}", colour= 0xFE6000, timestamp =tym)
        embed.add_field(name =f"Title:\n{self.children[0].value}" , value = f"Suggestion:\n{self.children[1].value}", inline = False)
        embed.set_footer(text=f"User-ID:{uid}")
        embed.set_thumbnail(url = avatar)
        await interaction.response.send_message(embeds=[embed])
    
class sugg(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @bridge.bridge_command()
    async def sug(self,ctx: discord.ApplicationContext):
        await ctx.send_modal(MyModal())

    @bridge.bridge_command()
    async def gsug(self,ctx: discord.ApplicationContext):
        await ctx.send_modal(MyModal())    

def setup(bot):
    bot.add_cog(sugg(bot))

where my brain.exe getting crashed heh

winged zephyr
#

it raises this error

proud mason
winged zephyr
#

@proud mason

proud mason
vale heath
winged zephyr
raw gust
# winged zephyr nooooo

Didnt your Question already get answerd? Use defer befor your api call then respond with followup.

proud mason
vale heath
proud mason
#

Wait i have a better plan

vale heath
#

Sry 😞

proud mason
#

In the init of your modal, accept a channel id. Then assign it to self.channel_id

In the command, pass the channel id to the modal like this MyModal(channel_id=12345)

#

Change the id according to the command

vale heath
#

Ok will try after sometime 👍

proud mason
#

What error

young bone
#

ctx.respond

proud mason
young bone
#

still respond

#

not send

proud mason
#

Oh in the error you mean

#

Why assign cursor again when you are getting it from async with

#

Remove the 2 lines where you reassign cursor

#

And pass that dict cursor thing to the async with cursor

#

Hmm show updated code

#

And explain what exactly is wrong

#

Any errors?

knotty surge
#

Hello all, for some reason my second slash commands arguments are not updating when I restart the bot (url being the one which isnt working), this is my py code:

@bot.slash_command(name="adduniform")
@discord.option("template", description="Enter the Template's Name")
@discord.option("url", description="Enter the imgur url for the template must be a .png")
@discord.option("div", description="Choose what division this is for",
                choices=["LPT", "RPG", "FSG", "SYFRS", "YAS"])
@discord.option("type", description="Choose the type of clothing",
                choices=["Shirt", "Vest", "Helmet", "Shoes"])
async def adduniform(
        ctx: discord.ApplicationContext,
        template: str,
        div: str,
        type: str,
        url: str
):
    #get_image(url)
    await ctx.respond(str(div) + " - " + str(template) + " has been uploaded.")

Any help would be great

fervent cradle
#

How can bot create a webhook?

verbal marten
#

.rtfm discord.Webhook

verbal marten
vale heath
#

But how to check for time out or if someone close the panel 🤔

#

.rtfm modal.timeout

winter condorBOT
#

Target not found, try again and make sure to check your spelling.

vale heath
#

.rtfm modal

proud mason
proud mason
vale heath
vale heath
proud mason
#

It will work

#

Each modal is separate from the previous ones

vale heath
#

K

winged zephyr
# proud mason What error

Application Command raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction

winged zephyr
limber urchin
#

What is jj.order?

winged zephyr
limber urchin
#

No, what is it? What does it do?

#

Where it is doesn't matter

winged zephyr
#

it contacts api and returns the response

limber urchin
#

So you should defer before sending a request

winged zephyr
limber urchin
#

You did not

winged zephyr
#

ok

limber urchin
#

How is that before?

winged zephyr
proud mason
#

And why the asyncio.sleep?

proud mason
limber urchin
#

Also since you're not awaiting that API call, it's probably blocking and will stop your bot from executing anything until the request is done

winged zephyr
#

thanks for help

blissful hazel
#

You forgot the capital letter Bot

#

from discord import Bot

#

Yes

#

No problem!

rare ice
#

Read the error

#

'ApplicationContext' object has no attribute 'member'

#

.lp

winter condorBOT
#
limber urchin
#

If you don't understand that error you probably don't know enough Python to be making a bot

#

wtw?

vivid plaza
#

You need a minimum knowledge of Python before making a discord bot.

jaunty raft
#

Remove the ctx. part

#

Haha np

echo egret
#

does on_voice_state_update trigger when a user is muted even when not in a voice channel?

knotty surge
#

Where is the embed documentation?

    embed = discord.Embed()
    embed.insert_field_at(1, "test", "Hello World", True)
#

This is not working

#

Any help/point in the right direction would be grand

full basin
#

.rtfm discord.Embed

full basin
knotty surge
full basin
#

Whats confusing about it?..

knotty surge
#

Is it like this:

    embed = discord.Embed(title="Test")
    embed.field("Blah")
     await ctx.respond(embed)
#

Sent my request

#

Came out like this

<discord.embeds.Embed object at 0x00000298562E80D0>
full basin
#

.rtfm Embed.field

winter condorBOT
full basin
#

Embed.field doesn't exist

#

You're looking for add_field method

#

And when responding, you need to provide the kwargs embed=embed

#

.rtfm ApplicationContext.respond

winter condorBOT
knotty surge
#

Ah awsome thanks mate, still quite new to this noticed I was missing something with ctx.respond(), thanks mate

proud mason
river dove
#

how do i reset command cooldown

final fractal
#

Is there something like if slash_command.user == 751563727161000017:?

candid wolf
#

hello guys I have a very basic question I believe : how can I respond to a message from a slash_command? I currently return an embed using ctx.send(embed=embed) and get the Application is not responding message because it is not seen as a response

proud mason
#

That's all

final fractal
proud mason
#

Np 🙃

proud mason
full basin
#

You have *users

#

It takes the second argument and the rest

#

Yes indeed

#

You'll never be able to get the reason

#

You'll need to take a str and parse the stuff yourself

lone kiln
#

Can I give a slash commands group default permissions with decorators like simple slash commands ?

full basin
#

Try it and see

lone kiln
rare ice
#

.tias

winter condorBOT
lone kiln
limber urchin
#

There's a difference between asking for basic help and just being too lazy to find out on your own

rare ice
#

^

#

Not trying your own code is just being lazy.

fleet marsh
#

how do you mention a slash command like this?

silver moat
#

.scm

#

.slashcommandmention

winter condorBOT
#

</full name:ID>

silver moat
#

.rtfm slashcommand.mention

winter condorBOT
fleet marsh
#

does the command need to be global?

#

doesn't work for me (just displays the string "/command")

#

isinstance(channel, discord.Thread) id assume

full basin
#

Do you realize we don't know what your code does and you never stated what isn't working

#

We're not some type of "provide code, we fix it for you" AI

limber urchin
#

You've been told multiple times to ask your questions properly instead of just sending code and expecting someone to fix it for you. If you can't ask a proper question, no one is going to help you and you're just wasting time.

young bone
fervent cradle
#

takes 2 long

limber urchin
#

We've told him like 5 times, but it seemingly does nothing

fervent cradle
#

idk how to add client intents

limber urchin
#

?tag intents

obtuse juncoBOT
#

https://docs.pycord.dev/en/master/intents.html
https://discord.com/developers/docs/topics/gateway#gateway-intents

import discord
from discord.ext import commands

# Get specific intents for fine control
intents = discord.Intents()
intents.emojis = True
intents.guilds = True
intents.messages = True  # Required for prefix commands!
...
# Get all non-priveliged intents; this excludes presences, members and message_content 
intents = discord.Intents.default()

# Set priveliged intents: these must be enabled on dev portal
intents.members = True
intents.presences = True
intents.message_content = True  # Required for prefix commands >= 2.0.0b5

# Get all intents; all intents must be enabled on dev portal.
intents = discord.Intents.all()

# Apply intents when creating your bot
bot = commands.bot(prefix="?", intents=intents)
Discord Developer Portal

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

fervent cradle
#

can i just pay you to fix it

limber urchin
#

no

fervent cradle
#

well you sent a thread that does not define how to add it in the code?

full basin
#

The irony

limber urchin
#

If you don't understand that, you're not ready for Discord bot development. Read rule 1 in #help-rules

fervent cradle
#

very odd i have to understand the language fully to receive support

#

ngl

young bone
#

hey @limber urchin can Helper mute people?

rare ice
#

let’s find out troll

young bone
limber urchin
rare ice
fervent cradle
#

yea ill just pay a helper to rewrite it for me

limber urchin
#

Good luck 👋

full basin
#

Tryna milk the cow but doesn't have a cow

rare ice
young bone
limber urchin
rare ice
#

You’ll get no where in life if you’re like that.

limber urchin
rare ice
#

Tbh if someone payed me to fix code I’d say hell no learn the language.

fervent cradle
#

learning python isnt a priority i need when i have the funds for someone to fix it

young bone
limber urchin
young bone
#

x3

limber urchin
#

What's the command? -mute?

fervent cradle
limber urchin
fleet marsh
#

not "developers for hire"

full basin
#

Yes. It's not "rent a helper"

fleet marsh
#

LMAO

limber urchin
full basin
#

Lmao everyone thought the same

rare ice
young bone
#

-mute

wanton pondBOT
#
Mute <User:Mention/ID> <Duration:Duration> <Reason:Text>
Mute <User:Mention/ID> <Reason:Text> <Duration:Duration>
Mute <User:Mention/ID> <Duration:Duration>
Mute <User:Mention/ID> <Reason:Text>
Mute <User:Mention/ID>

Invalid arguments provided: No matching combo found

limber urchin
#

-mute @limber urchin 5m test

wanton pondBOT
#

Unable to run the command: Can't use moderation commands on users ranked the same or higher than you

limber urchin
#

Oh

rare ice
#

Interesting

full basin
#

Try with me

limber urchin
#

-mute @full basin 10s testing

wanton pondBOT
#

Unable to run the command: The Mute command requires the Kick Members permission in this channel or additional roles set up by admins, you don't have it. (if you do contact bot support)

limber urchin
#

I see

rare ice
#

Rip

#

-mute @full basin 5s testing

wanton pondBOT
#

🔇 Muted dark#8901 for 1 minute

fervent cradle
rare ice
#

-unmute @full basin

wanton pondBOT
#

Unable to run the command: A reason has been set to be required for this command by the server admins, see help for more info.

young bone
#

xd

rare ice
#

-unmute @full basin o

wanton pondBOT
#

🔊 Unmuted dark#8901

limber urchin
fleet marsh
rare ice
full basin
#

I'm amazed these kind of people exist

rare ice
#

^

#

I lose a few brain cells every time I see someone like that

limber urchin
#

People on the internet never fail to surprise you