#Basic Pycord Help (Quick Questions Only)
1 messages · Page 33 of 1
i know
its not easy to view code on mobile yk
wait
oh 💀 yeah right
do u not use aiosqlite
sqlite3
The other code is working with sqlite3
wait
sqlite3 is not asynchronous
but not related rn
wait
r u sure price[0][0] is a str
Btw the message.mentions[0].id == 994347081294684240 returned False
price[0][0] in message.content
um
r u sure the message had proper mentions
I tried with "just a squid" to make it as an int, it gave me an error
Yes
what error
The things that returns False Are:
print(message.content.startswith(f"**💰 | {message.author.display_name}, has transferred "))
print(message.mentions[0] == 994347081294684240)
Others are True
hm
one sec
Okay
print(message.mentions[0] == 994347081294684240) this will never return true because message.mentions returns a list of abc.User objects. you are comparing to an id. You will need to get the ID from the user object.
instead of startsWith
he did .id
I did .id
@vivid plaza instead of startsWith
Yes I'm trying it
tell me if that returns True
\💰 != : moneybag:
Yup !
its the correct emoji but the content seems to return discords name. The emoji is its own Unicode character. You are trying to compare it to text with a name that does not convert to an emoji on anything except within discord
maybe try just member.name
do you know what is moneybag emoji in unicode?
?unicode 💰
nvm
No what i saying is you need to use :moneybag: not the emoji in your code for checking in the message
oh sry I didn't do print(member.name) let me do it
Everything should be fine
but wait I didn't define member?
print(message.author.name)
sure
dms link
k
i cant seem to send a message with the bot
i made the bot like 1 year ago and now i cant seem to send a message
whats wrong with this
are you getting an error message? or just nothing happens?
probably missing message_content intent
hello this might be a dumb question and a read docs question. But how to make commands.has_permissions(administrator=True) but in slash_command
and where is it in docs
@slash_command()
@commands.has_permissions()
@discord.default_permissions()
@discord.default_permissions(administrator=True) ?
default_permissions is to hide the command for user which doesn´t have the permissions
Okay thanks
and btw I put administrator=True ? or just administrator
administrator=True
okay thanks !
just nothing happens lmao
verify you have message intents enabled on your developer portal and/or that you have all intents set for your bot's intents in your code
i want to ban the member and not me "await interaction.user.ban()"
Then take a discord.Member option
Yea but its an interaction
i have it set to admin in the dev portal but have it at default in the code tho
but i do have manually enabled admin perms for the bot in the server itself
Is it not possible to decide between the interaction.author and the interaction.member in PyCord?
the author is a member object
yes i want to ban a user and i want to do it through the user command but the problem is that i have interaction.user and it wants to ban me instead of the user i have selected that means i have to use interaction.author.ban ?
interaction doesn't have an 'author' attribute. You likely want interaction.message.author
You should be passing a user parameter to your user command though, right?
@user_command(name='mycommand', description='Example command')
async def my_user_command(self, ctx, user):...
Like this
The user parameter is the user you used the command on
Yeah, so why do you need to get the user through the interaction object?
class Select(MyModal):
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.add_item(...)
async def callback(self, interaction: discord.Interaction):
...
@commands.user_command(name="Modal")
async def test(self, ctx: discord.ApplicationContext, user: discord.Member):
modal = Select(title="Review")
await ctx.send_modal(modal)```
I still don't see why you can't just use the user parameter
You can pass the user as a parameter to your Select class
how do you mean when the class is above the command
So your user command is part of your Select class? Well in that case just set self.user = user and reference that in your callback
Set self.user in your command executor. Obviously it won't work there
I would advise you to learn a bit more Python before going into Bot development. You don't seem to know how OOP works in Python well enough yet
And as per #help-rules you should at least have a basic understanding of it before asking for help here
Like said, try to learn a bit more how classes work in Python. Me telling you what to do and you guessing until you get it right won't be very progressive
why the hell is this not working...
import discord
intents = discord.Intents.default()
intents.message_content = True
intents.members = True
debug_guilds = [ 1040291339901870200 ]
bot = discord.Bot(
intents=intents,
debug_guilds=debug_guilds
)
@bot.event
async def on_ready():
print("lets gooo")
@bot.slash_command()
async def greet(ctx, user: discord.Member):
await ctx.respond(user.display_name);
its giving me this error:
also yes im running the bot
Which version of Python are you using?
PyCord only works with Python 3.11 if you use the master branch
?tag install
- 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
👌
Is it possible to create and send a text file without temporarily saving it on disk? 
Not sure, maybe using tempfiles
You could try doing this: https://stackoverflow.com/questions/60006794/send-image-from-memory
Thanks! That's interesting.
I don't get how to convert the string into a byte-like object, that I need to use for this method.
I've tried bytes() and encode() but they didn't work. Do you know another way for doing that?
Did you try
my_str = 'Hello World'
byte_object = str.encode(my_str)
can't you just do my_str.encode()?
yeah you can use io.StringIO
Thanks! That's exactly what I need. 
Use the @commands.cooldown decorator
https://docs.pycord.dev/en/stable/ext/commands/api.html?highlight=cooldown#discord.ext.commands.cooldown
@slash_command(name='example')
@commands.cooldown(1, 3, commands.BucketType.user)
async def example(self, ctx):
...
in the process of migrating from discord.py to pycord and got this error
google didnt com eup with anything
Show your pip list
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
If Discord is experiencing latency issues, is it reasonable that application commands might fail as a result?
Even with defer(), users are finding the commands failing during periods of high client latency
Yes, if Discord's API is having trouble, commands will fail
There isn't much to do about that, unless you add some error handling to detect an outage
You need to catch the commands.CommandOnCooldown error
the ctx object has an attribute for whoever used the command, which is user. From that you can access any property of the user object you want to
I'm not gonna keep giving you examples to copy, read the docs
https://docs.pycord.dev/en/stable/ext/commands/api.html?highlight=cooldown#discord.ext.commands.CommandOnCooldown
"doesnt work" is not enough, you need to explain exactly what goes wrong and the errors you are getting
does pycord have an equivalent of @bot.hybrid_command from discord.py?
yesterday they sent me that syntax and I wanted to know if it can be done somehow with choices=
Bridge.
Here's the bridge commands example.
ty
should be discord.Member
i will try
Just typehint discord.TextChannel
ty it works
does not allow classes
Code
@bot.command(name="add_user",description="Create account for the user")
async def add_user(ctx,user:discord.option(name="user",description="Select to user for adding",choices=discord.Members)):
resp = await api_sql.db_add_user(user.author.id)
if resp:
await ctx.respond("Agregado Correctoidemente")
else:
await ctx.respond("Ya existe manito usted")
spanish xddd
the rest in english
remove "choices="
discord.Option(discord.Member, ...)
async def add_user(ctx,user:discord.option(discord.Member)):
will be my version of discord py?
https://guide.pycord.dev/voice/receiving following this guide but it never specifys how i do anything with the audio ive recorded
Pycord tries to keep the recording of audio as simple and easy as possible, to keep making Discord
can you show the pip list
that is not the full list
aiodns 3.0.0
aiofiles 22.1.0
aiohttp 3.8.3
aiohttp-socks 0.7.1
aiosignal 1.2.0
altgraph 0.17.2
anyio 3.6.1
asgiref 3.5.2
async-generator 1.10
async-timeout 4.0.2
attrs 21.4.0
auto-py-to-exe 2.20.1
beautifulsoup4 4.10.0
bottle 0.12.21
bottle-websocket 0.2.9
bs4 0.0.1
certifi 2021.10.8
cffi 1.15.0
chardet 4.0.0
charset-normalizer 2.0.10
click 8.0.3
colorama 0.4.4
commonmark 0.9.1
cryptography 36.0.1
discord-webhook 0.17.0
Django 4.1.2
Eel 0.14.0
et-xmlfile 1.1.0
Flask 2.0.2
Flask-MySQLdb 0.2.0
frozenlist 1.3.1
future 0.18.2
gevent 21.12.0
gevent-websocket 0.10.1
greenlet 1.1.2
h11 0.12.0
html5lib 1.1
httpcore 0.15.0
httpx 0.23.0
idna 3.3
itsdangerous 2.0.1
Jinja2 3.0.3
loguru 0.6.0
lxml 4.7.1
MarkupSafe 2.0.1
multidict 6.0.2
mysql-connector-python 8.0.26
mysqlclient 2.1.0
numpy 1.22.1
openpyxl 3.0.9
outcome 1.1.0
pandas 1.4.0
pefile 2022.5.30
Pillow 9.0.0
pip 22.2.2
protobuf 3.18.0
py-cord 2.1.3
pycares 4.2.2
pycparser 2.21
Pygments 2.13.0
pyinstaller 5.1
pyinstaller-hooks-contrib 2022.7
PyNaCl 1.4.0
pyOpenSSL 21.0.0
pyotp 2.6.0
pyparsing 3.0.9
pytesseract 0.3.8
python-dateutil 2.8.2
python-dotenv 0.19.2
python-socks 2.0.3
pytz 2021.3
pywin32-ctypes 0.2.0
requests 2.26.0
rfc3986 1.5.0
rich 12.6.0
selenium 4.1.0
setuptools 58.0.4
six 1.16.0
sniffio 1.2.0
sortedcontainers 2.4.0
soupsieve 2.3.1
sqlparse 0.4.3
trio 0.19.0
trio-websocket 0.9.2
typing_extensions 4.3.0
tzdata 2022.5
urllib3 1.26.8
webencodings 0.5.1
Werkzeug 2.0.2
wheel 0.37.0
whichcraft 0.6.1
win32-setctime 1.1.0
wsproto 1.0.0
XlsxWriter 3.0.2
yarl 1.7.2
zope.event 4.5.0
zope.interface 5.4.0
I'd recommend using some sort of virtual environment to avoid conflicts, and a requirements.txt file to keep track of the libraries you need to install for your bot to work.
If someone has the same problem, it is solved like this
adding on to this if you dont want to manually make your own requirements.txt you can install pipreqs pip install pipreqs then use pipreqs in project directory and it will make it for you (you will have to replace discord.py with py-cord)
Anyone know why I’m getting this error? I’m can’t seem to find why..
Ignoring exception in on_connect
Traceback (most recent call last):
File "/home/container/.local/lib/python3.9/site-packages/discord/client.py", line 377, in _run_event
await coro(*args, **kwargs)
File "/home/container/.local/lib/python3.9/site-packages/discord/bot.py", line 1138, in on_connect
await self.sync_commands()
File "/home/container/.local/lib/python3.9/site-packages/discord/bot.py", line 692, in sync_commands
registered_commands = await self.register_commands(
File "/home/container/.local/lib/python3.9/site-packages/discord/bot.py", line 570, in register_commands
data = [cmd["command"].to_dict() for cmd in filtered_deleted]
File "/home/container/.local/lib/python3.9/site-packages/discord/bot.py", line 570, in <listcomp>
data = [cmd["command"].to_dict() for cmd in filtered_deleted]
File "/home/container/.local/lib/python3.9/site-packages/discord/commands/core.py", line 841, in to_dict
"options": [o.to_dict() for o in self.options],
File "/home/container/.local/lib/python3.9/site-packages/discord/commands/core.py", line 841, in <listcomp>
"options": [o.to_dict() for o in self.options],
File "/home/container/.local/lib/python3.9/site-packages/discord/commands/options.py", line 315, in to_dict
"type": self.input_type.value,
AttributeError: 'NoneType' object has no attribute 'value'
anyone?
what should I put in @Bot.command() so that only admin can use it?
@discord.default_permissions(administrator=True)
?
code?
@bot.slash_command(description = "View Aziel's current commands.")
async def help(self, ctx: discord.ApplicationContext):
if not ctx.author.id == 831118106876969021:
return await ctx.respond("This command is under maintenance.", ephemeral = True)
pages = [
discord.Embed(title = "test page 1"),
discord.Embed(title = "test page 2")
]
await ctx.respond(embeds = pages[0] if isinstance(pages[0], list) else [pages[0]], view = ButtonMenu(pages, 10, ctx.author))
I believe it’s this command since when commented out, I no longer get the error
I think it's the if and else
hmm, let me try remove it
nope, i still get the error when using:
await ctx.respond(embeds = pages[0], view = ButtonMenu(pages, 10, ctx.author))
i add it to "@bot.command(discord.default_permissions(administrator=True))?
what should that function do? If the condition is met, send another embed?
yes since i can pass another list of embeds inside my pages list, if there is a list of embeds in my pages list, I want to respond with all embeds
sure but there you are matching the embed to "pages[0]" and the condition is on air
you should put the condition before or a function that does it in that case you could use "embed = def selec_embed"
Oh, wait, are you doing slash commands or message commands?
Mine was for slash commands
wdym by put the condition before?
@bot.command(name="balance",description="Show the balance in your account")
@has_permissions(administrator=True)
async def balance(ctx):
```I use "/" I managed to do it so do you think it can be trimmed?
although i don’t believe it’s the if condition causing the error, I just tried embed = pages[0] yet I still get the same error
This looks fine, IIRC from message commands
I haven’t touched them in a year, though
xd
is that you are sending conditions not a format
try this
embed = discord.Embed(color=0x32CD32)
if condition:
embed.title("test page 1")
else :
embed.title("test page 2")
await ctx.respond(embed = embed)
and try taking out that "s" Maybe it has something to do with it, I wouldn't know how to tell you
there is no if in this case…
and I’m using buttons to swap through embeds
so there is no 1 embed
Which is why I had a pages list
which was a list of embeds
oh if it's buttons I couldn't help you yet I haven't gotten to that part :S
ah no worries, hopefully someone else knows :)
@woeful spindle why don't you use the built in paginator
Here's the modal dialogs example.
this if for me i couldnt find it
@discord.ui.button(
label="Make a feedback",
style=discord.ButtonStyle.primary,
custom_id="nftgoio:feedback:make",
)
async def make_feedback(self, button: discord.ui.Button, interaction: discord.Interaction):
await interaction.response.defer(ephemeral=True, invisible=False)
followup = interaction.followup
select_bord_view = SelectBoardView(boards=(await canny.client.list_boards()))
msg = await followup.send(
content="Please select a board and a category",
view=select_bord_view,
)
await select_bord_view.wait()
select_cate_view = SelectCategoryView(
categories=(await canny.client.list_categories(select_bord_view.select.values[0]))
)
msg = await msg.edit(
content="Please select a category",
view=select_cate_view
)
await select_cate_view.wait()
modal = FeedbackModal(title="Submit a feedback")
await msg.send_modal(modal)
await modal.wait()
print("board", select_bord_view.select.values[0])
print("category", select_cate_view.select.values[0])
print("author_mail", modal.children[0].value)
print("title", modal.children[1].value)
print("detail", modal.children[2].value)
# edit followup: pop category select
await msg.send_modal(modal)
AttributeError: 'WebhookMessage' object has no attribute 'send_modal
How can I send modal after two view . I tried to use followup, but it seems not work
You must send the modal at first response
Consider subclassing views and using callbacks
thank you. Actually before filling up the modal the user should make 2 selections
I have no idea how to do that, may I have an example ( Pseudo code ) to show the right thing
I am stuck 
Here's the confirm example.
@discord.ui.button(label="Confirm", style=discord.ButtonStyle.green)
async def confirm_callback(
self, button: discord.ui.Button, interaction: discord.Interaction
):
# Don't send anything
# await interaction.response.send_message("Confirming", ephemeral=True)
self.value = True
self.stop()
I noticed If comment out interaction.response.send_message, discord tips me interaction failed
Can I not response any message?
you have to respond
@worldly tendon howssss that game
but you can delete the message after if you wish (delete_after kwarg also works)
got thank you
thank you too
Use edit_original_response
not work
In what way did it "not work"
good question, I’ll try it after school
@copper yew uh sorry for ping but you made BridgeCommandGroup right? if so is it possible to create it in a cog? trying to do so and struggling. I have seen the example
how do I get all the commands of my bot, divide them via cogs and have paginator for them?
an idea is enough for me
the issue is i have groups
just iterate
bot.cogs is a list of cog objects
Cog.walk_commands() goes through every command, group and subcommand in said cog
yes
and i can do group.walk_commands() right?
ty
well Cog.walk_commands already includes subcommands from groups
well it would be awkward to see in the help embed enable when the cmd is /danger lockdown enable
which is why you can do command.qualified_name to get its full name
oh
oki
ty
also slight correction, bot.cogs is a dict mapping of cog_name: cog_object
ok
dumb question, how would you iterate through them if it is a map of cog_name: cog_object?
you can iterate through dicts in several ways
if you just want the object, you can use dict.values()
for the key, you can iterate just through dict
and if you want both, you use two variables to go through dict.items() py for name, cog in bot.cogs.items():
ok my question was really dumb
thanks lol
also, cant we access the slash command desc? as it returns a ApplicationCommand it only has 3 attributes
SlashCommand inherits from ApplicationCommand so command.description will work
because message and user commands don't have descriptions
im having trouble with Paginatir
paginator*
I want 10 commands to be shown on an embed at once
and I have a dropdown to pick Which cog's commands to view
I have trouble embedding this into Paginator
ic, vsc yells at me about it
how to add my no of servers in myactivity
len(bot.guilds)
in discord.Activity
why? any error? show your updated code. saying "not work" doesnt help with anything
not working
anybody
in dm
As you guys can see the netflix value went to spotify and the minecraft value went to netflix, Really weird
yes
bot.guilds returns a list. Figure out the rest and make an attempt. We don't spoonfeed here.
anyone can help ?
is it better to do it like this or with an if in ctx.author.role.id ?
I consult because I see that it does not send a message when I do not have the permission
https://pypi.org/project/pycord-ext-ipc/
is this still possible to use?
I can't get him to grab it
Why not?...
how do i edit the message a button is on with interaction?
You can fetch the message from an interaction with the original_response
https://docs.pycord.dev/en/stable/api.html#discord.Interaction.original_response
Not quite, original_response is the response to the message and not the message itself
Id just recommend using interaction.response.edit_message
so I’d use something like this?
msg = await interaction.original_response()
await msg.edit(..)
I’ll try this
Well like Nelo said, that would edit the message from the button's interaction response. If you're looking to edit the message itself then yeah, do that
Could you show the full code?
sure I’ll be on my pc in about 10-15 mins so I can send it then if that’s fine
Ah, your parameters for the buttons are in the wrong order, it's supposed to be self, button, interaction
it seems to be working now, tysm! :)
although, my timeout for the buttons doesn’t seem to be working, the buttons don’t get removed after my set timeout and instead when using the buttons after my set timeout, I get a "interaction didnt respond" error on discord with no error on my console
Anyone know how I can add set options for a parameter for a slash command, but also have a default value that isn't one of the choices?
?
hey so i want to get a list of all the members who has permission to view channel so i can have somthing like users in ticket field
is that possible
without manually storing each one using for loop or somthing
is it this? im kinda confused what this does
Could pass me the API section to do something similar to this? pls 🥺
only the interactive box not the giveaways xd
Here's the modal dialogs example.
is there a way i can make a specific user of the bot see and use slash commands (without changing integrated properties on discord)
you mean that out of 100 users only 1 can use it?
is there a tutorial or some examples somewhere about unpack_audio?
i can only find one reference in the docs
well, you iterate through role members and send a message?
.doclink discord.Role.members
import discord
bot = discord.Bot()
@bot.slash_command()
async def help(ctx, name: str = None):
name = name or ctx.author.name
await ctx.respond(f"Coming soon!")
@bot.user_command(name="Say Hello")
async def hi(ctx, user):
await ctx.respond(f"{ctx.author.mention} says hello to {user.name}!")
bot.run(```
how to know if my comand is global or not (help command)
out of all users, only one (the bot owner) can see and use it
I found this way to even send a "you can't use this command" message
if 'id' == str(ctx.author.id):
ctx.respond("You are authorized")
else:
ctx.respond("You not are authorized")
so that they don't see it you will have to do a command with prefix "." or other than "/"
yes but the slash command still shows
you can’t make it not show without changing the integrated permissions on discord afaik
interesting, so what would be the best method to load and unload cogs
it is global if you don't specify any guilds in it
your (help) should be global
Ohh yay
How can I do so that if I choose an option, another 2 appear?
slash command
bot.reload_extension?
i try this but no lol
just have 3 options
What do you recommend to have the same command with different functions?
or do I do them separately?
nono, i mean as a slash command without others seeing it
You cannot have an option inside of a option
that's not possible.
oh :c
make it a guild-specific command and it should be your testing guild.
will have to be done separately then, thanks <33
Can entry be restricted? make the options only enter numbers or characters?
yes
Here's the slash options example.
ah thats ideal, thank you#
i love u, it worked :D
stay in one channel pls
does anyone know how to do this?
i don't think there is such thing as $ in CMD bash
at least not in that way of usage
||also it's py-cord, not disocrd.py server||
you should just use pip install without $
thanks now i try it
Hello! I am trying to get a referenced message from a slash command. However, when I use ctx.message, its value is None. But I need to somehow get the command's .reference attribute. Im honestly not sure if thats even a thing you can do, but I thought I'd ask!
And by reference, I mean a reply - like this
literally
What message reference exactly? From another X message?
like, replying to a message with a command
but now that i think about it i dont think you can really do that
discord kind of gives the illusion of that happening but you arent really replying
Basically what I want to do is reply to a message with /convert and it will convert the attachments of that message to a different format
thats what I figured, thank you!
Earlier answers
@commands.has_permissions(
administrator=True,
) how do i make it respond you dont have permission to use this instaed of just hrowing error
Then ask here and don't create a thread
You handle the error
I got a non-helpful answer
Last time I made a threat and no one helped me
Am I supposed to wait until idk what happens
so helpfull
adding try except every time seems inneficant
What
There's something called error handlers
You can't try except a decorator
At least try to investigate before being sarcastic on someone's anwer
it was seperate comments
Your response was still sarcastic.
because your response was helpless
Follow up questions exist.
I was looking for the example.
All about handling errors.
thank you
Are these values proper to the class?
If you have two children on your view, then yes
or perfect, is that in the class there is no children and I did not know xD
what
what happened ?
Notice children does not appear as a variable xd
I'm sorry, I don't understand you
what was client. renamed too
it wasn't renamed
so why is it not being registered
i lost my old codebase so im back like 200 days old
Hard to say without seeing any error messages or your code
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NameError: name 'client' is not defined
import discord
import json
import requests
from discord.ext import commands
class Toontown(commands.Cog):
"""Cog for Toontown commands"""
def __init__(self, bot):
self.bot = bot
#TTR Districts Command
@commands.command(pass_context=True, aliases=["ttr_districts", "ttr"])
async def ttrdistricts(self, ctx):
ttr_districts_api = "https://www.toontownrewritten.com/api/population"
ttr_districts_response = requests.get(ttr_districts_api, verify=True)
ttr_districts_json = ttr_districts_response.json()
ttr_districts = ttr_districts_json["populationByDistrict"]
ttr_districts = json.dumps(ttr_districts, sort_keys=True, indent=2)
ttr_districts = ttr_districts.replace('"', '')
ttr_districts = ttr_districts.replace(',', '')
ttr_districts = str(ttr_districts)[1:-2]
embed = discord.Embed(
title=f'Toontown Rewritten Population',
description='\uFEFF',
colour=0x98FB98,
timestamp=ctx.message.created_at)
embed.set_thumbnail(url="https://i.ibb.co/RzrzDVh/TTR.png")
embed.add_field(name="Population:", value=ttr_districts, inline=True)
embed.set_footer(text=f"Ran by: {ctx.message.author} • Yours truly, {client.user.name}")
embed.set_author(name=client.user.name, icon_url=client.user.avatar.url)
await ctx.send(content=None, embed=embed)
def setup(bot):
bot.add_cog(Toontown(bot))
You haven't defined a variable called client anywhere in that code
It's also not recommended to use the requests library for Discord bots as it's not async and will block code execution while the request is pending. But that's another issue
I am trying to make a class having all the mod commands in my bot. I have a variable called config containing most of my config for the bot. but using commands.has_role() it says self is not defined.
class ModCommands(commands.Cog):
def __init__(self, bot, config):
self.bot = bot
self.config = config
@commands.command()
@commands.has_role(self.config.get('modrole'))
async def ping(self, ctx):
await ctx.send('Pong!')
And here is the traceback
File "d:/PythonProjects/aspect bot/main.py", line 4, in <module>
from mod import ModCommands
File "d:\PythonProjects\aspect bot\mod.py", line 4, in <module>
class ModCommands(commands.Cog):
File "d:\PythonProjects\aspect bot\mod.py", line 10, in ModCommands
@commands.has_role(self.config.get('modrole'))
NameError: name 'self' is not defined
Any help?
self is only accessible inside of methods that have it as a parameter, so it doesn't exist in your decorator
Any help on how I can access the variable?
The best way would be to write your own check inside of the command. alternatively try to do something with global variables but I'm not sure if that would work
Okay ig. Lets see if it works
You could always just write your own has_role method and use that inside of your commands. Would probably be the neatest option
Or i think I can configure this in the integrations section of the server itself
Up to you
@limber urchin
I checked the Integrations section, / commands did not show up any explanation to why it might have happened?
Are the commands registered in the guild?
Well can you use the command in a chat?
I can't find them, how do I register it?
You can specify a list of guild IDs as the debug_guilds parameter when you create your Bot object. That way commands will automatically register directly in those guilds. If you don't, your commands will be global but it takes some time for them to sync
I'm not sure what you're asking, why would you need to call that inside of a cog?
you should only create a bot instance once, preferrably in your main file
config = Config()
debug = config.get('debug')
print(f'Debug mode is {debug}')
bot = discord.Bot(command_prefix=config.get('prefix'), debug_guilds= debug)
@bot.event
async def on_ready():
print('Bot is ready.')
bot.add_cog(ModCommands(bot, config))
bot.run(config.get('token'))
is this the correct way to add debug guilds? Also why is add_cog() giving an error?
File "D:\PythonProjects\aspect bot\env\lib\site-packages\discord\cog.py", line 544, in _inject
bot.add_command(command)
AttributeError: 'Bot' object has no attribute 'add_command'
because i need to call discord.user
i thought i have to prefix that with bot
if debug is an instance of a list, yes
Each cog should have an reference to your Bot object as a parameter in it's init function
this is all i have
def __init__(self, bot):
self.bot = bot```
Yeah? So why can't you use self.bot?
i just figured i couldnt let me test that
huh?
i lost like 2 months worth of work
I don't get how that would prevent you from using self.bot
@limber urchin Why is bot.add_cog() returing an error.
Traceback (most recent call last):
File "d:/PythonProjects/aspect bot/main.py", line 16, in <module>
bot.add_cog(ModCommands(bot, config))
File "D:\PythonProjects\aspect bot\env\lib\site-packages\discord\cog.py", line 639, in add_cog
cog = cog._inject(self)
File "D:\PythonProjects\aspect bot\env\lib\site-packages\discord\cog.py", line 550, in _inject
raise e
File "D:\PythonProjects\aspect bot\env\lib\site-packages\discord\cog.py", line 544, in _inject
bot.add_command(command)
AttributeError: 'Bot' object has no attribute 'add_command'
What version of pycord are you using?
2.2.2
Are you sure there are no conflicting packages? Like discord.py
nope, using a venv
Hm, not sure then
Hi guys, I currently try to log all slash command uses by using on_interaction. That also works pretty well, I just have one question: Is there a special attribute/function or so, which gives me the full command string?
So a attribute that gives me something like /group subcommand option1: value1 option 2: value2? That would make my life much easier...
To log slash commands, on_application_command https://docs.pycord.dev/en/stable/api.html#discord.on_application_command is probably better. It also gives you the application context of the command so you could fetch information from that
more actual question now:
server.icon_url_as what is called nmow
.docs discord.Guild.icon
That helps me, thanks a lot for your tip 👍
It’s None if there isn’t an icon.
is icon_url still a thing
No
is there an alternative to it
Read the docs
!help cogs
No command called "cogs" found.
!help
Don't use this channel to spam commands
go to #app-commands or #883236900171816970
How do I add cog?
config = Config()
debug = config.get('debug')
print(type(debug))
bot = discord.Bot(command_prefix=config.get('prefix'), debug_guilds= debug)
@bot.event
async def on_ready():
print('Bot is ready.')
bot.add_cog(ModCommands(bot, config))
bot.run(config.get('token'))
class ModCommands(commands.Cog):
def __init__(self, bot, config):
self.bot = bot
self.config = config
@commands.command()
async def ping(self, ctx):
await ctx.send('Pong!')
This is right? but discord.Bot() is having issues adding cog, switching to commands.Bot() makes it work, why is it happening?
discord.Bot() shows this error
Traceback (most recent call last):
File "d:/PythonProjects/aspect bot/main.py", line 16, in <module>
bot.add_cog(ModCommands(bot, config))
File "D:\PythonProjects\aspect bot\env\lib\site-packages\discord\cog.py", line 639, in add_cog
cog = cog._inject(self)
File "D:\PythonProjects\aspect bot\env\lib\site-packages\discord\cog.py", line 550, in _inject
raise e
File "D:\PythonProjects\aspect bot\env\lib\site-packages\discord\cog.py", line 544, in _inject
bot.add_command(command)
AttributeError: 'Bot' object has no attribute 'add_command'
py-cord == 2.2.2
Because discord.Bot is a different class than commands.Bot
So can I not add cogs in discord.bot ?
No
sorry my bad
How do get channel by id?
it's edit_original_response, not edit.
'https://github.com/Pycord-Development/pycord/blob/master/examples/views/button_roles.py'
This helps me to make embeds that change when you touch a button?
It's an example for how to create buttons that grants a user a role when clicking on them
something similar to this but with "back" "stop" "next" buttons is possible?
yes
do you have any example? 🥺
Create a view, store a reference to the embed you want to change in the view, on the button callbacks, edit the embed to your liking
something like
async def button_callback():
page -=1
await interaction.response.send_modal(modal)
my example is horrible :'c xdxd
I better make it real and see haha
I'll be back in a few hours xd
Try on your own and come back if you run into any specific issues, we can't provide help with an entire feature
yep i will do that
thanks <3 
Sorry if the things I say are misunderstood, my English is bad xd
app commands not appearing without debug_guild list, do we must to use list for every guild?
No
The debug_guilds is to instantly register your commands to a specific set of guilds. Omitting the parameter will make your commands global but it can take up to an hour for the commands to register
like every time after code change?
how do I sync a channel
Yes
thanks
But you shouldn't be registering your commands as global while you're developing anyways
Just remove the param when you're done with your changes and ready to release them
got it
how do I add cooldown for interaction?
(buttons)
You need to implement it yourself
class TicketCreateView(discord.ui.View):
def __init__(self, bot):
super().__init__(timeout=None)
self.bot = bot
cd_mapping = commands.CooldownMapping.from_cooldown(1, 120, commands.BucketType.member)
@discord.ui.button(
label="Open Ticket",
style=discord.ButtonStyle.blurple,
custom_id="create_ticket:blurple",
)
async def create_ticket(self, button: discord.ui.Button, interaction: discord.Interaction):
view: TicketCreateView = self.view
bucket = view.cd_mapping.get_bucket(interaction.message)
retry_after = bucket.update_rate_limit()
if retry_after:
return await interaction.response.send_message("Sorry you are on cooldown, cooldown: 120s")
``` should work right?
Try it and see 
Ive still got alot of coding to do to implement this button
thats why I asked
or i wouldve tried it
I've tried installing the latest version of pycord, and im getting this error preventing it from finishing the installation.
ERROR: Failed building wheel for yarl
Failed to build multidict yarl
ERROR: Could not build wheels for multidict, yarl, which is required to install pyproject.toml-based projects
Upgrade pip with python3 -m pip install --upgrade pip
how do i register Slashcommands in Discord with Pycord?
They will automatically be registered globally unless you define debug_guilds in your bot instance's init function
(.venv) PS C:\Users\Wacky\Documents\FoolishBot> py -3 -m pip install --upgrade pip
Requirement already satisfied: pip in c:\users\wacky\appdata\local\programs\python\python311\lib\site-packages (22.3.1)
i started a JS handler who registerd for me a /ping command, the command worked and was registerd, after i started my PY bot again, the Ping command was deleted and no new one was registerd... and i dont use debug_guilds
You don't need a 3rd party handler to register commands
Global commands can take up to an hour to register
?
building 'yarl._quoting_c' extension
error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/
[end of output]
note: This error originates from a subprocess, and is likely not a problem with pip.
ERROR: Failed building wheel for yarl
Failed to build multidict yarl
ERROR: Could not build wheels for multidict, yarl, which is required to install pyproject.toml-based projects
I installed it though
uhm, with the handler written in JS it was instant registerd
but i will wait an hour and see
@limber urchin
Did you try doing what the error message tells you to do?
yes
^
Would anyone know how to edit a ephemeral message? This piece of code works on non-ephemeral messages but returns a "400 - Invalid Form Body" otherwise
That's correct
So you've messed up something with your View
why it says this
File "f:\fun\Desktop\coding practice\python practice\bot_pycord\main.py", line 2, in <module> from discord.ext import commands File "C:\Users\fun\AppData\Roaming\Python\Python311\site-packages\discord\ext\commands\__init__.py", line 18, in <module> from .flags import * File "C:\Users\fun\AppData\Roaming\Python\Python311\site-packages\discord\ext\commands\flags.py", line 57, in <module> @dataclass ^^^^^^^^^ File "C:\Program Files\Python311\Lib\dataclasses.py", line 1221, in dataclass return wrap(cls) ^^^^^^^^^ File "C:\Program Files\Python311\Lib\dataclasses.py", line 1211, in wrap return _process_class(cls, init, repr, eq, order, unsafe_hash, ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Program Files\Python311\Lib\dataclasses.py", line 959, in _process_class cls_fields.append(_get_field(cls, name, type, kw_only)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Program Files\Python311\Lib\dataclasses.py", line 816, in _get_field raise ValueError(f'mutable default {type(f.default)} for field ' ValueError: mutable default <class 'discord.utils._MissingSentinel'> for field name is not allowed: use default_factory
Huh, alright, I'll triple check thanks
If you're using Python 3.11 you need to use the master branch from git
um so i should downgrade my python
Either that, or install an unstable version of pycord
what is the difference between unstable and stable
The unstable version may have bugs in it as it isn't fully released and tested yet
how can i do that
.tag install
pip install py-cord
- 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
(Or just don't use 3.11
)
^^
You can read the changelog on github, but I don't believe there should be any major changes
ok
Can Anyone Help Here 🙂
My guess it you are turning an old bot with message commands into a bot with application commands?
THis should help
?tag forbidden
You get a 403 Forbidden (error code: 50001): Missing Access as error?
You might've added your bot in the past without the applications.commands scope.
What to do?
Old way: Re-add the bot with the applications.commands scope.
New way: Since 11/07/2022 discord automatically includes the applications.commands scope in OAuth. You just need to re-add the bot with the bot scope. See [#discord-api-updates@996103073111998544](#discord-api-updates message) for more infos.
Basically just re-invite the bot
Ok so,
I'm trying to make my bot delete logs older than 3 days listed in my # log channel.
I already got far enough to create the log functions itself
# Edit log
@commands.Cog.listener()
async def on_message_edit(self, message_before, message_after):
member = message_after.author.mention
the_channel = message_after.channel.mention
channel = client.get_channel(log)
channel_id = message_after.channel.id
if channel_id == log:
return channel_id == log
else:
pass
em = discord.Embed(title="Message edited!", description = f"{member} has edited a message in {the_channel}.", color = em_yellow)
em.add_field(name = "**Message before:**", value = message_before.content)
em.add_field(name = "**Message after:**", value = message_after.content)
await channel.send(embed = em)
and
# Purge log
@commands.Cog.listener()
async def on_message_delete(self, message):
member = message.author.mention
the_channel = message.channel.mention
channel = client.get_channel(log)
channel_id = message.channel.id # Built this stuff in here due to cog listeners (checkers), do not support ctx.
if channel_id == log:
return channel_id == log
else:
pass
em = discord.Embed(title = "Message deleted!", description = f"{member} has deleted a message in {the_channel}.", color = em_red)
em.add_field(name = "**Message:**", value = message.content)
await channel.send(embed = em)
But now I want my bot to automatically delete logs older than 3 days which it sent itself in # log
I was thinking of using message.created_at somehow but I have no idea how.
Tasks?
It just has to delete any message older than 3 days in my log channel, yes I know the limit of deleting messages is 14 days but if theres no message older than 14 days in the channel it should be fine.
did but same issue
the bot even has all intents and admin perms
Here's the background task example.
You can set up a task that checks the messages every 12-hours or so and deletes any messages older than 3 days
And you are sure that the screen looked like this on the dev portal?
yep
same as this
both bot and application.commands ticked
Are you on the latest pycord version?
Also I assume you copied the URL at the bottom of the page In the image above and not somewhere else.
join is an int not a list
anyone know: is it possible to edit an ephemeral view when it times out?
It is possible, make sure to have proper error handling if the message does not exist anymore.
It should work the same way as editing a non ephemeral view on timeout
self.message is NoneType when it's ephemeral though! how can i get the message object?
my timeout code, super simple
how long is the timeout
i've got it at 30s for testing
The message that this view is attached to. If None then the view has not been sent with a message.
From the docs i think you need something else. Give me one second
maybe i need to pass the message/interaction to the view as a separate object? 
You need to import it from somewhere chief
Could you try sending a message along with the view and see if that changes anything?
Full path is discord.ext.commands
thanks
no dice! i am using ctx.followup.send() to send the initial message, maybe that's my prob
self.client.get_channel()
message = ctx.followup.send() and than passing it to wherever you need it would be the best bet than.
message.edit()
still same error
is there a way to still use prefix commands as well as slash commands?
I cannot use the slash command again here...
yes
wait
I was faster ;3
from discord.ext import bridge
bot = bridge.Bot(intents = intents, prefix = !)
you can still use the slash command decorator and prefix commands in your bot
anyway this is still an issue
do you have something else installed?
no... it seems like the parameters within the decorator are false..
YESSSS thank you
because this works
passing the original_message to the view and that works like a charm! ❤️
I did yes
You always have to try a few things with ephemeral because they act weird on discords side
so glad i got this figured out 😍 my game's UX increased by 100% now
thank you very much!
error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/
[end of output]
note: This error originates from a subprocess, and is likely not a problem with pip.
ERROR: Failed building wheel for yarl
Failed to build multidict yarl
ERROR: Could not build wheels for multidict, yarl, which is required to install pyproject.toml-based projects
I cant install pycord, i have installed C++ 14.0
you're trying to install a module with c components without a c compiler i guess
Map to str
Hey! Does anyone know how I could access the guild id in cogs/init.py?
Thanks!
for what?
I have some models :
class GuildConfig(Model):
id = fields.BigIntField(pk=True, unique=True, nullable=False)
prefix = fields.TextField(default="$")
mod_enabled = fields.BooleanField(default=False)```
And in the __init__.py I would like to load the specified cog if it's enabled
I fixed it, but now i cant start the bot
ValueError: mutable default <class 'discord.utils._MissingSentinel'> for field name is not allowed: use default_factory
could you send the whole traceback
yeah sure sorry
Traceback (most recent call last):
File "C:\Users\Wacky\Documents\FoolishBot\main.py", line 6, in <module>
from discord.ext import commands
File "C:\Users\Wacky\Documents\FoolishBot.venv\Lib\site-packages\discord\ext\commands_init_.py", line 18, in <module>
from .flags import *
File "C:\Users\Wacky\Documents\FoolishBot.venv\Lib\site-packages\discord\ext\commands\flags.py", line 71, in <module>
@dataclass
^^^^^^^^^
File "C:\Users\Wacky\AppData\Local\Programs\Python\Python311\Lib\dataclasses.py", line 1221, in dataclass
return wrap(cls)
^^^^^^^^^
File "C:\Users\Wacky\AppData\Local\Programs\Python\Python311\Lib\dataclasses.py", line 1211, in wrap
return _process_class(cls, init, repr, eq, order, unsafe_hash,
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Wacky\AppData\Local\Programs\Python\Python311\Lib\dataclasses.py", line 959, in _process_class
cls_fields.append(_get_field(cls, name, type, kw_only))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Wacky\AppData\Local\Programs\Python\Python311\Lib\dataclasses.py", line 816, in _get_field
raise ValueError(f'mutable default {type(f.default)} for field '
ValueError: mutable default <class 'discord.utils._MissingSentinel'> for field name is not allowed: use default_factory
What's your python version
11
I installed it on python.org, not github & used pip install py-cord==2.0.0rc1
That version is old as hell
Oh lol
- 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
alr will do
Fixed now, I've took a big break from coding so im rusty haha
why isnt bot.run(os.getenv(TOKEN)) working?
the file .env is made & its got TOKEN = TOKEN
Obviously TOKEN is the token
how would i go about adding a user cooldown to a interactive button?
"TOKEN" not TOKEN
You have to do it yourself
could u point me in the right direction please?
i looked into this one, however, it i found it didn't actually work
and the commands.CooldownMapping doesnt exist on the api docs
please use an actual IDE.
I think he's using pterodactyl
thanks
you really should start to use cogs...
Am I understanding the checks argument from SlashCommand right that I can pass any function into it and it will only allow the command to execute if the check function returns the equivalent of bool True?
6000 lines 💀
tiny bump ^
does a bridgeCommand works with checks too?
yes
I have this custom check but my command is still executing.. anyone know why?
Traceback (most recent call last): File "F:\fun\Desktop\coding practice\python practice\bot_pycord\main.py", line 10, in <module> bot.intents = discord.Intents.all() ^^^^^^^^^^^ AttributeError: property 'intents' of 'Bot' object has no setter
why?
intents should be passed in when the bot object is created.
?
trying to check the link in my bridgecommand if it´s a tiktokurl
async def checkURL(self, ctx):
print("in function")
linkPrefixes = ['https://m.tiktok.com', 'https://vt.tiktok.com', 'https://tiktok.com',
'https://www.tiktok.com', 'https://vm.tiktok.com/']
for link in linkPrefixes:
if link in ctx:
print("True")
return True
return False
@bridge.bridge_command(description="xxx", checks=checkURL)
async def tikload(self, ctx, link):
if link is not None:
if isinstance(ctx, commands.Context):
await ctx.message.delete()
await ctx.send("xxx", delete_after=5)
.....
but i get TypeError: 'function' object is not iterable
full traceback thanks
Ignoring exception in on_interaction
Traceback (most recent call last):
File "C:\Users\xxx\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 377, in _run_event
await coro(*args, **kwargs)
File "C:\Users\xxx\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 1141, in on_interaction
await self.process_application_commands(interaction)
File "C:\Users\xxx\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 822, in process_application_commands
await self.invoke_application_command(ctx)
File "C:\Users\xxx\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 1088, in invoke_application_command
await ctx.command.invoke(ctx)
File "C:\Users\xxx\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 371, in invoke
await self.prepare(ctx)
File "C:\Users\xxx\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 291, in prepare
if not await self.can_run(ctx):
File "C:\Users\xxx\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 400, in can_run
return await async_all(predicate(ctx) for predicate in predicates) # type: ignore
TypeError: 'function' object is not iterable
I don't think that's the full traceback
it is
I don't see where checkURL is used.
but I want a custom check so I can return my custom error without having to handle the CheckFailure error
could you provide more code?
like how the decorator is used.
pip list in terminal and show output thanks.
also you shouldn't return an await ctx.respond since it returns an interaction, which is true.
yeah
?tag not pycord
No tag not found.
I'm trying to make a bridged bot
?tag notpycord
The library name is py-cord not pycord
so it has both slash and prefixed at the same time
mhm
sigh
oh wait I thought there was like 3 times more
well here it is
Here's the slash cog example.
uninstall discord.py and py-cord and reinstall py-cord
allegedly
well uh thanks
yeahhh well now it says a different error
restarted vsc?
huh. try reinstalling py-cord?
after saving the user OAuth2 token for a user after allowing me to use guilds.join how can i make the user join back to the guild?
I literally just did
ehh, maybe I'll try Sublime Text
also vscode just crashed for me
wow.
closed itself
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
hey guys why is it not working?
.tag idw
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.
you do realize that localization exists?
@bot.slash_command(description = "Use Aziel's Help Panel!")
@checks.mod_only()
async def help(ctx: discord.ApplicationContext):
emb = discord.Embed(colour = 0x2f3136)
# and all the other unimportant stuff
Asking about your attempted solution rather than your actual problem
but the options
#998272089343668364 message
and it shows the same error
strange.
and discord still imports somehow
what should I do instead then?
OHHHH I'm dumb
you can run await ctx.respond and return False seperately
alright so noone knows.
?tag notpycord
The library name is py-cord not pycord
pycord = ffmpeg wrapper thing
py-cord = python discord api wrapper
Will slash commands take a bit to appear? I made a slash command and it isnt showing
yeah
global slash commands take up to an hour
restarting/updating your discord client should work.
tried that
Alright thanks (It is a global, so makes sense)
not after slate v2
oh
my command have an error `Ignoring exception in command privchannel:
Traceback (most recent call last):
File "C:\Users\fun\AppData\Roaming\Python\Python311\site-packages\discord\ext\commands\core.py", line 178, in wrapped
ret = await coro(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "F:\fun\Desktop\coding practice\python practice\bot_pycord\main.py", line 15, in privchannel
id2:str = ctx.args[1]
~~~~~~~~^^^
IndexError: list index out of range
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\fun\AppData\Roaming\Python\Python311\site-packages\discord\ext\commands\bot.py", line 347, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\fun\AppData\Roaming\Python\Python311\site-packages\discord\ext\commands\core.py", line 950, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\fun\AppData\Roaming\Python\Python311\site-packages\discord\ext\commands\core.py", line 187, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: IndexError: list index out of range`
code:https://paste.pythondiscord.com/qalagaxopu
pretty sure the global 1 hour wait was removed a while back yeah
why
so what could it be?
IndexError: list index out of range
please make a separate thread 👍
ok
I restarted my discord client & made sure its reading all of the code
is it in a cog?
are you running two or more instances of your bot?
Im not
Yeah and its been loaded
are you loading cogs in on_ready
def mod_only():
async def predicate(ctx):
if not ctx.author.guild_permissions.manage_messages:
await ctx.respond("You aren’t a moderator!", ephemeral = True)
return False
return True
return commands.check(predicate)
like this?
sure
import os
from dotenv import load_dotenv
load_dotenv()
from discord.ext import commands
bot = commands.Bot(intents = discord.Intents.all(),command_prefix='!', activity = discord.Activity(type=discord.ActivityType.playing, name="BennixMC"))
@bot.event
async def on_ready():
print('I am online')
@bot.event
async def on_application_command_error(ctx, error):
if isinstance(error, commands.CommandOnCooldown):
await ctx.respond(f'This command is on cooldown, Try again in {round(error.retry_after)} seconds')
directories = ["Fun commands", "./Utility Commands","./Embeds"]
for directory in directories:
for filename in os.listdir(directory):
if filename.endswith(".py"):
bot.load_extension(f"{directory[2:]}.{filename[:-3]}")
bot.run(os.getenv("TOKEN"))``` (If this code is slightly outdated, then is because its old code haha)
^ no im not loading it in on ready
hi there uh
seems fine i guess
so I'm making a bridged bot
what does the cog look like
import discord
from discord.ext import commands
class Server(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.slash_command(name="serverinfo")
async def serverinfo(self, ctx):
await ctx.respond("Server Info..")
def setup(bot):
bot.add_cog(Server(bot))
well
show ur code
as in if I use a prefixed command (prefix being t?) it doesn't work
but it works with the slash command
your command isn't actually in the cog
ill help if i can but am rusty
intents = discord.Intents()
intents.message_content = True
bot = bridge.Bot(command_prefix="t?", intents=intents)
print("BOT INITIALIZING...")
@bot.event
async def on_ready():
print("BOT ONLINE")
@bot.bridge_command()
async def sum(ctx, a: int, b: int):
print('someone used sum command ooo')
await ctx.respond(a + b)
bot.run(_token)
should it be inline w the function
the def
you also need message intent
oh
you should do Intents.default() instead of just Intents()
Appreciated it works now, will get to actualy doing this
at least it didn't say 69
yeah LOL
nah if they're integers, it does actual math
if I saved the arguments as strings however it would respond with 69
well guess what I made
woo
with the current snippet, it is hard to see what you are doing. Please share more code.
hey chat
because I'm lazy, and it's like 11pm
how do I check if a user has admin perms
I thought it was discord.User
If you read the docs you’d know.
it is discord.User outside of guilds, but discord.Member in guilds.
ok but which one of these is the admin attribute 😭
.
excluding methods
.
.guild_permissions
.docs discord.Permissions.administrator
Well what are you trying to do
async def say(ctx,
msg: Option(str, 'The thing you want the bot to say',
required=True, default=None),
hidden: discord.Option(str, 'Do you wanna keep it secret?', choices=['True', 'False'], required = False, default='True')
):
if not hidden:
await ctx.respond(f'{msg}')
else:
await ctx.send(f'{msg}')
Can you have "wild cards" in URL links
ctx.author can return a member or a user depending on the context
You can’t expect us to spoon feed you when it’s not that far into the docs.
yeah sorry if I'm getting on your nerves
it's always ctx.respond with bridge commands
I don't understand
I want an embed to fetch a daily picture, which the day number changes.
e.g. https:// mywebsite.com/photos/122/1.jpg
So the 122 needs to read as anything
so you are fetching an image but you don't know part of the url?
Just the day number changes
Every day +1
ok so what's the issue?
Then why are you comparing an ID with a Member object
why isnt
Server = discord.Embed(title="Server Statistics", description=f"Server Owner: {ctx.guild.owner}\n Server Name: {ctx.guild.name}\nMember Count: {mem}", color = 0x1295db)
Server.set_footer(f"Server ID: {ctx.guild_id}")``` working? It worked before i added the footer.
Dw abt the indentation, just messed up when sending
How do you set multiple lines for embed?
Just add \n or embed.add_field
thanks
do you realize that will always default to your else? a member object will never be the same as an id
remove "Server" before "set.footer"
should work
no?
no
set_footer(text="")
Oh thanks
myb
hi, a bit of a noob question here:
how do you supposed to pass variables into a decorator?
e.g. with this code is there anyway to put self.placeholder into the decorator
youd need to subclass your select and then add it to your view
its almost the same thing lol
instead of subclassing a view, you subclass the select and pass the parameters
then just add it to a view
wait
ok let me try it
ok i can subclass the select, but i dont get how to pass the parameters
should i just append my subclass to view.childrens
maybe i didn't subclass this properly decorators are weird
Hey, sorry for re-asking.
What I would like is a way to load cogs if the option is enabled (in the db)
So I have some models:
class GuildConfig(Model):
id = fields.BigIntField(pk=True, unique=True, nullable=False)
prefix = fields.TextField(default="$")
mod_enabled = fields.BooleanField(default=False) ```
and I have my cogs/_init_.py which loads the cogs as so:
```python
def setup(bot: 'Nethra'):
bot.add_cog(Moderator(bot))
but in order to get the guild config I need its id, and I can't figure out how! If anyone knows how I could do this, I would be very grateful! Thanks!
how can you make a permission overwrite object and what will the syntax of it be?
It's a dict. {MemberOrRoleObject: discord.Permission(...)}
ok got it
does anyone know whats missing im getting this error when trying to make a persistent view
view has no timeout
and there's a customid set
nvm
im bad i was calling super init again later
Hello, i have a bot related question. For a while now i saw that the second bot does not have an online symbol. Does anyone know what is going on with this? Like how did he hide that even though he is online
The bot is connected through http connections
Guys I know this is kinda stupid but how do I make my bot run by just opening the py file
I paid for a bot hosting just for them to tell me they don’t support the way I open it
How could I check if a user is server muted / not server muted
i am and i still cant figure it out 
Check the attributes of the Member object
kk ty
@tasks.loop(seconds=60)
async def my_loop(userobj, memberobj):
if memberobj.voice.mute == False and memberobj.voice.deaf == False:
await memberobj.edit(mute=True)
await memberobj.edit(deaf=True)
else:
print("user already muted / deafened")
Traceback (most recent call last):
File "C:\Users\Austin\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\tasks\__init__.py", line 176, in _loop
await self.coro(*args, **kwargs)
File "D:\Coding Stuff\Python\Discord\Other Miscellanious Bots\Mute Annoying People\constantlyMuteAnnoyingPeople.py", line 20, in my_loop
await memberobj.edit(deaf=True)
TypeError: Member.edit() got an unexpected keyword argument 'deaf'```
anyone able to help?
bruh im dumb, thanks
we all are.

because it doesn't have.
looks nice
so im getting this error
Ignoring exception in command whitelist_user:
Traceback (most recent call last):
File "C:\Users\Nikola\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 124, in wrapped
ret = await coro(arg)
File "C:\Users\Nikola\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 980, in _invoke
await self.callback(ctx, **kwargs)
File "c:\Users\Nikola\Documents\fn id lookup\bot.py", line 57, in whitelist_user
if user.id not in whitelist['users']:
AttributeError: 'str' object has no attribute 'id'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Nikola\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 1114, in invoke_application_command
await ctx.command.invoke(ctx)
File "C:\Users\Nikola\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 375, in invoke
await injected(ctx)
File "C:\Users\Nikola\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 132, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'str' object has no attribute 'id'```
which ive never had before
command
@bot.slash_command(description="Add or remove a user from whitelist (BOT OWNER ONLY)")
@option("action", str ,description='"add" or "remove"')
@option("user", str ,description='The user you wish to whitelist')
async def whitelist_user(ctx, action, user: discord.User):
if ctx.author.id in whitelist['owners']:
action = action.lower()
if action=="add":
if user.id not in whitelist['users']:
manage_whitelist(user.id, "+", "users")
await ctx.respond(embed=discord.Embed(description=f"Added `{await bot.fetch_user(user.id)}` ({user.id}) to Premium whitelist!", color=0x5ed515), ephemeral=True)
await user.send(f"`{await bot.fetch_user(user.id)}` has whitelisted you! You can now use `/lookup`!")
log(f"{await bot.fetch_user(ctx.author.id)} ({ctx.author.id}) has whitelisted {await bot.fetch_user(user.id)} ({user.id})")
else:
await ctx.respond(embed=discord.Embed(description=f"`{await bot.fetch_user(user.id)}` ({user.id}) is already whitelisted!", color=0xea0000), ephemeral=True)
elif action=="remove":
if user.id in whitelist['users']:
manage_whitelist(user.id, "-", "users")
await ctx.respond(embed=discord.Embed(description=f"Removed `{await bot.fetch_user(user.id)}` ({user.id}) from whitelist!", color=0x5ed515), ephemeral=True)
log(f"{await bot.fetch_user(ctx.author.id)} ({ctx.author.id}) has removed {await bot.fetch_user(user.id)} ({user.id}) from whitelist")
else:
await ctx.respond(embed=discord.Embed(description=f"`{await bot.fetch_user(user.id)}` ({user.id}) is already whitelisted!", color=0xea0000), ephemeral=True)
else:
await ctx.respond(embed=discord.Embed(description="Only a owner can use this command :slight_smile:", color=0xea0000), ephemeral=True)```
any ideas?
Is it possible that whitelist['owners'] a list of strings are?
Thats my idea
change my mind
nah, its a list of integers/user ids, what does throw me off is when i @ the user in the 2nd field the output is <@someid> which it never was so im very confused, makes sense why user.id wouldnt work but it wasnt like this before
Ohhh maybe because its asking for an input type that is a string and u want it as a member?
so u want it to autocomplete members?
Like it must be maybe a discord.Member or a discord.User obj
@option("user", str ,description='The user you wish to whitelist') this? so id have to change str to discord.User?
Is this #discord-api-updates message already added to pycord?
Not yet, it's a planned feature
okay
don’t think that’s got anything to do with pycord…
File "F:\fun\Desktop\coding practice\python practice\bot_pycord\main.py", line 2, in <module>
from discord.ext import commands
File "C:\Users\fun\AppData\Roaming\Python\Python311\site-packages\discord\ext\commands\__init__.py", line 18, in <module>
from .flags import *
File "C:\Users\fun\AppData\Roaming\Python\Python311\site-packages\discord\ext\commands\flags.py", line 57, in <module>
@dataclass
^^^^^^^^^
File "C:\Program Files\Python311\Lib\dataclasses.py", line 1221, in dataclass
return wrap(cls)
^^^^^^^^^
File "C:\Program Files\Python311\Lib\dataclasses.py", line 1211, in wrap
return _process_class(cls, init, repr, eq, order, unsafe_hash,
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Program Files\Python311\Lib\dataclasses.py", line 959, in _process_class
cls_fields.append(_get_field(cls, name, type, kw_only))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Program Files\Python311\Lib\dataclasses.py", line 816, in _get_field
raise ValueError(f'mutable default {type(f.default)} for field '
ValueError: mutable default <class 'discord.utils._MissingSentinel'> for field name is not allowed: use default_factory
why?
If you're using Python 3.11 you need to use the unstable version of pycord
so either downgrade your Python, or use the master from GitHub
ah i forgot it again 🤦♂️
Looks like an error from the googletrans module you're using, not much we can do to help you here
is any1 aware of any way to add a cooldown to a button (one where the cooldown only applies for the user)
There is no way to do this with the library right now, so you would have to implement your own solution for it
i guess you have to use your own python knowledge 🤓
I would do something like this:
- Set up a globally available dict with button IDs as the keys and lists/sets as the values
- When a user clicks a button, add the user to the list mapped to the button ID
- Remove the user from the dict after x number of seconds
- Every time the user clicks on a button, check if they are part of the list/set mapped to the buttons ID
yea that would be what i do
I personally prefer using sets as they are way faster than lists when checking if something is part of it, but it depends on your solution and how you want to implement it
how can you make descriptions for a option in a slash command?
Add a description='Your description here' parameter to your Option constructor
@bot.command(description="sends the option you put")
async def option(ctx,option:str):
await ctx.respond(f"{option}")
where would i put it?
import Option from discord.commands and type hint your option to that instead, it allows you to set a type, description and requirement. Like this
from discord.commands import Option
@bot.command()
async def my_command(ctx, option: Option(str, description='My option description', required=True))
...
ok ty
https://docs.pycord.dev/en/stable/api.html#discord.Option Here is the docs for it, if you want to see all parameters you can set
would it be discord.commands or discord.ext.commands?
discord.commands
ok
user1:discord.commands.Option(input_type=discord.Member,description='User 1') but the option is just a str not letting me choose the user
or do i have to do from discord.commands import Option
nvm got it sorted
oh you can use it like that? i always did it like this
@bot.slash_command(description="Add or remove a user from whitelist (BOT OWNER ONLY)")
@option("action", str ,description='"add" or "remove"')
@option("user", discord.User ,description='The user you wish to whitelist')
async def whitelist_user(ctx, action, user: discord.User):
...
With discord.ui buttons, is there any way to just store if an interaction has happened? I don't want to react to the interaction right away, but rather know if the user clicked yes/no and do something with that later. I saw #discord.InteractionResponse.defer, but I don't understand how it works.
Yeah, you can use the decorator as well. Personal preference really
agreed, still good to know!
You can defer an interaction to prevent it from timing out after 3 seconds, but you will have to respond in some way to prevent the "This interaction failed" message from showing
Hmm that's not what I'm looking for.
I want to have a message ask for example a yes/no question, and simply store what the user clicked so I can use that information later on in the command.
I mean I don't think you have to respond to a button interaction, you can just store it. But it's always good to acknowledge a button click so that the user knows something has happened when they clicked it and doesn't think the button didn't work
Well really my question is how do I store it, lol
It depends on how you want to use it later
Im new to py-cord and this stuff and i get an error "discord.errors.InteractionResponded: This interaction has already been responded to before" i know what it stands for but i don't know how to fix it 😅
You fix it by not responding twice to the same interaction
But i have to edit it twitce
Then edit it, don't respond
Bot asks question, user clicks button "option 1" or "option 2", all I want to store is the str text that's on the button. So if the user clicks "option 1", I store "option 1" into another var
What's preventing you from just storing it in a variable and re-using that variable later?
https://docs.pycord.dev/en/stable/api.html#discord.Interaction.edit_original_response You can use this to edit a response without responding

