#Basic Pycord Help (Quick Questions Only)
1 messages · Page 28 of 1
mmm okay I shall try to locate such. I just need to define these terms as I'm SUCH a noob to all of this. Tysm for the help
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'
Show the pip list
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 >.<
uninstall all this
discord 2.0.0
discord-components 2.1.2
discord.py 2.0.1
discord-webhook 0.14.0
discordSuperUtils 0.3.0
tbh
uninstall pycord
discord-webhook is fine
pycord is also fine
uhh yeah thats what it is for most basic docker files
py-cord yes, pycord no?
It's just NOT letting me build the image >.<
failed to solve with frontend dockerfile.v0: failed to read dockerfile: open /var/lib/docker/tmp/buildkit-mount883359202/Dockerfile: no such file or directory
it didn’t have any conflicts
yeah but why have it when 1 lib does it and does it good
k
run pwd in the directory your code is in and use that
because slightly more memory efficient

Still the same error
||gonna use space when user most likely didnt want that library||
whats the location of your main.py
C:\LocalCode\kidsoftheapocalypse\main.py
yeah then remove main.py from it
and use that.
try C:\LocalCode\kidsoftheapocalypse ig
failed to solve with frontend dockerfile.v0: failed to read dockerfile: open /var/lib/docker/tmp/buildkit-mount4077465603/Dockerfile: no such file or directory 
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”]
dk then. havent done docker before. i wanna use it but idk where to start and what guides to use
it's named Dockerfile not dockerfile right
tbh, there are great tuts on google, but I am seriously stuck at this error I'm getting
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
yeah but looking for some basic stuff. last time i got stuff for more advanced things. will see again tho
Tried changing path - changing drives - changing images
are you building it in vscode
yes'
must be the issue
INTERESTING
okay, so I'm so sorry I'm such a noob..what is considered a "normal terminal"?
got it! Will try!
hit win+r and type in cmd
windows search (bottom left. idk what thats called) would get you there too
windows key and start typing will open search
mhm that thing
Yea, no still jack shit from the CMD Prompt. I'm stuck on this one 🥹
did you go to the directory your files are in?
OMFG
I THINK IT'S WORKING
cd C:\LocalCode\kidsoftheapocalypse iirc. i have forgotten how windows does it
omg a new error 🥲 
thats progress 😂
FACTS! hahaha
Gonna keep at this! Thanks for the help xD
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.
not exactly sure, i think you can create a decorator that add attribute to the function use the thread
~~somewhat like https://github.com/Pycord-Development/pycord/blob/master/discord/commands/core.py#L1725~~
use the thread
please do not crosspost
this is basic python
you are making a comparison between two values. what is the comparator
did you mean select.values[0] == "4":?
man really needs his own help channel
@me rn with this bs Docker setup LMFAO
lmao
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 :/
Running it manually in a VM would also be the next option
If you need a reference for how I do it, I'll put a link on my version based on the Alpine Linux base: https://github.com/No767/Kumiko/blob/dev/Docker/Alpine-Docker/Dockerfile
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?
For asyncpg just make the connection uri (refer to the docs). And for an ORM, just refer to the docs of that ORM
if i have the numbers 1-10. How can i return all combinations of three numbers that add up to be less than 7?
is this homework?
no its for a bot but im having an aneurism trying to figure out how to write it
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
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
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
oh ok tyvm my squishy friend
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?
probably using an HTTP server instead (and directly contacting the discord gateway instead). iirc this is what MEE6 and Dank Memer had to do since their discord lib (which im guessing is discord.js) couldn't handle the sheer amount of sharding that was needed
mee6 runs on python and dank memer runs on eris
oh thanks for telling me that
no
No one is going to spoonfeed you. Does anyone even read #help-rules ?
No, it's too long. 
You know how some bots join servers FOR you when you add them to your server? How can I implement that into my bot?
that's not strictly bot invites, that's using other oauth2 scopes which isn't part of the library
https://discord.com/developers/docs/topics/oauth2
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
Which section is it?
Sorry, got 0 hours of sleep last night, don't want to strain my eyes for too long.
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.
crazy
#1031475930297798706
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
You have to wrap a generator (x for x in) in brackets [] so it's a list
Also you'd probably want to use string joining
light theme 💀
it now raises the error, int object has no attribute mention, how do i fix that, i mean if it was one id i could convert it to role object, but here there are list of ids and am not sure what to do
So is rlist a list of IDs?
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}>"
can i use guild. get_role for a list of ids (int type) and get it converted to list of users types?
Uhh if you want a user it'd be bot.get_user or guild.get_member
wait no i mean sorry to role types not user types
You'd have to use get_role on each ID in the list separately
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?
interaction.message
thank you! 🙂
thanks it works just one last thing is it possible if i can remove those quotes and brackets from the output (since its a list) without using map or join?
why wouldn't you use join
just wanted to know if there are any other methods too
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
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?
what about python3 instead of python
Same error :/
yeah idrk much about pm2
might be best to google or maybe find a server that's dedicated to it
I gave up on Docker because I couldn't get numpy legs to generate and now PM2 has me stuck here 
rip
Google has nothing for me (been all over), but good idea on looking for a PM2 server! I will try that out ^-^
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!")
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
message = ctx.respond()
print(message)?
My message has been edited by the bot several times so I do not have to retrieve the message at the beginning
For dockerfiles, use tini to spawn PID 1 as the process u want (probably the bot), and then once the docker container stops, tini will reap all zombie processes
I used to use pm2 but it isn't the best way to use in docker images
You can message.id there.
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 Solved in a different way (see below).on_message_edit() and check if the message being edited needs to be edited back.
I've managed to edit it back by using Solved by passing 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?attachments = [].
After further investigation, it seems that when used with application commands it uses application context, not message
no it always uses i actually can't tellContext
I've wound up switching to pm2 from Docker all together, but it's presented it's own array of problems ofc 🥹
try specifying the python with its version in the interpreter flag --interpreter=python3.10
or --interpreter=/path/to/bin/python
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
1, it was bugged
Oh alright
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
This is what ended up working for me! ^-^
Yeah. You can use asyncio, don't know how to at all. But Google has some answers.
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?
no, but datepicker is a planned feature
Oh cool
Is there like a feed where new features get posted
well that'd be #discord-api-updates
.tag noreplit
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.
Railway
I recommend imo
But you should just get a VPS
It’s worth it
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?)
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())
yep if you want to use pycord you need to install py-cord. crazy huh?
well, discord.py and py-cord use the same namespace so conflicts
Which would you say is better, now that discord.py is back?
React with
for Py-cord
React with
for discord.py
Opinions?
both have their own ups and downs. Neither is exactly better than the other from a library perspective since both use a very similar codebase.
add wikipedia==1.4.0 in requirements.txt
Far more people know about discord.py, which makes it more trusted. However, py-cord is almost always more up-to-date.
That pretty much goes for anything haha
YouTube Coding Videos are useless.
You can't understand anything.
ikr imagine using replit after railway
Yeah. Sadly I live in Oceania, so I get an average of 82 Ping. But, lately I've been getting something like 1830 ping.
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
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? 🥲
interaction.followup.send
it throws me AttributeError: 'Webhook' object has no attribute 'send_message'
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?
?tag ex
Bot examples: https://github.com/Pycord-Development/pycord/tree/master/examples
Slash command/context menu examples: https://github.com/Pycord-Development/pycord/tree/master/examples/app_commands
Buttons, dropdowns example: https://github.com/Pycord-Development/pycord/tree/master/examples/views
?tag guide
?tag docs
ahh, the examples are what I needed! Thank you!!
( I try to read the docs, but my pea brain gets confused
)
it's all fine. this channel exists for a reason
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...
all good
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
);
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
🤔
There are like 3 attributes for avatar, never knew what's the actual difference
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
When you open the connection to the database, you need to enable pragma keys.
query = "PRAGMA foreign_keys = ON;"
async with self.client.database.cursor() as cursor:
await cursor.execute(query)
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
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
return x should be at the very end, on the same level of indentation as result, otherwise you aren't returning anything when the else happens.
oh ok
wait a sec
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
You can use break there.
but x becomes False in the end
oh yea
ty
@spice oysterstill getting the same issue
I had a suspect it wouldn't have been enough. I don't know what else is wrong. Can you share the full traceback?
wait im trying smth
nvm
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
what's ur code now
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
how send files like this
ctx.send(there file)
await ctx.send(file=file)
ok i test
with the import
yeah i know
discord.File()
@cobalt tangle can you send etc
file=discord.File("file.txt")
thanks
^
If required, send the path
ok
is eny way to randomize what its send(i want my bot send random videos what i added in)
What's the line where you get this error?
Make a list of videos, choose a random number and use it as index.
ok i test
return x
You can just loop and use random
Also that. I doubt they need to use the secrets module in this case but it's an option even with that.
why this method dosent work
https://imgur.com/CflAXv6
oops
yeah too big file
Solved? If not, paste the full traceback.
no solved
#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
Add ctx.defer() at the beginning of the Slash Command.
Are the files in the same folder as the file calling them?
like this
ctx.defer()@bot.command(description = "heittä kivi")
async def kivi(ctx):
await ctx.respond(file=tiedosto)
yeah there are
No, you just call it inside, on the first line.
like this @bot.command(description = "heittä kivi")
ctx.defer() async def kivi(ctx):
await ctx.respond(file=tiedosto)
Please, this is basic stuff. Inside the function.
async def kivi(ctx):
await ctx.defer()
await ctx.respond(file=tiedosto)
i am beginner sorry
@spice oyster thanks A LOT I think you should get some helpper role
I'm happy it worked. 
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"
You can use either button.disabled = True or self.disable_all_items().
button.disabled*
ty
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
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")
As I tryed respond and it said that it was not a attabut of context.
do you have something else installed?
No.
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.
can you show the pip list and also which version is installed?
version of pycord?
yes
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.
update it and try it again
After the update it popped up this.
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?
Anyone?
?
permissions
?
Did they get rid of is_owner as that seems to be erroring now?
?
commands.is_owner()?
Same thing after the update.
?
@bridge.bridge_command()
async def test3(self, ctx):
await ctx.respond("Test")
That is the code that is with it.
yes
So all it will change is allowing bridge commands to work?
yes
Do I need to change anything else in the line I have?
Or is that all.
What do I need to know while creating a new instance to host my Discord bot on Oracle?
What's the easiest way to upload all my files? I'm a bit lost after creating the instance.
thanks !
GitHub clone ?
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
@fervent cradle Please don’t ping support members randomly.
ooooo new docs
It shouldn’t
Make sure you have NO other slash commands with the same thing
Double check every file
The function name is irrelevant if you override the name on the decorator.
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
With some editors you can open the project folder and easily search a string across all files.
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??
you forgot self
you dont need to do datetime.timedelta, just put 5 as the argument
it takes a datetime.timedelta object
why doesn't my discord bot work on other servers?
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.
added my bot to another server and it doesn't work
define doesn't work
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
code ?
oops i saw the error
ok
At your PC?
lmao

