#Basic Pycord Help (Quick Questions Only)
1 messages · Page 57 of 1
Oops lol
thanks, much love
that looks pretty complicated, any way to simplify? (sorry for 2 pings)
you can use
.rtfm discord.ui.select
discord.ui.select
discord.ui.Select
discord.ui.Select.add_option
discord.ui.Select.append_option
discord.ui.Select.callback
discord.ui.Select.channel_types
discord.ui.Select.custom_id
discord.ui.Select.disabled
discord.ui.Select.from_component
discord.ui.Select.is_dispatchable
discord.ui.Select.is_persistent
discord.ui.Select.max_values
discord.ui.Select.min_values
discord.ui.Select.options
discord.ui.Select.placeholder
discord.ui.Select.refresh_component
discord.ui.Select.refresh_state
discord.ui.Select.row
discord.ui.Select.to_component_dict
discord.ui.Select.type
alr thanks! sorry once again
as a decorator instead of sub classing the select. It is still best practice to subclass the view though.
Im here to help no need to be sorry :)
so i place these at the top like @ option thingy?
yes
gotcha
why is suraj not printed?
Because you're breaking the loop when you hit Taruna
And you should probably go to a different server, this is not a place to be learning basic Python.
Use the @guild_only() decorator. There's an example in the docs: https://docs.pycord.dev/en/stable/api/application_commands.html#discord.commands.guild_only
Command Permission Decorators: Commands: Shortcut Decorators: Objects: Attributes full_parent_name, qualified_id, qualified_name. Methods@ after_invoke,@ before_invoke,@ error, def get_cooldown_ret...
alright thank you
Np
is there any better way to get everyone in a server that has a specific role instead of looping through everyone and checking if they have the role?
@proud pagoda
Models are classes that are received from Discord and are not meant to be created by the user of the library. Attributes key, url. Methods def is_animated, async read, def replace, async save, def ...
Does anyone have a example of discord.ui.select where the options change based on the input of the user?
How it'd be based on the user's input? A slash command option? Some value stored in a db?
Slash command option
And what would the user choose/how would it work exactly
you would subclass discord.ui.Select and do it from there.
Right I was thinking about that, might be the best approach
Yeah that is the best option
I'll do just that, thanks
yw
What's the limit on how many options you can have, 25?
Yes
Thanks
Just saying you are getting an error isn't helpful. Show your code and your pip list
Hey, can someone help me with this: I'm not getting an error in the console & nothing is noticeable when debugging either. The problem is that when I run the slash command in Discord, the bot doesn't respond and Discord returns "The application didn't respond".
if activities:
embed.add_field(name='Aktivitäten:', inline=False, value='\n'.join(activities))
await ctx.respond(embed=embed)
What if the user doesn't have any activities
if activities is a useless check because it's always going to be defined
try deferring
please help guys pycord no work with the onmessage
@client.event
async def on_message(message):
?tag intents
https://docs.pycord.dev/en/master/intents.html
https://discord.com/developers/docs/topics/gateway#gateway-intents
import discord
from discord.ext import commands
# Get specific intents for fine control
intents = discord.Intents()
intents.emojis = True
intents.guilds = True
intents.messages = True # Required for prefix commands!
...
# Get all non-priveliged intents; this excludes presences, members and message_content
intents = discord.Intents.default()
# Set priveliged intents: these must be enabled on dev portal
intents.members = True
intents.presences = True
intents.message_content = True # Required for prefix commands >= 2.0.0b5
# Get all intents; all intents must be enabled on dev portal.
intents = discord.Intents.all()
# Apply intents when creating your bot
bot = commands.bot(prefix="?", intents=intents)
In version 1.5 comes the introduction of Intents. This is a radical change in how bots are written. An intent basically allows a bot to subscribe to specific buckets of events. The events that corr...
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
?tag message-content
but when I put # in front of it, it still doesn't react.
As of Pycord Beta 5, Discord API v10 requires message content intent to receive message content. This affects the traditional commands. Not enabling this intent will result in the messages' content, embeds, and components being empty.
You will need to enable the intent on the developer portal, as well as in your code:
intents = discord.Intents.default()
intents.message_content = True
bot = discord.Bot(intents=intents)
Docs: https://docs.pycord.dev/en/master/api.html#discord.Intents.message_content
does django or flask makes sense if you work with vuejs3 frontend?
Just as an api server i think?
Why wouldn't it?
indentation. move ctx.respond 1 tab to the left
dont fetch user. you should already have everything
defer the response at the first line of the callback
Django if you know Python well and are planning to build a big site, otherwise just flask
fastapi is cool too 
not for static web pages
I personally use fastapi over everything else 
yes, thanks
fastapi looks very good
Django is also very overkill if you only want a backend to set up an API
What's the difference between discord.Bot() and commands.Bot?
?tag inheritance
No tag inheritance found.
?tag client
discord.Client # just for events
discord.Bot # events + slash/user/msg commands
commands.Bot # above + prefixed commands
bridge.Bot # above + bridge commands (application commands and text commands in one)
How do you preshoot my questions?
because they are common questions
ig
is there a way to make it so when a bot sends a modal there is already text in the input field that the user can edit?
Set the value attribute of the TextInput. The docs literally tell you this
I started getting this error when i launch my bot and it doesn't update any commands anymore...
venv\lib\site-packages\discord\http.py", line 366, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In options.1: Required options must be placed before non-required options
I thought it may be of discord options but i haven't changed those, yet it suddenly started showing it.
maybe you updated the code, but didn't run the bot
I added one command. Tried removing it and it still throws the error... I tried looking if i have the required options behind non-required (as the error says), but to no avail, where multiple options are either all are non-required or all are required.
Just tried removing the command again.. now it doesn't throw an error... ahh to find the problem now
Solved! Just added "default" value to the option that didn't have it and no more error! Really strange tbh
How does one get the item selected from a selection callback?
select.values[0]
Where does select come from
Wait I need to clarify 1 min...
Here's the dropdown example.
Yeah I looked at that...
how can i edit a response
from a slash command?
ctx.edit()
Thanks! I got it. Just needed to create a separate class instead of the weird workaround I was doing before.
its returns an interaction and you also can use https://docs.pycord.dev/en/master/api/models.html#discord.Interaction.edit_original_response
@bot.command()
async def ping(ctx):
await ctx.respond("Pinging...")
start = time.time()
result = requests.get("https://discord.com/api")
end = time.time()
elapsed_time = (end - start) * 1000
await ctx.edit(f"Pong! ({elapsed_time:.2f} ms)")```
am i doing something wrong
TypeError: Interaction.edit_original_response() takes 1 positional argument but 2 were given```
content=""
💀
is there a better way to do it
thx
In components.0.components.0.options: Must be between 1 and 25 in length.
I seem to be getting this weird error.
Code:
elif self.selection == 'voice_channel':
for channel in guild.voice_channels:
if len(options_list) >= 20:
selects.append(Select(options=options_list))
options_list = []
else:
options_list.append(discord.SelectOption(label=channel.name))
selects.append(baseSelect(options=options_list))
for select in selects:
view.add_item(select)
print(select)```
This same code works for text channels, but for voice channels it gives the error.
I'm not sure why.
When I print the selects it gives me a baseSelect with options which is normal
What does this error even mean
It means you're adding too many options to the select, or none at all
HMmmmmmmmmmmmmmm
Ok I'll try some things. Thanks!
When printing the children of view I get:
[<baseSelect type=<ComponentType.string_select: 3> placeholder=None min_values=1 max_values=1 options=[<SelectOption label='annoucements' value='annoucements' description=None emoji=None default=False>, <SelectOption label='rules' value='rules' description=None emoji=None default=False>, <SelectOption label='about' value='about' description=None emoji=None default=False>, <SelectOption label='changelog' value='changelog' description=None emoji=None default=False>, <SelectOption label='reaction-roles' value='reaction-roles' description=None emoji=None default=False>, <SelectOption label='general' value='general' description=None emoji=None default=False>, ... (more select options afterward)```
OH WAIT
I'M BIG DUMB
I don't have any voice channels in the server...
I'm so sorry...
tysm btw
@bot.event
async def on_member_join(member):
global welcoming
global checking_age
welcome_channel = bot.get_channel(1073385967722954782)
if checking_age:
if (member.created_at - member.joined_at).total_seconds() / (3600 * 24) < 10:
await member.kick(reason="Account age is under 10 days.")
if welcoming:
await welcome_channel.send(f"Hi {member.mention}! Welcome to the server!")
async for entry in welcome_channel.history(limit=10):
if (member.joined_at - entry.created_at).total_seconds() <= 5:
welcoming = False
checking_age = True
start
await welcome_channel.send("WARNING: RAID DETECTED | DISABLING WELCOME MESSAGES AND ENABLING AGE CHECKS | @languid wave @Literally An Axolotl#0001")
return```
am i doing something wrong here cuz this is how i did it in discord.py when it was still a thing
?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.
So the issue is that the event isn't firing?
yeah
yuh
intents = discord.Intents.all()
bot = discord.Bot(intents=intents)```
thats correct right
or am i dumb
It also has to be enabled in your developer portal
they are
@limber urchinnvm they werent enabled in the portal
but it spams messages in the chat when a raid is detected
it shouldnt do that, do u know why
Because your code makes it send a message on every join?
it's not a method, it's an attribute
same thing
Target not found, try again and make sure to check your spelling.
.rtfm User.avatar
.rtfm Asset.url
Take a look at the docs and you'll know
.tias
gay
?
Lol #ignore
anybody know how to add execption if bot has no perm to add roles
Do you mean raise exception ?
Yeah, what do you mean by "add" exception?
.rtfm Forbidden
Maybe it's easier if your write your own code instead of relying on copilot
Well I can't see the rest of your code so I don't know. Try it and see
imma test it brb
raise InteractionResponded(self._parent)
discord.errors.InteractionResponded: This interaction has already been responded to before
now that error appear
lemme go look on that on the doc
oh wait i think i know why
since i added the response before i actually add the role
works now thx
Here's the buttons example.
i want a buttons example...
Here's the @everyone example.
no i need how to make the bot not ping
how to make the button clickable only by the uh owner who ran the cmd
.rtfm interaction_check
@boreal abyss the second one, discord.ui.View.interaction_check
You add it to your view, and in the interaction_check method you check if the interaction.user.id is the same as the owner's ID. return a True if it is, the button's callback will process, otherwise it does nothing.
Can you specify?
any code example from /example
Here's the interaction example.
Pass allowed mentions when sending msg
.rtfm allowed
discord.AllowedMentions
discord.AllowedMentions.all
discord.AllowedMentions.everyone
discord.AllowedMentions.merge
discord.AllowedMentions.none
discord.AllowedMentions.replied_user
discord.AllowedMentions.roles
discord.AllowedMentions.to_dict
discord.AllowedMentions.users
discord.Bot.allowed_mentions
discord.AutoShardedBot.allowed_mentions
discord.ext.bridge.Bot.allowed_mentions
discord.Client.allowed_mentions
discord.ext.commands.AutoShardedBot.allowed_mentions
discord.AutoShardedClient.allowed_mentions
discord.ext.bridge.AutoShardedBot.allowed_mentions
discord.ext.commands.Bot.allowed_mentions
i need to learn how t o use the docs
its not helping
how can i add that in my "Class"
why do i await it?
why IS THERE no code example just like what djs do
dayum
You are subclassing view right
Override that method
It should return a bool
Hey, so I have a view that I need to make persistent but to instantiate an object of this class I need to pass in a bunch of parameters, how would you pass in the parameters in
bot.add_view(MyView())
For example I need to pass in a user object to MyView which will be used to check if the user exists in my db, I can do this fine when I'm sending the view from a command because I can pass in ctx.user but what do I pass for user in bot.add_view(MyView()) ?
Well you would need to store the parameters you want to pass in a db. Then fetch the stuff from the db when adding and pass them
You can also store user id and use bot.get_user to get the user object at runtime
ah that makes sense, also sounds like my work just increased lol, thanks though
Lol good features aren't always easy
a = int(x)
print(a)
channel = await ctx.guild.fetch_channel(a)```
x returns a value of numbers but when i put in channel var it says unkown var
Cam you show full error
Well that channel is not found in the server. Are you sure the id is correct?
Yez
Is it possible to have button interaction as a boolean? For example, if click button A then execute command(x), if click button B then execute command(y) 
Does the bot have permissions for this channel?
Here's the confirm example.
You can execute functions with button presses. The example above shows you how to subclass the view and add 2 buttons that when pressed execute 2 different functions.
Thank you 
Ye
Is it possible to write a script or code that will restart the chatbot in case of an error.
I I tried to write (it works badly), but I would like to learn from people who know programming better.
I would be grateful to anyone who can help.
@bot.event
async def on_error(event, *args, **kwargs):
await bot.logout()
await bot.close()
await bot.connect()
It can help 🤔🤔
?tag restartcmd
Tag Credit: discord.py server
The only good way to restart your bot is to shut it down and have your process manager handle it. You can shutdown your bot by running Bot.close().
Do use:
- run your bot in a process manager such as:
- systemd
- openrc (gentoo, devuan)
- runit (void linux)
- supervisord
- upstart (old ubuntu)
- docker
- manually reboot it
Do not use:
- a bash loop (it can eat your C-c by rapidly spawning python and if your bot fails it won't stop it from constantly failing)
- subprocess.call (you will eat your memory up by not letting your old processes die)
- os.exec*
Is there a better way of sending/editing messages than using modals? (Using application commands and without having the msg content intent)
Depends on what you re doing?
Are you getting user input?
How to set a none status like the following?
Most likely it's a bot that only uses HTTP requests
So that's why it doesn't have a status
I am sending a message through a webhook to a thread, all works fine. But i don´t know why there is :
"Ursprüngliche Nachricht wurde gelöscht" - Original message has been deleted
a = int(x)
print(a)
channel = await ctx.guild.fetch_channel(a)```
x returns a value of numbers but when i put in channel var it says unkown var
Yup. It’s to allow the admins to send and edit custom messages (multi-line including formatting). Currently using modals which works fine for sending messages, but is a little inconvenient when it comes to editing if you only want to edit a small part of the message while keeping the rest exactly the same
try hardcoding the channel id and see if it works
also, which python version and show pip list
well if you want to use interactions and avoid msg content intent, modals or dms are really the only way
why is it inconvenient to edit messages?
if it is a button click to edit msg, pass interaction.message which creating the modal instance, and store it on a self variable in the modal
use that to edit in the modal callback
Cause you can’t just backspace 5 characters and keep the rest the same
Ig I’ll just add a copy raw text command
Just thought there might be a cleaner way

I’ll interpret this as "I understand what you’re trying to archive, but unfortunately don’t know another way"
what did you mean by "Cause you can’t just backspace 5 characters and keep the rest the same"
Let’s say I send this message.
Edit: Now I can add those words without having to reformat/type the words prior
but yes, that was the general vibe of my response 💀
Kinda like editing your own message, I want the initial message to be already typed, allowing the user to add or edit smaller portions without having to manually copy or rewrite the initial message
well you can do this-
smth like content = message.content + "\n\n" + input_text.value
I gotta exit the train now and than walk home, I’ll check in here later tho
lol alr
channel = await ctx.guild.fetch_channel(12345) where 12345 is an actual channel id you confirmed is in the server
But that would just add the new lines. I want the users to add/edit/delete whatever part of the message they like
Is there anyway to already have some typed out text (in my case the raw initial message content) pre entered to a modal field? This would allow the users to edit the text similarly to editing their own messages
The library has helpers to help create component-based UIs. Shortcut decorators: Objects: Attributes children, disable_on_timeout, message, timeout. Methods cls View.from_message, def add_item, def...
That's exactly what i was looking for, thank ya
How to place some embed field like this?
Because i need to add everytime blank field between all inline field
All Field are inline
No tag embed found.
is there a way to show a list of scheduled events in a slash command option(bit like how to get a list of channels)?
Do we have docs about role connections?
what might be the issue of bot restarting itself on linux vps but not on my windows pc?
on_ready can fire multiple times while the bot is running
oooh thanks :D
import B
import os
from discord.ext import commands
bot = discord.Bot()```
I am not sure why my bot isn't connecting to discord.
It keeps saying module discord has no attribute 'bot'
Most likely you have conflicting libraries
commands.Bot, not discord.Bot
@sick oriole
discord.Bot is correct
I'm not saying that commands.Bot is wrong. I'm saying discord.Bot exists
O
?tag client
discord.Client # just for events
discord.Bot # events + slash/user/msg commands
commands.Bot # above + prefixed commands
bridge.Bot # above + bridge commands (application commands and text commands in one)
Is it possible that they didn’t add a bot.run(“token”)
I think we need the full code to figure out the problem properly
this should not be happening. @full basin provided the correct answer.
It would be a dependency/package issue
ping
Yes
Why would you need the full code? The error is a missing or conflicting package. The rest of the code has nothing to do with that.
Yup ive done that
When using a select menu with user_select on mobile it only shows a small list of names. Is there any way to fix this?
how to make these type of points in an embed?
You do
hello
So ">" and a space in front of your text
so it's > hello
is it normal for my bot to not go online out of nowhere?
hey, i have a backend for my website using django, and how to things like kicking a person using website?
backend sends request to bot?
Wdym 🤔
like
it wont go online without any changes whatsoever
it worked completely fine some days ago
You use ipc to communicate between those two. There is a library called better-ipc. Check it out
Discord recently has some issues but I'm not sure if they are related to this
See latest msg in #discord-api-updates
Also, make sure to update to latest pycord version
i did too 😉
Nice
tried everything i could
What about a different bot token?
Did that work?
and i get no errors aswell
Hmm
no, i tried running on cloud but same thing
What happens when you run just a basic bot
let me do so
Here's the basic bot example.
Like that
let me run it
That goes online 😭
then it has to be somewhere in my code
let me check it again
Is there any way to show the attachment from discord.Option(discord.Attachment) in an embed image?
yes
what is it?
what is it returning?
How do i edit the response to a slash command?
.rtfm to_file
f = discord.File("some_file_path", filename="image.png")
e = discord.Embed()
e.set_image(url="attachment://image.png")
await messagable.send(file=f, embed=e)```
(ofc without the 1st line)
you can just use the url?
?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.
Ok, i send Modal through the button like this
await interaction.response.send_modal(Reason(timeout=60, title='Введите причину', id=id, closer=interaction))
class Reason(discord.ui.Modal):
def __init__(self, id,closer, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.closer = closer
self.id = id
self.add_item(discord.ui.InputText(label="Укажите причину закрытия", placeholder='Bla-Bla-Bla', value='Не указана', style=InputTextStyle.long))
async def callback(self, interaction: discord.Interaction):
await interaction.response.send_message(embed=Embed(description=f'Вы успешно закрыли тикет с причиной `{self.children[0].value}`!'), ephemeral=True)
member = await interaction.guild.fetch_member(self.id)
await member.send(embed=Embed(description=f"{'❎ Ваш тикет был закрыт администратором!' if interaction.user.id != member.id else '❎ Вы закрыли свой тикет!'}\n{f'🟨 Администратор: {interaction.user}' if interaction.user.id != member.id else f'🟨 Администратор: {interaction.user}'}\n{f'✅ Комментарий: {self.children[0].value}' if interaction.user.id != member.id else f'✅ Вааш комментарий: {self.children[0].value}'}" ))
async def on_timeout(self):
member = await self.closer.guild.fetch_member(self.closer.user.id)
await member.send(embed=Embed(description=f"{'❎ Ваш тикет был закрыт **администратором**!' if self.closer.user.id != member.id else '❎ **Вы** закрыли свой тикет!'}\n{f'🟨 Администратор: {self.closer.user}' if self.closer.user.id != member.id else f'🟨 Администратор: {self.closer.user}'}\n✅ Комментарий: **Не был указан**" ))
It just don't working
I figured it out
im so dumb
class NS(commands.Cog):
def __init__(self, bot):
self.bot = bot
game = SlashCommandGroup("newstate", "Various greeting from cogs!")
class Pass(discord.ui.Modal):
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.add_item(discord.ui.InputText(label="LOBBY name:",min_length=4,max_length=25,placeholder="Enter the title." ,style=discord.InputTextStyle.long))
self.add_item(discord.ui.InputText(label="Time:",max_length=40,placeholder="Start time." ,required=False, style=discord.InputTextStyle.multiline))
self.add_item(discord.ui.InputText(label="Password:",max_length=6,placeholder="Enter password." ,style=discord.InputTextStyle.multiline))
self.add_item(discord.ui.InputText(label="Map/Perspective:",max_length=400,placeholder="Map/Perspective", style=discord.InputTextStyle.long))
self.add_item(discord.ui.InputText(label="Additionally:",max_length=3000,placeholder="Enter ",required=False, style=discord.InputTextStyle.long))
async def callback(self, interaction: discord.Interaction):
embed = discord.Embed(title=f"PASSWORD MENU" , description=f"**LOBBY:** **{self.children[0].value}** {self.children[1].value}\n\n**PASSWORD:** **{self.children[2].value}**\n\n**MAP|FPP/TPP:** {self.children[3].value}\n\n**ADDITIONALLY:** {self.children[4].value}" ,colour=discord.Colour.random())
await interaction.response.send_message(embeds=[embed])
@commands.has_permissions(administrator =True)
@game.command(name='password', description='Write form the password to send.',guild_ids=[944934277777326090,769823680695107594]) #
async def password(self , ctx: discord.ApplicationContext):
roster = Pass(title="Password menu")
await ctx.send_modal(roster)
def setup(bot):
bot.add_cog(NS(bot))
WHY?!!!
Where wrong?
Ohh yeah that's much much better 💀
create the class outside of the other class?
ok will try
When using a select menu with user_select on mobile it only shows a small list of names. Is there any way to fix this?
Can you start typing the user name and the list will update?
I'm trying to make bot that supports slash commands, I'm using py-cord 2.4.0
I followed the provided code in the documentation, but I keep getting this error:
Exception has occurred: AttributeError
module 'discord' has no attribute 'Bot'
?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
I haven't done -U py-cord yet
that could very well be it 💀
Specifically step 1
can you show the pip list?
Package Version
------------------ -------
aiohttp 3.8.4
aiosignal 1.3.1
async-timeout 4.0.2
attrs 22.2.0
charset-normalizer 3.0.1
frozenlist 1.3.3
idna 3.4
multidict 6.0.4
pip 23.0
py-cord 2.4.0
python-dotenv 0.21.1
setuptools 65.5.0
wheel 0.38.4
yarl 1.8.2
did you also restart the editor and the terminal?
yes
can you uninstall py-cord and reinstall it?
10th time's a charm
done that
but unfortunately to no avail
should I move this to a thread?
I think this is an issue with your terminal being in one environment while your code is running in another.
you mean like PyCharm?
Yeah, there code is running in a virtual environment while the stuff they are doing in the terminal is not in the environment
if I use the terminal in the ide it says already satisfied
im pretty sure my command prompt and ide are synced
Hey Folks, is it possible to create a Modal which users can be "log in" with and be redirected to a website?
the login information is generated by a command if the user has a specific role, and is added to a DB. So they dont have to provide individual passwords or usernames so that a malicious use is excluded
hey people, is this the correct way of fetching a pfp of a user?
asset = user.avatar.url(size=128)
async def invert(self, ctx, *, user: Option(discord.Member)):
asset = user.avatar.url(size=128)
icon_url=user.default_avatar.url if user.avatar is None else user.avatar.url
awesome perfect
yes yes, gotch thanks both of you
You're welcome
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: 'str' object is not callable
any idea?
the full thing
i mean i changed to user.display_avatar.url
but still doesnt work
.
are you using @bot.command() decorator ?
i see
i think because you're using self parameter
so you have to put this function inside a cog
if its in a cog you need the self, ctx
Look at the docs for the right syntax
Agree
This should work @silent meadow
As far as I know in discord, you can't set permissions for a command from a group.
But how then to set the default permissions for the entire group of commands?
I read about it in the documentation https://docs.pycord.dev/en/stable/api/application_commands.html
But how should it work for my case?
For example, I want administrator rights to use commands from the dump group
dump = bot.create_group(name="dump")
@dump.command(name="first_join")
async def command(ctx: discord.ApplicationContext):
print(f":/: {ctx.author} used command /{ctx.command}")
Quick and dumb question
It used to be that to invoke a bridge command from another bridge command within the same cog, you can just use
await ctx.invoke(self.other_command)
However #1642 changed it to
await self.other_command.invoke(ctx, *args, *kwargs)
Doing this, however, errors out for me with
discord.ext.commands.errors.MissingRequiredArgument: ctx is a required argument that is missing. within the command being called???
https://docs.pycord.dev/en/master/api/application_commands.html#discord.SlashCommandGroup.default_member_permissions
You can pass a permissions object as a kwarg to create_group
Command Permission Decorators: Commands: Shortcut Decorators: Objects: Attributes full_parent_name, qualified_id, qualified_name. Methods@ after_invoke,@ before_invoke,@ error, def get_cooldown_ret...
Doesn't seems so. Doing that passes the Cog object itself to the command (as self.command was used, so self will be the first arg)
It would fail earlier because it will check is_app on the Cog and not ctx
Thats it?
dump = bot.create_group(name="dump",
default_member_permissions=discord.Permissions(permissions=8))
In the example they dont use self.other_commanf
Just other_command.
It looks correct
Doesn't seem so. Without self it would NameError
Cog.command.invoke(ctx) fails similarly as well
Wait you would need self wouldn't you. Try ctx=ctx
That would TypeError because ctx isn't a kwarg
Command raised an exception: TypeError: invoke() missing 1 required positional argument: 'ctx'
Sorry I am not thinking straight rn. I would open a thread about it and hopefully someone less tired can help.
It doesn't seem to work.
I checked on a person without roles and any admin permissions to use the command, but nothing has changed, the command can still be used.
settings = {
'TOKEN': '---',
'BOT_NAME': 'SubBot',
'APP_ID': 959411069753901084,
'ALLOWED_SERVERS_ID': [1069357003362807848],
}
import discord
import json
import time
from config import settings
bot = discord.Bot(intents=discord.Intents.all())
@bot.event
async def on_connect():
if bot.auto_sync_commands:
await bot.sync_commands()
dump = bot.create_group(name="dump",
guild_ids=settings["ALLOWED_SERVERS_ID"],
default_member_permissions=discord.Permissions(permissions=8))
@dump.command(name="first_join",
guild_ids=settings["ALLOWED_SERVERS_ID"])
async def command(ctx: discord.ApplicationContext):
_output = "Added:"
for user in ctx.guild.members:
if str(user.guild.id) not in user_first_join:
user_first_join[str(user.guild.id)] = {}
if str(user.id) not in user_first_join[str(user.guild.id)]:
user_first_join[str(user.guild.id)][str(user.id)] = str(int(time.mktime(user.joined_at.astimezone().timetuple())))
with open("user_first_join.json", "w") as f:
json.dump(user_first_join, f)
_output += (f"\n+ {user}")
await ctx.respond(_output, ephemeral=True)
bot.run(settings["TOKEN"])
If I am extending the bot class in order to instantiate my bot, how can I implement slash commands? i.e.
class SomeBot(discord.Bot):
async def on_ready(self):
print(f'Logged on as {self.user}!')
async def on_message(self, message):
print(f'Message from {message.author}: {message.content}')
//Add a slash command here
Or is this dumb to do in the first place
Yeah... don't do this, the moment you have more than a few simple commands it will be a giant mess. Use Cogs.
what might using Cogs with this approach look like?
Basically just shove all the commands you need into a Cog and ship it around between where you may use it
How to get the message url from a context menu?
I'm trying to get message's url:
@bot.user_command(name = "Translate")
async def translate(ctx, message: discord.Message):
...```
jump_url
How can i create private thread?
thanks
how can i use shards?
how much will it cost for a shard that can server around 1.2k servers?
Just change your Bot to AutoShardedBot https://docs.pycord.dev/en/stable/api/clients.html#discord.AutoShardedBot
can i hide commands like mee6?
though you generally don't need it around 1k guilds
i think mee6 implements command management over oauth2 which is something you'd have to implement yourself, but you can use default_permissions to set minimum required permissions (which admins can override) https://docs.pycord.dev/en/stable/api/application_commands.html#discord.commands.default_permissions
will it be stupid if i try to implement it using guild commands?
you can't hide through commands since there's no (standard) api for it
you CAN limit commands using stuff like check decorators, but they'll still show on the user end
i mean if this guild need a kick command admin can add it then bot will create a guild command for this command
so if they remove even admisn cant see it
uhh not quite sure what you mean
1 min
i mean using this to create a guild a command when an owner or admins add a command
then yeah fill in default_member_permissions and sync
async def play(self, ctx, *, song_name):
"""Search from spotify to add to the song queue."""
await ctx.defer()
results = sp.search(q=song_name, type='track', limit=1)
track_id = results['tracks']['items'][0]['id']
print(track_id)
if ctx.author.voice is None:
embed = discord.Embed(description=":warning: **Not in a voice channel**")
await ctx.respond(embed=embed)
return
if not ctx.voice_client:
vc: wavelink.Player = await ctx.author.voice.channel.connect(cls=wavelink.Player)
await ctx.guild.change_voice_state(channel=ctx.author.voice.channel, self_mute=False, self_deaf=True)
else:
vc: wavelink.Player = ctx.voice_client
vc.tchannel=ctx.channel
if vc.queue.is_empty and not vc.is_playing():
try:
track = await vc.node.get_tracks(query=f"https://audio.shufflebot.xyz/track/{track_id}", cls=wavelink.LocalTrack)
await vc.play(track[0])
await vc.set_volume(50)
await ctx.respond(f'Added `{track[0].title}` to the queue.')
except:
await ctx.respond(":warning: Unable to find that song.")
else:
track = await vc.node.get_tracks(query=f"https://audio.shufflebot.xyz/track/{track_id}", cls=wavelink.LocalTrack)
await vc.queue.put_wait(track)
await ctx.respond(f'Added `{track.title}` to the queue.')```
the first song plays fine then when i run the command again (should add the next song to queue) it does not play it after the first song finishes
though the sync implementation is kind of whack...
so thats means yes 💀
...
someone here told it was not possible
may be my explanation was wrong back then
last question can i use pycord-v3?
it's "possible" but there are some issues with how pycord is structured that may make your approach inconvenient
like?
it's not recommended but yeah https://github.com/Pycord-Development/pycord-v3
after looking into codes, i think i will need to change lot of stuffs if i want to change to pycord-v3
i mean using this to create a guild a command when an owner or admins add a command
what exactly do you mean by this? can guild admins create slash commands on your bot?
lets say there is a plugin called mod commands, which has commands like ban, kick, warn.
when bot jjoins a server it wont have those commands (even oowner or admin cant see it)
but when owner/admin add that plugin it will be visible for those who have the permission to use that command
hmmmmm
so when owner/admin adds the plugin, i was thinking to create guild commands to get above functionality
is my way ok?
in theory, assuming you turn off autosync and have logic to loop through some data to call sync_commands then yeah it would be possible
okay
...but terribly inconvenient because you'd end up with thousands of individual guild commands instead of 3 global commands
will it cause performance issue?
probably not tbf
then okay
you are correct
but it looks like a fun challenge
discord bots use ipc to communicate?
like web server and the bot
yea thats really the only way to communicate with each other
okay
if you're curious, you can read their page on the gateway and connections https://discord.com/developers/docs/topics/gateway
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
Hello. I wanted to know who can help with the output of information.
Stupid question - Are @silent messages referenced anywhere in the message object? I see MessageFlags exists for sending, but does that also refer to flags when fetching?
(re: task running question that was deleted: https://docs.pycord.dev/en/stable/ext/tasks/index.html#discord.ext.tasks.Loop.is_running)
how do you disable a button with a certain custom id? is that possible? (in a separate command from where the buttons are being sent)
Might be on master
in pycord, if u can do msg.author.ban(), would msg.author.timeout() work as well?
try and see
Bit of a long shot but I've exhausted all my googling/support seeking options, anyone know how to get something like digitalocean's app platform to correctly launch a bot? In the deploy logs I see the "bot has connected" string print out and whatnot, but then DO just says the deploy didn't work with no errors shown even.. when it appears to launch successfulllly
you can try asking digitalocean support.
ah they're useless lmao
was hoping maybe someone here had run into a similar issue on some other app hosting platform
each hosting platform is different.
nbd, I'll poke around with it more, if I find a solution I'll post it here for future searchers
stupid question but the docs are hard to understand as theres barely any examples
how do i delete the original message
like the upper one
the send() method returns a message.
you can delete the message with
im supposed to put ctx.message.delete after ctx.send arent i
.rtfm message.delete
wondering why it wasnt working properly
ctx.message returns the message that was originally sent by the user that triggered the command
so like this
await ctx.message.delete
await ctx.send(string)
or the other way around
Try it and see
.
yeah?
and delete is a method
do you know what a method is?
do you know basic OOP?
object-oriented programming?
so if mimi is a Cat, which has a method called eat, how would you call eat?
good, so if ctx.message has a delete method, how would you call delete?
ctx.message.delete()
yeah i tried that
oh
yeah its not working its throwing an error
wait lemme see what the error is
nvm its not throwing an error
Command raised an exception: TypeError: object method can't be used in 'await' expression
i thought i had to await it
Show the code @dusky sorrel
@bot.command()
async def say(ctx: commands.Context, *, string: str):
"""Says what you tell it to."""
await ctx.send(string)
await ctx.message.delete()
Show the full traceback too please
there is no traceback
this is literally all it threw
because I told it to throw it
print(error)
?
RuntimeWarning: coroutine 'Message.delete' was never awaited
what do you want from me python
Oh now it works
its like plugging in a usb
It doesnt work then you try something else and then you try it again and it works
when you edit your code. you need to restart your bot for the code to update
(use cogs)
For anyone searching for this later, if you want to deploy a PyCord bot on DigitalOcean's app platform you have to select an instance of type "Worker" and not "Web".
It's better to just use a droplet though
True but some are lazy and don’t want to deal with OS stuff
Yeah, imo if you're in the development scene (and at the level of making Discord bots) learning how to use a terminal based linux OS is a pretty important step. But some people do prefer the easy way.
Not to mention VPSs are expensive
$5/mo is common
You won't find a good server for much less than that. If you do, it's going to be shit
I have an OVHCloud server I rented for $12 a year
(1st year only)
and after that?
what about my laptop that I bought. If I use it for 50 years, then it will cost a dollar a month
If you account for electricity and internet bills I'm not sure that'll be any cheaper
I believe $2.50 a month
Which is honestly fine for 1 vCore and 2 GB of RAM
i did use
Yeah, that's enough for a small-mid sized bot
@discord.slash_command(name='invert', description="🩻 Invert the colors of a user's profile picture" )
async def invert(self, ctx, *, user: Option(discord.Member)):
asset = user.display_avatar.url(size=128)
```
I mean I’m also running some other services too
for reference
it has unmetered traffic
I am getting an error that pfp is a str obj and it cant be callable
I mean I bought one of those cheap Android set top box
Installed Linux on it
Power draw under heavy CPU load is ~7W
If you account for electricity and internet bills
I mean internet is already paid regardless on whether I'm hosting or not , and I'm sure electricity is about less than a dollar.
I mean main concern is reliability tbh
And if you go low power by using ARM like me, well
I'm still not sure a 50 year old laptop would use that little electricity
Kiss your x86_64 CPython packages goodbye
dollar per month.
see breaking changes here https://docs.pycord.dev/en/master/migrating_to_v2.html
v2.0 introduced new Discord features and deprecated some old ones. Part of the redesign involves making application commands and components. These changes include a new Bot class, ui.View, and a ne...
I guess it depends on where you live, but my RPi currently uses about $2-3/mo if I'm seeing things right
3+1 is still cheaper than 4
Right, but I'd rather pay for a more reliable VPS with better hardware and latency.
Well here’s a scenario that I have that probably many of you don’t
I live in an area where international traffic is most served by underwater fiber lines
And these things go into maintenance like 3-4 times a year, which pulls my latency to the Discord voice server way up
i did that
it still just doesnt work
?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.
i did explain above one sec
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: 'str' object is not callable
I am trying to fetch a users profile picture and invert it
You call a str object
but this isthe error I receive
You were already told what is wrong with your code
I tried fixing it but I dont seem to understand what exactly do I fix it wit
.url is already an attribute, not a function that you call with (size=128)
okay, so I remove .url?
Read the docs, .url is a str
Please just read the docs
Or at a dang minimum the hint that your IDE is trying to give you
how do you disable a button with a certain custom id? is that possible? (in a separate command from where the buttons are being sent)
Is it possible with the api to fetch a guild that is public or are websites like discordlookup using other methods to get information on the guild?
.rtfm bot.fetch_guild
discord.ext.bridge.Bot.fetch_guild
discord.ext.bridge.Bot.fetch_guilds
discord.Bot.fetch_guild
discord.Bot.fetch_guilds
discord.ext.bridge.AutoShardedBot.fetch_guild
discord.ext.bridge.AutoShardedBot.fetch_guilds
discord.AutoShardedBot.fetch_guild
discord.AutoShardedBot.fetch_guilds
discord.ext.commands.Bot.fetch_guild
discord.ext.commands.Bot.fetch_guilds
discord.ext.commands.AutoShardedBot.fetch_guild
discord.ext.commands.AutoShardedBot.fetch_guilds
Is this what you are taking about?
Bot.fetch_guild() yes
.rtfm avatar
discord.DefaultAvatar
discord.DefaultAvatar.orange
discord.TeamMember.avatar
discord.TeamMember.default_avatar
discord.TeamMember.display_avatar
discord.ClientUser.avatar
discord.ClientUser.default_avatar
discord.ClientUser.display_avatar
discord.WidgetMember.avatar
discord.WidgetMember.default_avatar
discord.WidgetMember.display_avatar
discord.User.avatar
discord.User.default_avatar
discord.User.display_avatar
discord.Member.avatar
discord.Member.default_avatar
discord.Member.display_avatar
discord.Member.guild_avatar
discord.Webhook.avatar
discord.SyncWebhook.avatar
Quick question.
im using a command, where the user gets a message, with 3 Buttons and ephemeral.
And i want to edit the message and the buttons as soon the user clicks one of them, while still being ephemeral.
Do edit the message i need the message id right?
How would i give the id to a function in a diffrent file?
You wouldn't need the id. You have to use interaction.edit_original_response
(In command callback)
OR
You can also do interaction.message.edit
(In the button callback)
@ornate swan
that makes sense
im using a cuntion outside of the buttoncall back
i can just use the interaction too right?
Wdym by that? Are you saying you call another function in the button callback, and in that function you edit the message?
yes, im calling a function in the callback
You would need to pass interaction while calling it, that's all
Alr
since the 3 buttons im using, are doing pretty much the same think.
allright
makes sense, ty <3
Np 🙃
What is button-formatted messages supposed to mean?
I am guessing it refers to messages with a View attached
Done with your help thread?
Please close your own help thread by using </close:1009144375709814897> with @errant crane.
Traceback (most recent call last):
File "/home/container/.local/lib/python3.10/site-packages/discord/client.py", line 378, in _run_event
await coro(*args, **kwargs)
File "/home/container/cogs/music.py", line 203, in on_wavelink_track_start
await vc.tchannel.send(embed=embed)
File "/home/container/.local/lib/python3.10/site-packages/discord/abc.py", line 1616, in send
data = await state.http.send_message(
File "/home/container/.local/lib/python3.10/site-packages/discord/http.py", line 365, in request
raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access```
is there a way I can get my bot to send a message in the guild this error came from?
Tell the server owner to give your bot permissions
If they do not want to give the bot permissions they don't get to use your bot. ¯_(ツ)_/¯
Oh, you want an error message to show.
You could just try/except the start music function.
You can than respond to the interaction with a message saying you don't have permission.
I use the ```py
@name.error
Question understanding the language python is fairly easy and hard for different individuals but I'm abit confused on python system at the moment that reading all the rules and tips that PyCharm gives me... I don't know where to begin?
Begin what? lol
There's different fields of coding. I only interested of data science or data analytics but I only what to learn the essentials for those fields without wasting time but I don't know where to start cause there different languages.
Im sure Google can answer that
i found this
My idea: A user will add a reaction to a message, is it possible to make the bot send a message in the same channel but in ephemeral?
no, ephemeral message can only come as a response to an interaction
how would you fetch the message with the id of a WebhookMessage?
using the get_message method returns None
use fetch_message
fetch_message doesnt appear to be an attribute of Bot
unless my linter is wrong
The ID is actually the ID of the commands interaction
but it thought it returned WebhookMessage
but im guessing thats for followups
discord.abc.Messageable.fetch_message
discord.PartialMessageable.fetch_message
discord.TextChannel.fetch_message
discord.ext.commands.Context.fetch_message
discord.Member.fetch_message
discord.VoiceChannel.fetch_message
discord.ext.bridge.BridgeExtContext.fetch_message
discord.Thread.fetch_message
discord.Webhook.fetch_message
discord.ext.bridge.BridgeApplicationContext.fetch_message
discord.SyncWebhook.fetch_message
discord.ApplicationContext.fetch_message
discord.User.fetch_message
discord.DMChannel.fetch_message
discord.GroupChannel.fetch_message
riiight
.rtfm WebhookMessage
discord.WebhookMessage.guild
discord.WebhookMessage.id
discord.WebhookMessage.interaction
discord.WebhookMessage.is_system
discord.WebhookMessage.jump_url
discord.WebhookMessage.mention_everyone
discord.WebhookMessage.mentions
discord.WebhookMessage.nonce
discord.WebhookMessage.pin
discord.WebhookMessage.pinned
discord.WebhookMessage.publish
discord.WebhookMessage.raw_channel_mentions
discord.WebhookMessage.raw_mentions
discord.WebhookMessage.raw_role_mentions
discord.WebhookMessage.reactions
discord.WebhookMessage.reference
discord.WebhookMessage.remove_reaction
discord.WebhookMessage.reply
discord.WebhookMessage.role_mentions
discord.WebhookMessage.stickers
got what i was trying to do working 
i had to store the channel and fetch it from cache to fetch the message
yes, can a bot send it in DMs
yes
thanks
Tbh I think just trying it would have been faster than waiting 11 hours for someone to tell you 
i haven't even figured out how to use button 
properly
Good thing we have examples and docs then :)
bad thing ||I cant read docs|| 

Then learning that should probably be step 1
async def Join(ctx):
role_id_togive = 1036062978879004734
member = ctx.message.author
role = ctx.guild.get_role(role_id_togive)
await member.add_roles(role)
await ctx.send("{} Have Been Given The Role `{}`".format(member.mention,role.name))```
My code is not working, I am not sure what to do.
?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.
Nvm, solved it. I just needed to make the J in Join(ctx) lowercase.
How to send the modal's callback message to a specific channel instead of sending it to the channel where the modal was opened?
Hey guys, what's the has_permissions for Managing Nicknames? Is it manage_nicknames or manage_nickname or something else?
Ping on reply btw
noice
Get a channel and send the modal but you have to respond to it?
Some classes are just there to be data containers, this lists them. Unlike models you are allowed to create most of these yourself, even if they can also be used to hold attributes. Nearly all clas...
How do I get my bot to disconnect from a vc? At the moment i am using ```py
ctx.voice_client.disconnect(force=False)
why the hell my bot dosent respond
or print when i send my command
i am using the example
It is literally impossible for us to know unless you show your code
Hi, i have a question, how to create dropdowns with a choice of members? Like this
appreciate it
Is it possible to start an activity (like bobble league) through a bot?
which would allow people to play without nitro
No
.rtfm create_activity
@fervent cradle check if that still works
creating an invite probably works, but then the bot has to join and start the activity for it to work
Hmm nope i dont think that's possible
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix="!")
@bot.command()
async def ping(ctx):
await ctx.send("Pong!")
bot.run("")
bhur
do you know Basic python?
yes?
did you take a look at the Docs and examples?
i fucking copied the example
you try a slash command as a prefix command?
First of all, use codeblocks.
Second, show whatever error you are getting.
^
im not getting any error bruh
And how are you running your command?
!ping
Pong!
Cluster 215: 19.93ms (avg)
Shard 3443: 15.38ms
Node: Ip-10-0-20-29.ec2.internal
720ms
190ms
<t:1674133718:R>
do you have message intents?
yes
By the code you provided you didn't pass intents lol
okay
any idea why Im getting this error since I updated Pycord?
.intents
https://docs.pycord.dev/en/master/intents.html
https://discord.com/developers/docs/topics/gateway#gateway-intents
import discord
from discord.ext import commands
# Get specific intents for fine control
intents = discord.Intents()
intents.emojis = True
intents.guilds = True
intents.messages = True # Required for prefix commands!
...
# Get all non-priveliged intents; this excludes presences, members and message_content
intents = discord.Intents.default()
# Set priveliged intents: these must be enabled on dev portal
intents.members = True
intents.presences = True
intents.message_content = True # Required for prefix commands >= 2.0.0b5
# Get all intents; all intents must be enabled on dev portal.
intents = discord.Intents.all()
# Apply intents when creating your bot
bot = commands.bot(prefix="?", intents=intents)
In version 1.5 comes the introduction of Intents. This is a radical change in how bots are written. An intent basically allows a bot to subscribe to specific buckets of events. The events that corr...
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
shi-
that looks like an error caused due to me
Okay, when can you apply a fix?
i didnt face that when testing. can you show some code to reproduce it?
aah
got it
sure, lemme paste it to pastebin cuz its quite big
can you do a change in your local pycord files and test? ill tell you what to change
sure
you can always uninstall and reinstall pycord to clear these changes out
I know
cool. line 120 at discord/ext/bridge/bot.py
async def invoke(self, ctx: ExtContext | BridgeExtContext):
br_cmd = isinstance(ctx.command, BridgeExtCommand)
if ctx.command is not None:
self.dispatch("command", ctx)
if br_cmd:
self.dispatch("bridge_command", ctx)
try:
if await self.can_run(ctx, call_once=True):
await ctx.command.invoke(ctx)
else:
raise errors.CheckFailure("The global check once functions failed.")
except errors.CommandError as exc:
await ctx.command.dispatch_error(ctx, exc)
else:
self.dispatch("command_completion", ctx)
if br_cmd:
self.dispatch("bridge_command_completion", ctx)
elif ctx.invoked_with:
exc = errors.CommandNotFound(f'Command "{ctx.invoked_with}" is not found')
self.dispatch("command_error", ctx, exc)
if br_cmd:
self.dispatch("bridge_command_error", ctx, exc)
how would i make my bot use 3 shards
How can I either disabled a dropdown, or delete it, if it's in an ephemeral message? (if that's even possible)
The same way you'd disable or remove a dropdown from a message
Then I must be doing something wrong, as I disable the select in the callback, but it ain't disabling 😛
using AutoShardedBot or manunally sharding it?
im not sure what to use
Why do you want 3 specifically?
well i would like to have a set amount just using 3 as an example
Why not just use AutoSharded?
Is it possible for a SlashCommandGroup have a base command e.g. having a /test along with /test subcommand1 and /test subcommand2
you can specify shard id (0 indexed) and shard count (1 indexed) while creating the bot
on my bot it does not seem to work its in 1.5k guilds but still only 1 shard
so you would start 1 instance with 0 and 3
2nd instance with 1 and 3
3rd instance with 2 and 3
Sharding isn't required until 2.5k
i would like to get it done sooner then later
That's what AutoSharded is for, so you don't have to "get it done". It will do it for you when required
at about what amount of guilds will it add another shard
is that true? sharding happens only at startup iirc
I'm currently running my discord bot on an ubuntu server, how would I set it up to be a systemd service? I haven't really used systemd before so I don't really know where to start
Or just use pm2 to run it
?tag botvar
Need to keep track of a variable between functions? No problem!
⚠️ Careful what you name it though, else you might overwrite something ⚠️
Just add it to your commands.Bot or discord.Client instance like so:
bot = commands.Bot(...)
bot.my_variable = 0
async def foo():
bot.my_variable += 1
# In a cog
@commands.command()
async def counter(self,ctx):
await ctx.send("Current Counter is at {}".format(ctx.bot.my_variable))
This also allows you to access this from other cogs/extensions/functions. Anywhere you have access to the bot instance
well i'm trying to keep the uptime of my bot but i want the command in misc, but the code for defining when it went up in main (incase i reload the misc cog, it would be wrong). Is that the right way?
Why wouldn't it be?
you have access to the bot instance using self.bot, so yea you can use bot vars for it
It sounds like you need to learn more about OOP in Python
Because that is a very basic concept
that i clearly haven't been taught
Which is exactly why you need to learn it
So its not possible? I remember that in the obsolete version you could declare a commandgroup using a decorator as with other commands but it seems to be giving me issues here
What sort of "issues"?
well thanks for the help.
It seems like the way to declare a command group is with x = discord.commands.SlashCommandGroup(name="x") and following up the subcommands with @x.command(), which would get me commands like /x a, /x b...
Of course this means I can't name another command simply just /x
In the old version of discord.py you could just declare a command group using a decorator which made creating the base command as trivial as any other command
Now I've tried using @commands.slash_group() to make a command but now I subcommands can't seem to find the name of the slash group defined this way
you cant have a base command for a group anymore
discord limitation
:(

ok thats what i was asking about, thanks
👍
Hi, I need a little help with this line, For some reasonn it only allows me to warn people who has got permission to kick people, If i add "if not" to it then it allows me to warn everyone but anyone can warn people.
sorry what?
You add a check for the kick_members permission, and you're surprised that only people with the kick_members permission can use the command?
Ok I need some assistance with this. As I'm 100% doing something wrong, but cannot figure it out for the life of me...
Why is the following code, not disabling the dropdown/Select? And how can I fix that?
https://gist.github.com/lorddusk/348637224fd66a4b5ac8a73ecb4b39df
Do you not need to edit the message with the disabled select for it to update?
Yea
Wait read wrong
Why are you surprised that the code does exactly what you tell it to do?
You can only warn people with the kick members permission,
And what is user in your command?
The person doing the command
No
oh?
Send the full command
@bot.slash_command(guild_ids = server_ids, name="warn", description = "Warn a user.")
async def warn(ctx, user:discord.Option(discord.Member, description="What user do you want to warn?"), reason:discord.Option(str)):
if user.guild_permissions.kick_members:
embed = discord.Embed(
title= "You were warned",
description= f"{ctx.author.mention} warned {user.mention} \n Reason: {reason}",
color = discord.Color.random()
)
await ctx.respond(embed=embed)
try:
coll.insert_one({"_id":{"guild":user.guild.id, "user_id":user.id}, "count":1})
except pymongo.errors.DuplicateKeyError:
coll.update_one({"_id":{"guild":user.guild.id, "user_id":user.id}}, {"$inc":{f"count":1}})
else:
await ctx.respond("You don't have permission to do that!", ephemeral = True)
Read your code again... what is user in your command?
Ohh, I think i get it, Im using user to define the person i want to warn so its messing with the permission?
You're checking if user has the permission
user is the person you're trying to warn
the code does exactly what you tell it to do
every person can warn a user if that user has kick_members permission 😛
What would i swap user with to check permissions?
Even edit_original_message?
You literally have the answer in your own code
yep
just to be sure, interaction.edit_original_message right?
discord.errors.NotFound: 404 Not Found (error code: 10015): Unknown Webhook
when running self.disabled = True await interaction.edit_original_response(view=self.view)
What if you do self.view.message.edit(view=self.view)?
ayy, that did the trick, thanks!
Cool!
hmm, Ive tried discord.Member and that just stopped the command from working.
ah cool, that means I can also do the same trick to delete the message 😛

my man
change if user.guild_permissions.kick_members:
to if ctx.interaction.user.guild_permissions.kick_members:
(disclaimer, this is from the top of my head, it might not be user anymore)
I think you need to learn basic OOP in Python, you're clearly just guessing your way forward
Mostly, Yes. Been learning python since i was like 14 but i never actually understood it.
Then you need to understand it before making a bot. Pycord is not a beginner friendly library.
Nor is any Discord API wrapper
Ok.
Is it possible to create a command with options that don't require any input, instead the specific option selected will do a specific action? I don't want 3 commands in a group, as they will display as 3 separate commands with a prefix/parent, I want 1 command that can do 3 actions
something like this?
umm yeah but they all require any input
add them optional with "required=false"?
they will still require input when you select it, making them not required will just allow to use the command without selecting them, which I don't really want
Is it possible to use pycord to recieve interactions through an endpoint and HTTP?
Why the first ctx.respond give discord.Interaction Object?
Is always returns an Interaction object
no
Would love to lean on more experienced brains to think of the best way to do this: I'm running a megagame on Discord and have a command for players to create treaties with one another. They can list the nations involved in the treaties using commas and spaces "Federation, Mist" etc. The dream would be to have players able to autocomplete nation names, or even be restricted to only the nations available, but autocomplete can only do the first item of the list obviously. Is there any way to use autocomplete or options for this purpose/what would be the best way?
Thanks! I am reading the docs extensively but my head is spinning 😂
What you could do is have different options
Instead of just one
Each option takes one nation
Mhmmmm. Which could look kinda messy but would basically be text issuing_nation nation1 nation2 etc., and they would just leave blank the slots they don't need?
I'm pretty sure that's possible, although a much better way would be using select menus
Not sure but try discord.Colour.default()
Either just pass in "0x2F3136" or discord.Colour.embed_background("dark")
color=discord.Colour.embed_background"0x2F3136"
Some classes are just there to be data containers, this lists them. Unlike models you are allowed to create most of these yourself, even if they can also be used to hold attributes. Nearly all clas...
It only takes in one of the three arguments : dark, light or amoled
Ignoring exception in on_connect Traceback (most recent call last): File "/home/container/discord/client.py", line 377, in _run_event await coro(*args, **kwargs) File "/home/container/discord/bot.py", line 1164, in on_connect await self.sync_commands() File "/home/container/discord/bot.py", line 729, in sync_commands cmd_guild_ids.extend(cmd.guild_ids) TypeError: 'int' object is not iterable
Does anyone know why tis is poping up
Does modal dialogs applies only to slash commands?
Slash cmd, buttons, select menus etc. Everything that is an interaction
Although you can't send a modal as a response to another modal
Show pip list please
Give me 5 minites because the host is stupid
So according to what you mean is that Modal dialogs, buttons can not be used with prefixed commands
what?
A Modal cannot use with prefix commands
Thanks for the answer, appreciate the service which has been given. 🙂
I was wondering which bot i should subclass, discord.Bot or commands.Bot
which one do you use?
?tag client
discord.Client # just for events
discord.Bot # events + slash/user/msg commands
commands.Bot # above + prefixed commands
bridge.Bot # above + bridge commands (application commands and text commands in one)
Ooh thank you for that,
so bridge.Bot is the best for all?
if you want both yes
anything else is the kinda the same
there is no "best" class. it depends on your functionality. using a wrong class will either lead to feature absence or extra overheads causing poor performance
read
?tag client
discord.Client # just for events
discord.Bot # events + slash/user/msg commands
commands.Bot # above + prefixed commands
bridge.Bot # above + bridge commands (application commands and text commands in one)
discord.Bot(description="Creates an invite for you.")
AttributeError: module 'discord' has no attribute 'Bot' how abt this
?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
discord.Bot(description="Creates an invite for you.")
AttributeError: module 'discord' has no attribute 'Bot'
You have conflicting libraries
Pycord is the only discord library that should be installed
how can i check it?
do you know basic python?
no
Learn first the basic´s of Python...
Line-
slash= SlashCommand(bot, sync_commands=True)
Error-
What the hell are you even trying to do
Then don't expect help here
Syncing commands ☠️
discord.SlashCommand
discord.SlashCommand.after_invoke
discord.SlashCommand.before_invoke
discord.SlashCommand.call_after_hooks
discord.SlashCommand.call_before_hooks
discord.SlashCommand.callback
discord.SlashCommand.can_run
discord.SlashCommand.cog
discord.SlashCommand.cooldown
discord.SlashCommand.copy
discord.SlashCommand.dispatch_error
discord.SlashCommand.error
discord.SlashCommand.full_parent_name
discord.SlashCommand.get_cooldown_retry_after
discord.SlashCommand.has_error_handler
discord.SlashCommand.invoke
discord.SlashCommand.invoke_autocomplete_callback
discord.SlashCommand.is_on_cooldown
discord.SlashCommand.is_subcommand
discord.SlashCommand.mention
Yeah yeah
"A class that implements the protocol for a slash command.
These are not created manually, instead they are created via the decorator or functional interface."
You make no sense
.guide
Read the guides
People get here without basic python knowledge?
I am very sad for everyone trying to answer their questions
I think it's more common for people with no Python knowledge to ask questions here than people who get proper help
unfortunately
I guess it's because most people who actually have enough Python competence also know how to read the docs 
True
What's the proper way to typehint when using get_cog?
class MyCog(commands.Cog):
def __init__(self, bot: MyBot):
...
self.other_cog: OtherCog = self.bot.get_cog('OtherCog')
PyCharm whines because get_cog returns Cog (or None). Is there a pythonic way to overcome this, or is it just best to add a # type: or # noqa annotation to the tail-end?
Hey is it possible to fetch the @bridge.has_permissions(ban_members=True) Error:
Traceback (most recent call last):
File "D:\Dev\Bottesting\venv\Lib\site-packages\discord\ext\commands\bot.py", line 347, in invoke
await ctx.command.invoke(ctx)
File "D:\Dev\Bottesting\venv\Lib\site-packages\discord\ext\commands\core.py", line 942, in invoke
await self.prepare(ctx)
File "D:\Dev\Bottesting\venv\Lib\site-packages\discord\ext\commands\core.py", line 857, in prepare
if not await self.can_run(ctx):
^^^^^^^^^^^^^^^^^^^^^^^
File "D:\Dev\Bottesting\venv\Lib\site-packages\discord\ext\commands\core.py", line 1198, in can_run
return await discord.utils.async_all(predicate(ctx) for predicate in predicates) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\Dev\Bottesting\venv\Lib\site-packages\discord\utils.py", line 699, in async_all
for elem in gen:
File "D:\Dev\Bottesting\venv\Lib\site-packages\discord\ext\commands\core.py", line 1198, in <genexpr>
return await discord.utils.async_all(predicate(ctx) for predicate in predicates) # type: ignore
^^^^^^^^^^^^^^
File "D:\Dev\Bottesting\venv\Lib\site-packages\discord\ext\commands\core.py", line 2138, in predicate
raise MissingPermissions(missing)
discord.ext.commands.errors.MissingPermissions: You are missing Ban Members permission(s) to run this command.```
Just like :
** @commands.Cog.listener()
async def on_application_command_error(self, ctx, error):
if isinstance(error, commands.CheckFailure):
await ctx.respond(f"Nur Admins dürfen diesen Befehl ausführen!", ephemeral=True)
return
await ctx.respond(f"Es ist ein Fehler aufgetreten: ```{error}```", ephemeral=True)
raise error**
Just in Main Method an not in a Cog
the {error} is surroundered by 3 ` at the beginning and the ending
So you want to listen for the error in the main file?
Use @bot.listen() or @bot.event
Yeah i want to make an listener
Guys need some help, is there anyway when using a slash command to add an attachments argurement to add files or no?
cos for some reason you are unable to use a slash command aswell as upload a file
you are
Here's the slash options example.
yea I figured out how, do you know how to read the text file you just uploaded vai the slash cmd
Download the file and read it
how?
.rtfm to_file
it legit don't work I done await file.to_file()
than download it with aiohttp
can you give a code example?
is there no built in function u can do?
in pycord
no
and its not that hard to do by your own
only if you dont know basic python
all good bro I done it using my own way ty for the help tho
and how? ;3
I hope you dont use stuff like "requests"?
Hi, is it possible to check how long a member has been boosting the server for?
Or would I have to store the timestamp in a db
Error: no attribute author
@bot.tree.command(name='join', description='Tells the bot to join the voice channel')
async def join_voice(ctx: SlashContext):
if not ctx.author.voice:
# User not in a voice channel
await ctx.send("You are not in a voice channel.")
return
voice_channel = ctx.author.voice.channel
if ctx.voice_client is not None:
await ctx.voice_client.move_to(voice_channel)
else:
await voice_channel.connect()
await ctx.response.send_message(f"Connected to {voice_channel}")
Ping me 🙂
bot has no attribute tree
Uhm- my slash commands are only working this way
pip list in terminal and show output
Installing Pycord with Replit (only use replit as a last resort) - pycord-replit-install.md
It's there
also, discord.py and pycord are conflicting
The library name is py-cord not pycord
☠️ I forgot everything in 1 year☠️☠️☠️
Why do you need sooo many libraries....
Uninstall all those you dont need
replit auto-install
Dang
It's there storage idm lol
Quick question, does @before_invoke work the same way in Slash CommandGroup as they work with prefixed group?
is there a way to use aliases in a bridge command?