Using python?
Like are you asking which IDE to use or which language or something else?

I guess he's talking about the ide
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^^
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...
is it online or?
do i need to download smt?
like, where do i go to program my bot?
Watch the video I linked and read #help-rules too.
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?
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.
Check if inspect.iscoroutinefunction() (also available in asyncio, but slightly different) is what you need.
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```
how do I implement disconnect and cleanup for a vc?
no, we will not do your homework
pls stay in one channel
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
drop the code.
wait come this thread https://discord.com/channels/881207955029110855/1032277645515296848
is that in a command?
no
on_guild_join(self, guild)
and its version specific i suppose, as its fine for my development server
you could do len([member for member in guild.members if not member.bot])
yes, i am not saying its not working, its just, if there's an error in library's code that can be fixed
which version do you have installed?
py-cord 2.2.2
that one works for me
version?
2.2.0
i have 2.1.0 installed in development serv
hmm
guess i ll have to downgrade the version
do you have something else installed?
nope
or try it again?
Is there a way to squash commits that happened before a merge? I'm getting this error. 
In an IDE like VS Code and Pycharm. Make sure to have Python installed as well
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}")
Full traceback
Lots of places
You got VScode, replit, Pycharm
Like wherever you code python
IDLE works too
You mean IDE.
No idle
The python ide
The not good one that comes with python
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
Does does one programmatically add a reaction to a message?
if message.author == self.bot.user:
thanks
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
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.
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
I don't think you have other alternatives.
see https://docs.pycord.dev/en/stable/api.html#discord.Bot.listen for example usage
(cog.listener is equal to bot.listen)
well i tried having multiple cog listeners with on_mesage event but it just called the last one
my code was like this, and it only called the 3rd event
because you called all your functions the same name
as i said, the docs shows how to do it with different names
ok thank you
hello, any idea how can i get the selectmenu selected option from interaction?
discord.ui.Select**.values **
from interaction
You receive select ^ on the callback
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 traceback
if you get it from the modal why do you send the button and not the modal? also you get the error what tells you a field is empty
the modal is crazy long
and was working a bit ago
A full traceback would help to detect what you're missing
check the modal if something is only "" or '' without a text or something else
i dont
In data.components: This field is required it says this so would it by any chance have new params?
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
you didn't initialize the view
create __init__ and put super().__init__
update your pip with
pip install --upgrade pip
Ok and how do i make python program my bot?
to make a bot in python ?
I recommend learning how to use python first.
i know how to use python, i just dont know how i integrate a discord bot in this mess
@silver moat ^
i suggest you read the pycord guide first: https://guide.pycord.dev/
Still same issue
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
guys do you know if there is a snippet available anywhere for selectmenu callback usage?
I don't know if this is something similar to what you were looking for
But, I found this: https://guide.pycord.dev/interactions/ui-components/dropdowns/
this did not really help me
i still do not know where i code the bot...
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...
this vid iirc uses replit, which is fine for testing and educational purposes, but hosting on replit is a poor move
shared ips, poor specs, etc etc
running your bot on a VPS or on something like AWS, Azure, Oracle, DigitalOcean, or GCP
ok
How do I make an argument not required? I don't see anything about it in the documentations.
IMO The best things are:
A. Your own VPS.
B. Self-hosting.
C. Railway
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
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
try upgrading pip using pip install --upgrade pip
didn't work
do you lack the ability to read? people have told you multiple times- stop trolling
if you can't figure out how to open an IDE then your odds of writing a single line of working code is next to none
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
Can you be more specific to what you mean be where?
Do you mean host the bot?
i mean what website or program do i use to program my bot to do stuff
Official Beginner's Guide: https://wiki.python.org/moin/BeginnersGuide
Official Tutorial: https://docs.python.org/3/tutorial/
Shortcuts:
https://wiki.python.org/moin/BeginnersGuide/NonProgrammers
https://wiki.python.org/moin/BeginnersGuide/Programmers
Learn Python:
https://automatetheboringstuff.com/ (for complete beginners to programming)
https://learnxinyminutes.com/docs/python3/ (for people who know programming already)
https://docs.python.org/3/tutorial/ (official tutorial)
http://python.swaroopch.com/ (useful book)
http://www.codeabbey.com/ (exercises for beginners)
Learn Python™️ ^
Why don't slash commands appear? cog
@commands.slash_command(guild_ids=[GUILD_ID], description="test")
.tag commandnoshow
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)?
-
yes
-
yes
-
No
-
Just installed
-
yes
-
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 -
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))
Point 2 is a no in your case. Please, fix.
I understood, I was stupid about something
thanks
Mistakes happen. 
my checklist 
This can't be the best way to do it right?
string = ctx.author.name+"#"+ctx.author.discriminator
what's wrong?
Is there any better way to do that?
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
do you use discord.py?
pycord
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
@option("test", description="test", required=True)
How to make a mandatory text field?
so that the number could not be entered
str?
yes
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
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?
Check the error output. I suspect it's either that you are using an older version of Python, which may be breaking with building the wheels needed
2.2.0
Version i am using of pycord
The version of Python you are using
3.10
hm ok. Post the full error including the trackback as well
Oki kindly wait
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
I am a beginner 😅 idk whats aiohttp
Aiohttp is a http lib that Pycord uses
So what is the solution? Should i manually install?
how do i create a custom check for blacklisted users which has a decorator like this ig
@checks.is_blacklisted()
How do you get a username without the tag behind it?
That works, thanks!
answering to my own question in case anyone needs it - it can be retrieved from interaction.data
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
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.
in terms of string representation it is not a single character
try it - just print it out
It should automatically install with Pycord
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?
so you want to check for emoji or eliminate it from the argument to the command?
no clue about that, sorry
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)
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])
pretty sure you copied the message ID
unicode emojis on discord don't have IDs
If a members gives us the premission guilds.join is there a code example of how we can make the user join a guild?
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
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'
did you use bridge.Bot?
yep i did bot = bridge.Bot(command_prefix=commands.when_mentioned_or("-") intents=intents, help_command=HelpUpdated())
it works fine for prefixed commands but only breaks for slash commands which is pretty weird
where did you load the cogs?
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
ping me there
sure
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):
...
you can't use self in decorators
What does that mean?
You can't access self on decorators
How can I access a context then?
view=setupView(context=ctx)
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
you can intance the button then add it manually using .add_item
AttributeError: 'setupView' object has no attribute 'children'
you gotta init the super first
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):
...
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)
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
@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
Each modification gives me an error
We aren't Python interpreters, so errors could happen.
If you gave us the actual errors and traceback you encountered from our suggestions, this will help you and us.
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'
.add_item
I think it's time for me to go to sleep....
button.callback = self.addToken
wihout the parenthesis, also add self.
it work
also the callback takes only 2 arguments, (self, interaction)
button.callback = self.addToken I don't really understand this point
depends, if you define the callback as your view method (same indent as __init__ function), then you access it with self
if you define your callback as a local function (defined under init ), you can access it directly without self
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
wihout parenthesis
you called addToken
adding parenthesis means you call them
ugh.. i dont know how to call it, what i mean is ()
Ah... logic... 😅
If I want to send arguments in my function, how do I do?
addToken() takes 0 positional arguments but 1 was given
add a param then
it should take one parameter: interaction
addToken(arg, arg, arg) like this then?
Or is there a different way to do it in this case?

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
1st what i suggest you is make the callback as method for your view
then add only 2 param (self, interaction)
with that you can access any data under your view class with self
class setupView(discord.ui.View):
def __init__(self, context):
self.data1 = 1
super().__init__()
async def cb1(self, interaction):
self.data1 = 1
...
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
How do I make {member.roles} return a list of roles instead of this ugly little thing:
@silver moat ?
I mean technically it is a list, but it's not ideal.
Can't you just member.role.name?
WDYM?
role_names = [role.name for role in member.roles]
And? It's easy to continue now.
Ok i think i know what you mean
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
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.
You're not doing it the right way sadly.
Here's the format.
embed.set_footer(text=f"{message.guild.name} | {message.guild.owner} | {discord.utils.format_dt(<your timestamp here>, "f"))
alrighty, thanks ill try it
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
embeds are annoying to work with ugh
You can use timestamps anywhere else in the embed though.
it doesnt seem to like this, its saying its missing a closed bracket somewhere but I cant see where
You have to use ", ".join() for creating a string.
where do i use it?
The slicing is for removing @everyone.
values = ", ".join(role_names[1:])
??
define ur time stamp where you define the embed?
embed = discord.Embed(timestamp = …)
^ meant to reply to this
TYYYYYYYYYYYYYYY
You are welcome but that's just Python stuff you should already know. 
what kind of value does this take?
datetime?
^
How do I use an @mention as a prefix?
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
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!")
cmd group
the entire group has to have guild_ids
you can't do it on specific subgroups/subcommands
how do i do that
thats fine with me
just put it in SlashCommandGroup
rip okay
i understand
it makes sense
discord enters groups as one cmd
@cyan quaildo i have to remove the guild_ids parameter from every cmd?
you don't have to remove it, but just know that it gets ignored
i removed it
either way works
alr
any decorator to check if an user does not have a role?
can i do @commands.has_role(role=False)
That's after the thing closes though
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
Darn
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
Hi, I would like to know how can I get the list of users who have clicked the reaction from the message
make sure guild_id is int
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
is there a way to mention subcommands?
using
bot.get_application_command('subcommand').mention
like that shortcut
currently on 2.2.2, you'd need to get the group then group.subcommands and so on to find it and mention.
on the master branch, get_application_command can get subcommands directly py bot.get_application_command("group subgroup subcommand")for example
awesome thanks a lot!
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 😔
maybe reorder self.children?
like pop the middle item and append it again
👍
yes
what?
I'd suggest you reading the guide for better understanding https://guide.pycord.dev
you use ctx inside of the button
remove ctx inside of the button and change it to interaction.response.send_message("text")
docs for the discord.Interaction.response
also, arguments in button decorated methods are positional
first is button second is interaction
you have them swapped
🤔 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! 🙏
use files instead of file
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())```
you aren't sending an interaction response
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....
If you mean a custom context with more functions its possible.
You could also add a function to your cog class where the commands group is
Here's the custom context example.
I did that, but at the moment, they are empty except for logging some stuff and doing some primitive metrics stuff with prometheus
is it possible to reset/disable timeout on interaction.edit_message?
bcs when i edit the message i wanna give it a different view
timeout=None?
timeout is reset if you interact with it
its not
it is
only if you add it
ig it depends on how poorly you code it
yeah, im a beginner, so thats probably the reason
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.
so the command just doesnt respond in time?
btw thats why am asking here, bcs i need to improve this thing
We have set up a message and an edit afterwards, but the problem is that our threads are not executing correctly.
idk
why are u using both threads and (i assume) asyncio?
btw i just fixed my issue ....
Is it safe to just delete a role while there are still Members that posess this role?
what do u expect to happen? they just vanish?
yes. yes it is safe- you will not be liable for their immediate death
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...
Do you know how to run a function in a thread and get the output?
thread is ambiguous. thread as in a thread process or a ThreadChannel?
A python thread, not discord
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.
you can simply use aiohttp for this.
there is no need to overcomplicate it
To make the call we go through a module
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
this community maintained library is asynchronous: https://github.com/OthersideAI/chronology
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?
Okay, thanks. Thats what I expected.
why is there a connect method... but there isn't a disconnect method in discord.VoiceChannel
server > integration > your bot
Server settings > integrations > your bot > edit the slash command permissions
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)
)
i want the bot to set
@wary rover
owo
You can’t have bots edit integrations that I know of.
you can but only with oauth2
which pycord doesn't have an implementation for
ok
Don't implement this, it's used to do stupid things
Nobody? 😭
If I reboot bot, can't I interaction view like buttons that sent before reboot??
Should I delete the existing one and send new view?
Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - pycord/persistent.py at master · Pycord-Development/pycord
oh wow I'll try
I don't how to using this with lavalink 
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()
add a comma behind g_id to turn it into a tuple (g_id,)
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
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
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
on_member_update does not take member
after and before are already member objects
Oh, thank you.
Is there a role selection in the Model via Select?
or something similar to choosing a role
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)```
^
get_channel returned None because it couldn't find the ID. DId you convert to int?
modals only have text input at the moment
it's just reactions
https://docs.pycord.dev/en/master/api/models.html#discord.Message.reactions
yep
idk then, either you got the wrong ID or you disabled intents so that channels aren't cached
self.bot.dbcursor.execute("INSERT INTO welcome_embeds(guild_id,channel_id) VALUES(?,?)",(ctx.guild.id,int(channel.id)))
intents=discord.Intents.all()
doesnt this cover it...
then you managed to screw up elsewhere
the snippet alone you showed looks fine to me
actually
ok, so that doesn't returns the reaction, only [], how can i count how many times for example 👍 and 👎 was reacted?
do you have message content intent
just print cha_id
tried that
doesn't fetchone return a tuple
return None
... then you found your issue
yes
oh you messed up
oh
ctx.channel.last_message_id will return your command message lol
how can i get a integer then
idk, but maybe this would be easier as a slash command?
that's not the problem, if fetchone is returning None then your query failed
i fixed that somehow
i dont even know how
so now what does it print
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'
...please tell me you know how to access items in a list
i am going to cry you access them with an index using square brackets like list[0] for the first item
oh yeah i dont have a good memory
?
uh hey
when i am storing stuff in a databse
its not appearing
but when i am printing it its there
this isn't built in, but either;
channel.historywithlimit=2- make it slash so that your command won't count as a message until after it responds
like that:
msg = await ctx.channel.fetch_message(ctx.channel.history(limit=2))```
do i have to do a for?
don't you need to commit the changes
no, see the 2nd example
please kill me oh yeah thnks
thx
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>]````
read
what
your message contains the answer
idk what you mean
ah, ik that the count is there but i don't know how to print it
list = ["STUFF", "STUFF"]
print(stuff[0]```
yes
how do you get it then
print(stuff[count])````
yes
or ctx.guild, ctx.message, self.bot
ye
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````
what's with [counter]
you can image it would be 0 or 1
it's to choose the thing in the list
ok, and what does that mean, what do i have to change
ah
but now the answer looks like this, i can't find the count in it <built-in method count of list object at 0x106cb5f00>
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....
if it's the same db then yeah have it globally
guys what the equivelent of this in pycord?
@bot.event
async def on_slash_command(inter):```
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
try
homeGuild=...
role_id = 2134532534
role = homeGuild.get_role(role_id)
is there a way to make slash commands that are owner only only show for the bots owner?
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()
so like set the command to only work in one guild and then use that for owner commands?
owner only^^
ah ok i see
on_application_command
ty
ty
ok
tell me if it prints any error
kk
bty like this?
yeh




