#Basic Pycord Help (Quick Questions Only)
1 messages · Page 13 of 1
just select an existing channel
when you set ur guild to community you have to specify those two
it can either create one for you or select an existing one
not sure if the api will let you do the former
Yeah but that's not how an antinuke should work. In this case i would rather create 2 channels and pull them ids and just set them there
would it be good to make it so if community is set to True but rules and updates channels aren't specified to create ones like discord does?
looking at the api it's not clear if that's actually possible
i wouldn't be surprised if the UI makes separate channel creation requests for that before editing the guild
I was able to make it so the channels will get deleted after guild community is being set to false
why are you even toggling community
1 sec
Well, this can be toggled if u want it or not. it's for extra security. Up to the guild owner
any of those can be enabled / disabled
well there's a bypass
nukers will create channels using guild community
turning on - off will just spam channels inside the guild
which is dumb but sadly this is what happens
there's a very high chance there's a ratelimit on that though
yes but till they get ratelimited.... also imagine nuking with multiple bots
confusion is what they mostly like lol
no, guild-wide ratelimit
well idk but a lot of people tested my bot with it. I was surprised at first idk how they do that
but luckly i found a way to fix it
fair enough i guess
No. the reason why this wont happen is because once u want to enable our bot antinuke it will be required to put it at the top of the roles
then why doesn't the bot just ban the nuker(s)
In case they move it after it won't be the bot fault
How can the bot know if it's a nuker or not
if something doesn't happen
isn't that the entire point of antinuke
scanning actions and determining if someone is acting maliciously
if something happens what the bot will do is just back up everything changed by the non trusted member
yep that's what it does basically
it will also ban the non-trusted member
once something happens by a non trusted member (can be bot) -> ban the non trusted member -> replace everything back
i turned it on. what the bot did was to turn it off then delete the channels
@cyan quail I've done what u told me. Using create_text_channel
nice
How do i get invite link data from on_member_join
not possible
i mean invite link code/owner
You have to query all the invites and see which one increased in count
):
how @tacit night works?
so whats up with pycord sometimes returning truncated log lines
it seems to happen when a rate limit is encountered
im seeing api calls fail, and its not being reported through the framework as an exception
for example, the log line will say its retrying, and then
DELETE https://discord.com/api/v10/channels/.../messages/.../reactions/ave
rify%3A.../... has received
without the error code actually being there
also, when i navigate through my terminal theres some weird display shit going on as if there are ctrl characters in there that it doesnt like
this has been a thing for like.. as long as ive used pycord, which has been idk >6 months
anyone know something about it or?
seems like it ought to be a known issue by now
hm maybe i should post this in #discussion
What?
I've never had any issues like this
it wasnt a big deal at first but im starting to get more users and shit is breaking as a result
should i not rely on the built in rate limiter?
i seem to recall seeing a lot of pycord projects handling rate limiting themselves
Are you logging weird strings with control characters?
not that i am aware of lol
maybe there are weird strings in some of the message contents it prints to debug
perhaps thats the culprit for that bit
im not actually sure if this is just a display bug and the return code would be there if not for this
but also, this problem is correlated with api call failures so id like
expect to see a traceback if i didnt handle an exception its throwing due to rate limiting correctly
but im not
and im only catching Forbidden in that call, not HTTPException
i dont even know what pycord throws if it gives up retrying
id imagine it shouldnt, since the discord gateway just tells it to progessively back off
and yet, these calls never complete
gtg. ping me if u have an idea
No tag localization found.
The has_permissions decorator still works
^ all decorators from ext.commands also work with slash commands
just note these are all internal and won't hide them on discord's end; the user will still be able to see and "run" the command, but the bot will raise CheckFailure as always
you can use the @default_permissions() decorator that, by default, hides the command to those who don't have certain permissions. Using the ext.commands @has_permissions() is gonna make your command visible, but CheckFailure (i think) is gonna be raised when the user doesn't have enough permissions.
I'm trying to deploy my bot using v2.0.1, and I'm getting the following error on startup:
File "/app/.heroku/python/lib/python3.10/site-packages/discord/ext/pages/__init__.py", line 10, in <module>
from .pagination import *
File "/app/.heroku/python/lib/python3.10/site-packages/discord/ext/pages/pagination.py", line 27, in <module>
from discord.ext.bridge import BridgeContext
File "/app/.heroku/python/lib/python3.10/site-packages/discord/ext/bridge/__init__.py", line 26, in <module>
from .bot import *
File "/app/.heroku/python/lib/python3.10/site-packages/discord/ext/bridge/bot.py", line 32, in <module>
from .context import BridgeApplicationContext, BridgeExtContext
File "/app/.heroku/python/lib/python3.10/site-packages/discord/ext/bridge/context.py", line 28, in <module>
from discord.commands import ApplicationContext
File "/app/.heroku/python/lib/python3.10/site-packages/discord/commands/__init__.py", line 26, in <module>
from .context import *
File "/app/.heroku/python/lib/python3.10/site-packages/discord/commands/context.py", line 69, in <module>
class ApplicationContext(discord.abc.Messageable):
File "/app/.heroku/python/lib/python3.10/site-packages/discord/commands/context.py", line 319, in ApplicationContext
@discord.utils.copy_doc(Interaction.edit_original_message)
AttributeError: type object 'Interaction' has no attribute 'edit_original_message'. Did you mean: 'edit_original_response'?```
looks like discord.py
show requirements.txt ty
.
boto3==1.24.36
fastapi==0.78.0
flatdict==4.0.1
markdown==3.3.7
motor==3.0.0
numpy==1.23.1
Pillow==9.2.0
pymongo[srv]==4.2.0
python-dotenv==0.20.0
statcord.py==3.1.0
topggpy==1.4.0
uvicorn==0.18.2
validators==0.20.0
py-cord==2.0.1
topggpy depends on discord.py
(I've been doing this for months)
requirements.txt line 1
discord.py```
yeah discord.py just released 2.0
Very gross that they just had a versionless requirement
requirements.txt line 1
aiohttp>=3.6.0,<3.9.0```
Hey how do I send a message to s specific guild? I want to send the message with the help of my guild id. Can someone help me?
fetch or get the guild and then pick a channel from there
guild = bot.get_guild(id)
guild = await bot.fetch_guild(id)
ah thx
How do i get amount of server bots?
Hey I need a hand here, I looked up pycord docs about select menus and I didn't find anything about subclassing Select to create a custom Select Menu, anyone has a good tutorial regarding creating Select Menus while subclassing Select
How do i use datetime to show a users time in their timezone
edit_original_response
this is definitely a dpy breaking change i saw recently
iterate through guild.members and check for member.bot
you're looking for https://github.com/Pycord-Development/pycord/blob/master/examples/views/dropdown.py
Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - pycord/dropdown.py at master · Pycord-Development/pycord
subclassing isn't a must btw, use whatever method you wish
Yeah Ik i'm doing it to organize my code and make it readable, also to learn stuff and force myself to explore
use discord.utils.format_dt
What?
is there a way to disable the select menu after you select the item? It doesn't work to me for some reason
you have to edit the view again after setting disabled=True
So I need to pass the view to the new class in order to edit it?
kind of
Yeah because I'm using multiple select menus
alternatively you can use View.from_message to recreate the view https://docs.pycord.dev/en/master/api.html#discord.ui.View.from_message
i don't think it'll include the original callbacks though, but it'd be fine if the view will remain disabled
oh wait
nvm, Select has a view attribute already
i.e. self.view
Thanks, I'll check
This is what it's returning (footer)
Huh?
what
no
embed.timestamp = ...
providing a datetime object
or as you said discord.utils.utcnow()
Lmao
embed = discord.Embed(title="hello")
embed.timestamp = discord.utils.utcnow()
await ctx.send(embed=embed)```
But i want it with my footer, i dont want it to take over
How can my bot use another bot slash_command
it can't
@client.command(aliases=["av"])
async def avatar(ctx, member: discord.Member = None):
if not ctx.author.bot:
if member == None:
member = ctx.author
embed = discord.Embed(title=f"", color=0x2F3136)
embed.set_author(name=f"{member}'s Avatar", icon_url=f"{member.avatar_url}")
embed.set_image(url=f"{member.avatar_url}")
await ctx.reply(embed=embed)
``` ok im having an issue with this command
avatar.url
Ok
hey, is there a way to have a callback for paginators to say that for example they cant click on it
oh nevermind
How can i add permissions to slash group? ik that there is default_member_permissions but i cant understand how to use it with groups
you just pass it inside the group definition
nearly
you use permissions with kwargs
like discord.Permissions(administrator=True, manage_roles=True, ban_members=True, ...) and so on
so you just pass in as much as you want there
it finally works. thanks!
allgood
How can i detect when my bot has been added to other guild
b!rtrm pyc on_guild_join
there's event called on_guild_join
where bot 👀 unless i did prefix wrong

press f to pay respects
How do I set permissions for slash cmds?
Using the permissions decorator
The same like prefix command
bot.slash_command(name='test')
async def test(ctx):
if ctx.author.guild_permissions.administrator:
ctx.respond('test')```
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access
what im trying to do: await channel.send("example")
unless I set the bots role to admin this error occurs
Missing Access comes from application commands
Didn't invite the bot with the application.commands scope
async def userinfo(self, ctx, member: discord.Member = None):
if member == None:
member = ctx.author
if member == "":
member = ctx.author
embed = discord.Embed(title="User Information", color=0x8eabf7, timestamp=ctx.message.created_at)
embed.set_thumbnail(url=ctx.guild.icon_url)
embed.add_field(name="User ID", value="**`%s`**" % (member.id), inline=False)
embed.add_field(name="Name", value="**`%s`**" % (member.display_name), inline=False)
embed.add_field(name="Discriminator", value="**`%s`**" % (member.discriminator), inline=False)
embed.add_field(name="Creation Date", value="**`%s`**" % (member.created_at.strftime("%a, %d %B %Y, %I:%M %p")), inline=False)
embed.add_field(name="Bot Check", value="**`%s`**" % (member.bot), inline=False)
embed.set_thumbnail(url=member.avatar_url)
await ctx.send(embed=embed)
just did and it still doenst work
Nothing shows up when i try to run the command does anyone have a idea why
How can i check if 'COMMUNITY' is in before guild features but not in after guild features
do you have a decorator above the func
@commands.hybrid_command(
name="userinfo",
description="Userinfo basically Lol",
aliases=["ui"]
)
@checks.not_blacklisted()
async def userinfo(self, ctx, member: discord.Member = None):
if member == None:
member = ctx.author
if member == "":
member = ctx.author
embed = discord.Embed(title="User Information", color=0x8eabf7, timestamp=ctx.message.created_at)
embed.set_thumbnail(url=ctx.guild.icon_url)
embed.add_field(name="User ID", value="**`%s`**" % (member.id), inline=False)
embed.add_field(name="Name", value="**`%s`**" % (member.display_name), inline=False)
embed.add_field(name="Discriminator", value="**`%s`**" % (member.discriminator), inline=False)
embed.add_field(name="Creation Date", value="**`%s`**" % (member.created_at.strftime("%a, %d %B %Y, %I:%M %p")), inline=False)
embed.add_field(name="Bot Check", value="**`%s`**" % (member.bot), inline=False)
embed.set_thumbnail(url=member.avatar_url)
await ctx.send(embed=embed)
@cyan quail u on ? 😂
whats a hybrid command
?tag example
No tag example found.
Here's the slash perms example.
Also, in my commands (slash), I don't add the ctx : discord.ApplicationContext thing but it still works
what is the reason for adding that?
so that a third person can read your code fluently
I'm so confused
I'm running my bot with slash commands for the first time on another script and it works for like a minute and then the commands just disappear
like this:
show code
so, it's optional?
Idk what is there to show?
yes, but write it down
intents = discord.Intents().default()
setattr(intents, "members", True)
bot = commands.Bot(command_prefix=['qt!', 'QT!'], intents=intents, help_command=None)
and your slash commands?
there's hundreds
each command has this as its decorator
@commands.slash_command(guild_ids=NONE_TYPE)
NONE_TYPE is None
idk theres nothing to show with the slash commands
they all work fine
remove the whole arg or change it two a list of ids
so it worked, Questify had the Slash Commands badge which means it worked
but then after like 30 seconds
i try repeating the last command using the up arrow and now it can't access it anymore
and questify's slash commands badge is gone
same issue with guild_ids=None
and also idk why but my on_ready function is being called like a solid 3 minutes after all the cogs are loaded which makes no sense
without any code i cant help you....
Hi there, I'm making a bot for a client and they keep getting this error which is stopping the bot from actually registering the slash commands
show your
...
which parts do you need since i cant show all of it
most of the slash commands are in cogs folders as well
ight
@commands.slash_command(guild_ids=guildIDs)
@commands.has_role('Staff')
async def create_giveaway(self, ctx: discord.ApplicationContext,
name: Option(str, "The name of the giveaway")):
"""Create a new giveaway (Staff Only) | Usage: esw create_giveaway <name of the giveaway>"""
@commands.slash_command(guild_ids=guildIDs)
@commands.has_role('Staff')
async def announce_giveaway(self, ctx: discord.ApplicationContext,
winners: Option(int, "The number of winners to announce (Default: 1)", required=False, default=1)):
@commands.slash_command(guild_ids=guildIDs)
@commands.has_role('Staff')
async def delete_giveaway(self, ctx: discord.ApplicationContext):
"""Delete the current giveaway (Staff Only) | Usage: /delete_giveaway"""
@commands.slash_command(guild_ids=guildIDs)
@commands.has_role('Staff')
async def csv(self, ctx: discord.ApplicationContext):
"""Returns a CSV(Excel-like file) with the current giveaway's user data (Staff Only) | Usage: /csw"""
ignore the indent with between the two decorators
@dry echo
these are the only ones who uses inputs?
if you mean the options type thing, then yeah
wait nvm
my bad
@commands.slash_command(guild_ids=guildIDs)
async def balance(self, ctx: discord.ApplicationContext,
user: Option(discord.Member, "The user whose balance you want to check.", required=False)=None):
@commands.slash_command(guild_ids=guildIDs)
@commands.has_role('Staff')
async def remove(self, ctx: discord.ApplicationContext,
points: Option(int, "The amount of points to remove."),
user: Option(discord.Member, "The user to remove points from.")):
@commands.slash_command(guild_ids=guildIDs)
@commands.has_role("Staff")
async def add(self, ctx: discord.ApplicationContext,
points: Option(int, "The amount of points to add on."),
user: Option(discord.Member, "The user to give points to.")):
would it be bc of the balance cmd?
ill try now and get my client to run it in a sec
yeah so I tested with a brand new file with just one command from an example and it's doing the same thing..
tokenfile = open('token.txt')
token = tokenfile.read().strip()
tokenfile.close()
bot = discord.Bot(debug_guilds=[763520052484898886]) # specify the guild IDs in debug_guilds
# since global slash commands can take up to an hour to register,
# we need to limit the guilds for testing purposes
@bot.command(description="Sends the bot's latency.") # this decorator makes a slash command
async def ping(ctx): # a slash command will be created with the name "ping"
await ctx.respond(f"Pong! Latency is {bot.latency}")
@bot.event
async def on_ready():
print(f"Logged in » {bot.user.name} | {bot.user.id}")
print("Running")
bot.run(token)
is there some sort of debug mode for py-cord that i can enable
or is this a discord issue
because i'm lost lol
Do you have multiple instances of the bot running?
YE
I do
One that currently is running with text commands and this instance which is on my PC to test slash commands
don't run multiple instances at once
oh, i saw a stackoverflow thing saying it was okay to do so i thought it would be fine
*maybe* before slash commands existed but it generally isn't recommended regardless
Yeah with slash commands it can get really screwed up
i see
I've had this exact issue before, when I had a message command running on the beta version of the bot and not on the prod version
Every time I started the beta, the command would only be able to run once and then it would just disappear
So its highly recommended to use a separate bot during development and the actual bot for production
Yeah I do, I just wanted to test with the main bot because it's a verified bot and a little different to the testing bot
ah you didn't get intents i guess
i have the server members intent, that's it
Then I'd recommend taking the main bot offline for a min or two and just making sure that slash commands works
Fair enough
Should I care at all about a 40ms difference in ping? (Using slash commands.) Comparing a couple of different VPS providers
ehh pretty negligible
dont think it's going to cause a major difference
Is there a API wrapper function that will take a jpeg file and upload it into an embed, I see a method for using a URL but nothing for uploading from the hosted computer.
?tag localfile
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)```
guild.me doesn't work in overwrites after pressing button
Show code
class CreateTicket(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
@discord.ui.button(emoji='📩', label='Создать тикет', style=discord.ButtonStyle.grey, custom_id="create_ticket")
async def create_ticket(self, button: discord.ui.Button, interaction: discord.Interaction):
await interaction.response.send_message(f'Тикет создаётся...', ephemeral=True)
overwrites = {
interaction.guild.default_role: discord.PermissionOverwrite(read_messages=False),
interaction.guild.me: discord.PermissionOverwrite(read_messages=True)
}
ch = await interaction.guild.create_text_channel(name=f'{interaction.user.name}-тикет', overwrites=overwrites,
reason=f'Тикет открыт {interaction.user} (ID: {interaction.user.id})')
What exactly doesnt work?
user doesn't see channel
view_channel=True
bot doesn't add user to channel
Sorry, without the s at the end
Your code only lets the bot see the channel
If you want the user it's interaction.user
ahh
Does this happen for anyone else with
commands.HelpCommand
Is this your full code?
Remove the return
Fixed that part but now it sends
How do I make an AutoCompleteContext
HTTPException: 400 Bad Request (error code: 50006): Cannot send an empty message
but it did send hi
What is self.context?
Have you defined it or is it form the super()
Try to send the string
ctx
super()
Send the string then
I still get the same thing
idk much about the help commands sorry
you should return the value to be sent I believe
yeah youre right!
how can i start a game activity like chess in vc from pycord??
|coro|
A shortcut method that creates an instant activity invite.
You must have the :attr:`~discord.Permissions.start_embedded_activities` permission to
do this.
Parameters
------------
activity: Union[:class:`discord.EmbeddedActivity`, :class:`int`]
The activity to create an invite for which can be an application id as well.
max_age: :class:`int`
How long the invite should last in seconds. If it's 0 then the invite
doesn't expire. Defaults to ``0``.
max_uses: :class:`int`
How many uses the invite could be used for. If it's 0 then there
are unlimited uses. Defaults to ``0``.
temporary: :class:`bool`
Denotes that the invite grants temporary membership
(i.e. they get kicked after they disconnect). Defaults to ``False``.
unique: :class:`bool`
Indicates if a unique invite URL should be created. Defaults to True.
If this is set to ``False`` then it will return a previously created
invite.
reason: Optional[:class:`str`]
The reason for creating this invite. Shows up on the audit log.
Raises
-------
TypeError
If the activity is not a valid activity or application id.
~discord.HTTPException
Invite creation failed.
Returns
--------
:class:`~discord.Invite`
The invite that was created.```
await voice_channel.create_activity_invite(discord.EmbeddedActivity(...))
remember discord wont verify bots that give access to embedded activities
why?
#697236247739105340 message
i do think this statement is odd bc there's one bot thats verified and its entire thing is that it gives access to activities
How to check if the bot is tagged?
you mean in a normal message?
Hey Guys what's the latest version of Pycord?
just check if the bot mention is in the message content (<@id> and <@!id>)
how can i check ping and bot uptime
for uptime just store the current time when the bot starts
and compare to later time
#library-updates
The bot’s ID?
Yes
Alright, thankyou!
Hey, so I'm moving my bot to slash commands but I want users to know about this change so I need to keep it so it can still read messages beginning with the command prefix.
I have the server members intent which is fine but the message content intent I don't. Do I need to enable the message_content intent manually for it to work?
intents = discord.Intents().default()
intents.members = True
# intents.message_content = True
bot = commands.Bot(command_prefix=['qt!', 'QT!'], intents=intents, help_command=None)
Idk because I'm pretty sure I tried enabling it yesterday but an error occured saying I don't have access to the intent
yeah you'd need message content intents
you can also downgrade to api v9
#library-updates message
Ah ok
yeah
so if i switch to api v9 for now do i need to switch back to v10 on the 1st of september or will it still work fine
if discord hasn't granted you message_content and your bot's in over 100 servers, then no it will not work
gotcha
how can i send message to specific channel
create channel obj and then channel.send() 
what
wtf
so my bot is working, the slash commands are there but all of them apart from the ones with slash command groups ??
is it because they take a while to load?
My bot randomly stopped responding to commands. Has anything changed about the Discord API? When I first installed Py-cord version 2.0.1, everything worked just fine. Yesterday it completely stopped replying to commands. Even the old version, the exact one that worked two days ago.
they're literally not showing at all its been like 10 minutes
this is one of them
main.py
bot.groups = Placeholder()
bot.groups.completions = SlashCommandGroup("completions", "View Individual Quest Completions")
def setup(bot):
class Overview(commands.Cog):
completions = bot.groups.completions
@completions.command(name="general", guild_ids=NONE_TYPE)
async def general_completions(self, ctx: discord.ApplicationContext,
username: Option(str, "A valid Minecraft username or UUID", default="", required=False):
"""View General individual quest completions"""
await getOverview(self.bot, ctx, "General", username, mode="completions")
Do you have tried it from another IP or with another token?
I've tried both.
wait im dumb i think
nvm
Indeed, something unexpected changed.
Now I've got a new problem: which intent do I need to enable to create a channel? I don't want to enable all of them, so it doesn't receive tons of information it doesn't need.
It's a private channel, and it's trying to add specific users to it.
just read through https://docs.pycord.dev/en/master/api.html#intents
message_content intent?
Yes, and I don't know when it has changed, and why it stopped working overnight.
I can't find what I'm looking for on that page.
what are you looking for then
if you're trying to work with guilds then surely you want the guilds intent
I've got the guilds intent enabled.
then what's the issue
Traceback (most recent call last):
File "/home/whiskey/.local/lib/python3.8/site-packages/discord/ext/commands/core.py", line 184, in wrapped
ret = await coro(*args, **kwargs)
File "/home/whiskey/Desktop/0.37/cogs/dungeons.py", line 65, in enter_dungeon
dungeon_channel = await cat.create_text_channel(name=dungeon[1] + " - " + ctx.author.name, overwrites=overwrites)
File "/home/whiskey/.local/lib/python3.8/site-packages/discord/channel.py", line 2077, in create_text_channel
return await self.guild.create_text_channel(name, category=self, **options)
File "/home/whiskey/.local/lib/python3.8/site-packages/discord/guild.py", line 1205, in create_text_channel
data = await self._create_channel(
File "/home/whiskey/.local/lib/python3.8/site-packages/discord/guild.py", line 1086, in _create_channel
"id": target.id,
AttributeError: 'NoneType' object has no attribute 'id'
just as a test, can you enable the members intent?
I've found this, but I don't want to enable strictly all intents.
I've already got the members intent enabled.
messages=True, message_content=True, members=True, typing=False, presences=False, guilds=True, reactions=True
can you show the code that triggered the error
or rather, show the overwrites object you passed in
overwrites = {
ctx.guild.default_role: discord.PermissionOverwrite(read_messages=False),
bot_role: discord.PermissionOverwrite(read_messages=True),
ctx.author: discord.PermissionOverwrite(read_messages=True),
ctx.guild.owner: discord.PermissionOverwrite(read_messages=True)
}```
It used to work.
can you show what happens if you print all the keys there?
at least one of them resolved to None
i'm porting my bot over from using psycopg2 to asyncpg so it runs faster - does asyncpg not require committing changes? my connection object doesn't have a .commit method so
That was correct, I changed the role name to the new one, and it works again.
I agree with that, but isn't the role id different if the bot is in a different server?
thank you! so i should probably wrap all my queries and stuff with the async with conn.transaction() then
fair enough, but guild has a bot_role attribute i think anyway
very much still getting the hang of asyncio - it's very confusing compared to everything else i've done in python lol
guild.self_role
do note this isn't guaranteed to exist either though
e.g. someone invites the bot without permissions=...
may be best to validate that all the roles exist before putting it into overwrites (or conversely remove all None keys after)
Does guild.self_role return None if it doesn't exist?
yes
Thanks.
this is the func i'm using to create my db pool - the if/else is so i can run the db locally when i'm changing stuff on my pc - how do i make it so my 'conn' var is visible to my commands outside of create_db_pool itself? am i missing something really basic here
Global variable. 🤔
I created the connection globally, outside any function, and I can use it anywhere.
oh right hahaha
i sort of thought having the variable inside a function like this made it less resource intensive
i have this down at the bottom of my fle
You can create a global variable within a function too.
or return it and set it as a bot attribute?
so something like this?
i also read in the docs that putting my db queries outside of a .transaction thingy means they just autocommit - what's the advantage of committing with the async with bot.db.transaction() then?
Hey I want to use discord.ext.bridge for my commands but I have @commands.has_permission() in my code. How do I use has_permission with .bridge?
Can someone help me?
does it not work with bridge?
no
My Code:
@bridge.has_permissions(administrator=True)
Error:
AttributeError: module 'discord.ext.bridge' has no attribute 'has_permissions'
But in the guide it says that bridge can do everything that commands can do
So thats why Im wondering if I did something wrong.
what if you just do @commands.has_permission
I needed to make my commands all lowercase and now It works with
@client.bridge_command()
@commands.has_permissions()
Buts thats something thats wrong in the guide
I think Im going to add that later
nice
from bot import Bot
import discord
from discord.ext import commands
from discord.ext.tasks import loop
class Notifier(Cog):
def __init__(self, bot: Bot) -> None:
super().__init__()
self.bot = bot
self.test.start()
@loop(minutes=30)
async def test(self):
print("test")
def setup(bot):
bot.add_cog(Notifier(bot))```
The cog loads fine according to console but nothing loads and it doesn't print anything
All other cogs work fine with commands and what nots. Just this one doesn't load
add store=False to load_extension
Ok now I have a different problem.
I can send the command with the helps of /
and it sends the message
but I get an error that the Application cant react
you need to use ctx.respond for slash commands
this is the code
yes change it to ctx.respond
ok do I need to do that with every message that is send from a command now?
yes
Perfect! Thanks for the help 🙂
Hey, I want to register a command for one guild only, but it gets registert in every guild. Is there anything wrong with it?
it's guild_ids
not guilds_ids

If I simply have a discord.User (e.g. from an on_user_update event), what's the best way to ban them?
guild = await bot.fetch_guild(guild_id)
await guild.ban(user.id)
i was wondering how i can make a group command in cogs
group slash command that is
nvm i manually used class
Thanks! Wish the event had the guild context, but I suppose that'll have to do 🙂
You're welcome
I'm having trouble tagging a role. I send the role ID in a message in the angle brackets like this <@&role_id> but the role does not get tagged (I don't do it within an embed).
It does result in the role name getting displayed, so I know the ID is correct, it just doesn't tag users with that role.
Possible to hide Slash commands completly for users?
If it's in a webhook (which it will be for slash commands or interaction responses) you need to adjust the allowed_mentions
@commands.has_permissions
Use @commands.has_permissions
Thanks!
@commands.has_permissions(administrator=True)
I'm not finding such a parameter for the respond function.
how to make a message about a new person who entered the server from the bot's discord be written to a specific channel welcome on all servers but not by id channel
Ah thanks! got it working!
you can get the channel with discord.utils.get(guild.channels, name=channel_name)
Im trying to handle the error for discord.errors.CheckFailure, but when implementing the following code, it still shows the exception. How can I get it to not raise any exceptions?
@bot.check
async def checkBlacklisted(ctx):
if not isNotBlacklisted(ctx):
await HandleBlacklistError(ctx)
return False
return True
@bot.event
async def on_command_error(ctx, error):
pass
is the timeout for views reset after an interaction?
And if yes, how can I change that?
update: I was able to make it work. It wasnt "on_command_error", it was "on_application_command_error"
Is there some sort of way to catch errors with failed connection?
In pycord
like a on_error for on_ready or on_connection?
In NodeJS client.login("token")---
.catch(err() => does the thing.
look at the message above
try:
bot.run("defintely a real token.jpeg")
except e as Exception:
print(f"didn't work and raised {e}")
Oh yeah, forgot try exists.
Thanks, this works.
np
I don't think on_command_error would work with my example.
are there any good tutorials for working with asyncpg and pycord?? i just cannot figure out how it works at all lol
there is an on_disconnect if that would help you
search it with discord.py but they should be similar enough and be aware of changes
it's not connected so how does it disconnect
You don't need pycord specific examples, just need to know how to use it with python
If the connection fails for whatever reasons, how would the on_disconnect work?
Nope, I believe that there is a name field which effectively functions as the title of the field
so it's name
Yep
on_disconnect is fired for various errors such as HTTPException, GatewayNotFound and ConnectionClosed; just override it in your bot's class
or if you're not subclassing, @bot.event
Guess I can implement this too then I.g
Im using these two files and the second file won't work when i ping, but there is no error
what does this error means? ```py
Ignoring exception in on_connect
Traceback (most recent call last):
File "C:\Users\danie\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 382, in _run_event
await coro(*args, **kwargs)
File "C:\Users\danie\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 1041, in on_connect
await self.sync_commands()
File "C:\Users\danie\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 628, in sync_commands
registered_commands = await self.register_commands(
File "C:\Users\danie\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 473, in register_commands
desynced = await self.get_desynced_commands(guild_id=guild_id, prefetched=prefetched_commands)
File "C:\Users\danie\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 321, in get_desynced_commands
elif _check_command(cmd, match):
File "C:\Users\danie\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 256, in _check_command
as_dict = cmd.to_dict()
File "C:\Users\danie\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 765, in to_dict
"options": [o.to_dict() for o in self.options],
File "C:\Users\danie\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 765, in <listcomp>
"options": [o.to_dict() for o in self.options],
File "C:\Users\danie\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\options.py", line 246, in to_dict
"type": self.input_type.value,
AttributeError: 'NoneType' object has no attribute 'value'
how to make a check in the select menu, what exactly was selected by the user? To give out a specific role
That'll be under interaction.data
It means that somewhere, you didn't specify the input_type for a slash command
Please read the guide on creating cogs at https://guide.pycord.dev/popular-topics/cogs. It will tell you how to put your bot's code in multiple files
not as far as I know
well... the bot has to be in the server at the very minimum
the best you could do is manually grab the emote and upload it to a private server with the bot or something
File "/home/container/.local/lib/python3.9/site-packages/discord/client.py", line 382, in _run_event
await coro(*args, **kwargs)
File "/home/container/.local/lib/python3.9/site-packages/discord/bot.py", line 1041, in on_connect
await self.sync_commands()
File "/home/container/.local/lib/python3.9/site-packages/discord/bot.py", line 643, in sync_commands
registered_guild_commands[guild_id] = await self.register_commands(
File "/home/container/.local/lib/python3.9/site-packages/discord/bot.py", line 517, 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 517, 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 765, 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 765, 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 246, in to_dict
"type": self.input_type.value,
AttributeError: 'NoneType' object has no attribute 'value'
Esports Wales Bot#3449 has connected in Discord!```
what's your new code
uhhh
it'd have to be an actual emoji
you can't just throw images into description
no
is there a particular reason you're trying to use an emoji the bot can't access?
surely you could just upload it yourself
anyone getting AttributeError: 'Object' object has no attribute 'get_thread' when making a thread? either from a message or not
if you see it on your client you can usually just right click it and open the image
show code and full error
just a stub atm
async def post(channel):
'''A'''
# empty
question = await pop()
if question:
await channel.create_thread(name=question, auto_archive_duration=60 * 24)
else:
# role mention
await channel.send('I am out of questions')
Unhandled exception in internal background task 'post_question'.
Traceback (most recent call last):
File "/Users/kyle/Code/nexbot/.venv/lib/python3.10/site-packages/discord/ext/tasks/__init__.py", line 176, in _loop
await self.coro(*args, **kwargs)
File "/Users/kyle/Code/nexbot/bot.py", line 31, in post_question
await post(channel)
File "/Users/kyle/Code/nexbot/library/questions.py", line 28, in post
await channel.create_thread(name=question, auto_archive_duration=60 * 24)
File "/Users/kyle/Code/nexbot/.venv/lib/python3.10/site-packages/discord/channel.py", line 799, in create_thread
return Thread(guild=self.guild, state=self._state, data=data)
File "/Users/kyle/Code/nexbot/.venv/lib/python3.10/site-packages/discord/threads.py", line 160, in __init__
self._from_data(data)
File "/Users/kyle/Code/nexbot/.venv/lib/python3.10/site-packages/discord/threads.py", line 190, in _from_data
if thread := self.guild.get_thread(self.id) and data.pop("_invoke_flag", False):
AttributeError: 'Object' object has no attribute 'get_thread'
do you have the guild's intent enabled?
guild typically fallsback on discord.Object if it wasn't recieved for some reason
the server members intent?
so i didn't pass anything to the intents property in construction so that would use the default intents?
sec
prints <Object id=255161337116622850>
possible bug is im using the channel straight from a bot.fetch_channel() call and not via a guild
@tasks.loop(hours=24)
async def post_question():
'''A'''
snowflake = 941697109227356180
channel = await bot.fetch_channel(snowflake)
print(channel.guild)
await post(channel)
strictly speaking that shouldn't have an effect but yeah try get_channel without the await
I am facing into slash commands not showing up.
I Imported with the applications.command flag and the cog file works on a different bot...
hmm, anyone knows what shit has to be turned on so commands show up. I doubt that I am missing out on anything.
import discord
from discord import Option, OptionChoice
from discord.commands import slash_command
from discord.ext import commands
class Responsive(commands.Cog):
def __init__(self, bot):
self.bot = bot
@slash_command(guild_ids=get.config("gid"), description="Runtime Information")
async def testv(self, ctx):
await ctx.respond('test')
def setup(bot):
bot.add_cog(Responsive(bot))
this is the slash command
"loaded via" via
for filename in listdir("./cogs"):
if filename.endswith(".py"):
bot.load_extension(f"cogs.{filename[:-3]}")
solved it by just putting a sleep() at the beginning of the task loop. i think it was just starting to early before the cache was ready
ty
You could wait for the bot to be ready before starting the loop
@post_question.before_loop
async def ready_before_loop()
await bot.wait_until_ready()
That will only run before the first iteration iirc
It don't make too much sense
You need to put the code in a class and add a setup function
Still confusing, im new to pycord
I dont know much about pycord
Functions and classes are python things, not just pycord things
@commands.slash_command(guild_ids=guildIDs)
async def balance(self, ctx: discord.ApplicationContext,
user: Option(discord.Member, "The user whose balance you want to check.", required=False, default=None)):
@commands.slash_command(guild_ids=guildIDs)
@commands.has_role('Staff')
async def remove(self, ctx: discord.ApplicationContext,
points: Option(int, "The amount of points to remove."),
user: Option(discord.Member, "The user to remove points from.")):
@commands.slash_command(guild_ids=guildIDs)
@commands.has_role("Staff")
async def add(self, ctx: discord.ApplicationContext,
points: Option(int, "The amount of points to add on."),
user: Option(discord.Member, "The user to give points to.")):
#998272089343668364 message
everything here except balanxe which was changed as above
Ive never heard of them
How do you do slash commands again
In the prefix section
I would recommend learning them then
?tag learnpython
We're glad to help where we can, but come with at least a basic understanding of Python.
Official Beginner's Guide: https://wiki.python.org/moin/BeginnersGuide
Official Tutorial: https://docs.python.org/3/tutorial/
Shortcuts:
https://wiki.python.org/moin/BeginnersGuide/NonProgrammers
https://wiki.python.org/moin/BeginnersGuide/Programmers
Learn Python:
https://automatetheboringstuff.com/ (for complete beginners to programming)
https://learnxinyminutes.com/docs/python3/ (for people who know programming already)
https://docs.python.org/3/tutorial/ (official tutorial)
http://python.swaroopch.com/ (useful book)
http://www.codeabbey.com/ (exercises for beginners)
just add @bot.slash_commands as the decorator
or @commands.slash_command if its cogd
cogs*
Ok i got it working thanks
hey guys so i was trying to add bool paramater
async def join(self, ctx: discord.ApplicationContext, button_enabled: Option(bool)):
i also tried buttton_disabled: bool but it ownt show up
Hello, whats wrong with the code?
modal = ticket_modal(title="Question")
await interaction.response.send_message(modal)
Error:
TypeError: Modal.__init__() missing 1 required keyword-only argument: 'title'
Discord issue:
<load.ticketsystem.ticket_modal object at 0x00000143C5C2E440>
did you pass in the kwargs in the classes' super()?
class ticket_modal(Modal):
def __init__(self, **kwargs):
super().__init__(**kwargs)
...
ye
class ticket_modal(discord.ui.Modal):
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
try taking out *args
okay
no.. ```Py
super().init(**kwargs)
TypeError: Modal.init() missing 1 required keyword-only argument: 'title'
i restarted vsc, why is this happening
could you try defining the title in the super()
instead of when initializing the class
okay
super().__init__(title="Question", *args, **kwargs)
TypeError: discord.ui.modal.Modal.__init__() got multiple values for keyword argument 'title'
```Mhmmm.. :((
needs help
did you take out the title parameter in the class initialization
Ups no this is the error:
raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In components.0.components.0: Value of field "type" must be one of (2, 3, 5, 6, 7, 8).
what paramater
Can group commands have parameters
what is a group command
thanks that's nicer
Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - pycord/slash_groups.py at master · Pycord-Development/pycord
but i figured it out
i just made it normal then put it back and i fixed itself
but another questionnow how do i make button not timeout i but it in @discord.ui.button but it said it waas unexpected
Here's the persistent example.
oh thanks
idk why but with some of my slash commands that have an attachment and a view that disappears 5 minutes after the command is sent, shortly after the images are disappearing from the api resulting in them not loading
and sometimes its fine
is the command response ephemeral
is there a way to reload cogs with the use of slash commands?
Hey I want to use PostgreSQL as my database. What libary should I use to work with psql?
asyncpg would be a decent choice
reload_extension, though your mileage may vary when it comes to updating the behaviour
https://docs.pycord.dev/en/master/api.html#discord.Bot.reload_extension
Ok thx I didnt find anything in the guide so I asked here. Thx
no
when i start my bot sometimes it just doesnt reply to slash commands for like 10 seconds to a minute
is that discord fault
I recommend sqlalchemy
is discord.ApplicationContext.send_response() the same as discord.ApplicationContext.respond() ?
Here's the context menus example.
So when getting user that clicked button do I put in button decorator interaction.user
Or is that person that caused button to be sent
trying to clean up my main.py by porting a load of my stuff to cogs - i'm quite new to using classes and stuff. why is my emoji_catch func being treated as undefined in the listener just below its definition?
ah - i think i fixed it by changing to await Emoji.emoji_catch
please forgive my spaghetti code lol
You use it in your code, not the decorator
sqlalchemy + asyncpg
Like in the command function
Idk what you mean
anyone know why i'm getting this ??
tried changing it to an f-string like this
now i get this instead
Idk what you mean
Why would you put interaction.user in the decorator
I remember seeing a screenshot where you could pass multiple values to an argument directly into a slash command. Anyone know if that's an actual thing, or mockup/future functionality? Couldn't find any examples that used it
e.g. /mycmd opt1: A, B and both A and B were accessible in a list or something.
I really want that but for mentions
this doesn't exist yet as far as i'm aware, but i wouldn't be too surprised if it was planned
or alternatively because this is such a popular request people were happily making mockups already
it might have also been them just using a string option since you can still technically mention and such in those, then parse it yourself after
The screenshot was an example where two autocomplete options were added like you would on a tag cloud. But if it's not a real thing, then no sense trying to dig it up. heh
Would definitely be great to be able to pass multiple arguments, though. Hopefully in the future, as you said.
How can I send a pagination command to a specific channel that wasn't in the interaction or context of where the user initiated the command?
channel.send() ??
hmmm not sure how to make channel.send work with pagination. This is the command I am sending await paginator.send(target=channel) Where channel is a text channel object
oh i see
you could send a message into another channel grab the object and pass it in reference or target ig
thanks, I'll try something like that... seems like there should be a more straight forward way for it.
Quick question. I am starting to learn pyCord, but it seems that even the quickstart for slash commands is out of date, or at least the commands are not functioning as intended for me. Is this a known issue, or do I have an issue with my library install?
For example bot = discord.Bot() doesn't work. Looking around, I tried bot = commands.Bot, and while I can get the on_ready event to trigger, I can't seem to get any @bot.command() to function
how can I set timeout to none in an View class
view = View(timeout=None)
for non persistent views
class myview(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
and thats how u set timeout to None in a persistent view
for slash commands, use @bot.slash_command. and i think @bot.command is mainly for prefixed commands, not slash commands. If you need some examples to work with, there are some examples in the github repo (https://github.com/Pycord-Development/pycord/tree/master/examples/app_commands).
hi I tried makin a reload command for cogs within a slash command but apparently it only works with prefixed commands, is there any way to use bot.reload_extension in slash commands?
hallo can a bot read the content of a message the user replied to with the bot's prefix? if so how?
it'd also be helpful if it could find and read the latest message in chat, excluding the command message. i'm trying to make a translation thingy btw
here's an example of how it works
you can use slash_command and command interchangeably, there's a bridge extension plug inside the base py-cord module
its happening because i've either downgraded to v9 api or because i've transitioned from saving files and then giving the location of it to discord.File to just loading the image from memory
you can read the last message with https://docs.pycord.dev/en/master/api.html#discord.TextChannel.history and break the loop if message.author != bot.user
as for this part, you probably can via applicationContext fiddling https://docs.pycord.dev/en/master/api.html#applicationcontext
just gotta dive deep into the attribute bog to find the exact thing you're looking for
oh it wouldn't read it if the message above was sent by the same person, right? it could instead see if the message starts with its prefix
i'm having problems understanding your request
it would be best if you wrote an example of what's happening in the chat
User A: bonjour
User B: /translate command on the previous message
Bot: "Hello"
like this
as long as the user B uses "reply" in his command, it should be relatively easy to find the initial message
pretty much. have it default to the message above if the user is not replying to another message if possible
if he does not and you want to look for the previous message
then you want to take ctx.message.id
and do the for loop
and check for message.id == the previous message variable
and when it's true, you take the next message in the list and translate it
you can get message id via Bot.get_message(id)
https://docs.pycord.dev/en/master/api.html#discord.Bot.get_message
sometimes that doesn't work and you have to use textchannel.fetch_message(id)
if you want it to work both ways, you'd need to do an if check
and check if context has a reply to somebody attribute
yeah that'd work. the arguments taken can be changed with it too i assume. for example, if the user is not replying to a message, take a quoted text argument as the string to translate, then the source and destination languages
the world is your oyster
I have error like this
``` when i try run modal by select menus
Modal is runing by this code:
```await interaction.response.send_message(viev=Modalconfident())```
Someone know why?
i figured out the argument priority i want, that being the input text, output language, and input language, all being optional. though i can't wrap my head around detecting if only language arguments were passed. would it be smarter (or the only possible option) to have it skip the text if a dot or some other character is passed in its place?
You have to enter a title value for your value
where? I know how to read error. When i put like this await interaction.response.send_message(viev=Modalconfident(title="test")) erorr says i can't put argument's there
in your super()
working thx
This sounds like a great use case for Message context commands cc: @nocturne canopy
https://guide.pycord.dev/interactions/Application-Commands/context-menus
What is the command to see how all the Discord.colors look in discord?
i was trying to avoid slash commands as i don't fully understand them yet but i'll be forced to use them at some point so i'll take my shot at it now
context menu is not really slash
they work on mobile also, right?
@bot.message_command(name="Translate")
async def get_message_id(ctx, message: discord.Message):
await ctx.respond(translate(message.content))
this is boilerplate for your stuff
just create the translate function
i should've mentioned i'm using googletrans
doesn't really matter
this is just boilerplate to take the message and return the result of translation upon it
whatever happens in the function has no bearing on the workings of this
so you mean putting the logic in that new function
just use this
btw
if you want the translation to be visible only to the person who used the command
which, i assume, would ease the flow of the dialogue
use await ctx.respond(translate(message.content), ephemeral=True)
ephemeral makes the message be only visible to the person who called the command
I'm getting "This Interaction Failed" but I actually edit the message with a new view and change the content. How could I fix this without sending another message? (I've also tried to send a new message with the view but that won't work)
How are you editing the message
interaction.response.edit_message() might work
It's fixed.
Yeah I figured, and it does work
Great
Do you guys have any ideas on how to hide some data within a message
pretty much, i have a persistent view which needs to know the id of something so that it can get the data from the database when the user responds
Now, if the bot hasn't been rebooted yet, I can just pass the data in when making the view so it doesn't have to query the db
But otherwise, I need to know the unique ID so that I can get it from the db
So are there any ways to hide that within a message?
I am facing into slash commands not showing up.
I Invited with the applications.command flag and the cog file works on a different bot...
hmm, anyone knows what shit has to be turned on so commands show up. I doubt that I am missing out on anything.
import discord
from discord import Option, OptionChoice
from discord.commands import slash_command
from discord.ext import commands
class Responsive(commands.Cog):
def __init__(self, bot):
self.bot = bot
@slash_command(guild_ids=get.config("gid"), description="Runtime Information")
async def testv(self, ctx):
await ctx.respond('test')
def setup(bot):
bot.add_cog(Responsive(bot))
this is the slash command
"loaded via" via
for filename in listdir("./cogs"):
if filename.endswith(".py"):
bot.load_extension(f"cogs.{filename[:-3]}")
what is the py-cord version?
2.0.1
Try using @discord.slash_command(...) instead of @discord.commands.slash_command(...)
add store=False to load_extension
Hold on, where is get defined?
get?
You wrote this:
@slash_command(guild_ids=get.config("gid"), description="Runtime Information")
So where is get.config defined
I am using @safe inlet_command which works in a different project.
from p_modules import get
from p_modules.graphical import msglist
from p_modules.utilities import logger
I added it ^
Is that in the same file as the Responsive class?
Yep.
Ok good
JUst left it away from the example because it looks weird.
But I would recommend just adding store=False to load_extension because it also prevents other bugs from being overlooked
Still didn't fix anything :/
Did it cause any errors to be raised?
nope
Also changed guild_ids, in this case: guild_ids=[123456790]
123456790 is the server ID
Try adding this to the Responsive class:
@commands.Cog.listener()
async def on_ready(self):
print("Responsive cog is online")
Alright
this will check to see if the cog is even loaded
yep it prints
Responsive cog is online
Are you sure that you're running the command in the correct guild?
It still doesn't appear.
I am sure I followed everything.
Invited bot with bots and application.commands and (administrator) flag.
channel allows application commands.
I am in only 3 guilds lmao
this, my server I am testing it and a different server.
Ok
and the guild I run it from has the bot + i checked the guild id and it equals to it.
Try kicking and reinviting the bot to see if that does anything
did it a lot
Ok
and then i reinivited with all the necessary flags (bots, application.commands) and I gave it administrator flag.
I’ve needed this before; I just added the identifier into the footer of the embed
Oh alright thanks
The only other way I could see it working is if you saved a reference to the message/interaction internally
Yeah, except I don't really want to do that so...
I think I'm just not gonna make it a persistent view
So I guess my problem seems to be weird
I gave my friend the token who has a pycord bot and his slash commands appear on my bot..
Well on my site, nothing works... hmm
That's strange
the get also works, i am printing what its returning [9129492481]
isn't this the point of custom_id
Why not use the message id?
im trying to catch slash commands from bots but idk how to
nothing is printed on the console
what is .listen?
you can say a replacement for client.event
from other bots?
yeah
not possible
why?
because interactions are only between the client and discord
they aren't broadcast to everyone
so i can get the interaction from message of the bot right as my bot is private bot
messages themselves don't contain interaction data
message.interaction?
that indeed exists, however if im not mistaken that isn't actually from the message and instead compiled elsewhere
let me try
my mistake, it is a part of the message; you could use message.interaction.data
but regarding command info, it will only include the command name
I don't really want to store it in the database
Also, I realized I don't really need the view to be persistent so I just decided not to make it persistent
and what abt params?
nop
oof
hey guys! is there a specific indent to getting a channel object from a guild object? I'm using intents = discord.Intents.guilds rn
would await self.client.get_channel(id).send(embed=embed)
work
You don't need any intents for getting channel objects
Hmm it should I would think assuming id isn't none
its None though
Does it error?
Are you sure that id is a valid channel id?
it may not be cached, try guild.fetch_channel
guild.fetch_channel or would client.fetch_channel work too?
yepp
I don't think there's a client.fetch_channel
Hmmmm. Wouldn’t it just be relaxing get_ channel with fetch_channel ?
does this look right
ah kk
does pycord have modals i cant find example
yes
Here's the modal dialogs example.
when i register a command in a cog with @commands.command(), is that a prefixed command or a slash command? or both?
prefix
how do i make them slash commands? is that possible?
@safe inlet_command()
Is just slash commands in cogs
ahhhhh
i'm looking at the docs for cogs - no mention made of slash commands
it just says "Every command is marked with the commands.command() decorator."
Here's the slash cog example.
@celest lichen try this example ^
thank you :)
Is it possible to use buttons within ephemeral messages?
Cuz I keep getting an interaction failed error on Discord's end
Alright thanks for the confirmation
Need some code?
Yes please
Wait a min
@slash_command()
async def foo(self, ctx) -> discord.Embed:
embed = discord.Embed() #your stuff
await ctx.respond(embed=embed, view=MyClass(), ephemeral=True)
class MyClass(discord.ui.View):
def __init__(self, bot):
super().__init__(timeout=None)
@discord.ui.button(label="Idk", style=discord.ButtonStyle.red)
async def callback(self, button: discord.ui.Button, interaction: discord.Interaction):
embed = discord.Embed(title=f"blabla", color=self.embed_color)
embed.set_footer(text=f"ID: {interaction.user.id}", icon_url=interaction.user.display_avatar.url)
embed.timestamp = datetime.now()
await interaction.response.send_message(embed=embed, ephemeral=True)
Ok thanks
Anyone knows why reload_extension won't work from within a slash command
It works for me
Here's what my code looks like:
# Reload cogs manually
@dev_commands.command(
name="reload",
description="Reload an extension",
)
async def reload(
self,
ctx: discord.ApplicationContext,
extension: discord.Option(str, "The filename of the extension to reload")
):
self.bot.reload_extension(f'cogs.{extension}')
await ctx.respond(f"Reloaded **{extension}**")
hey sso it my first time using modals and select menus but i cant figure out options heres my options code options=[discord.SelectOption(label='Red', value='Red Team', description='You Choose red team')] but i get error Ignoring exception in view <Join_Enabled timeout=None children=1> for item <Button style=<ButtonStyle.success: 3> url=None disabled=False label='Join event' emoji=None row=None>: Traceback (most recent call last): File "/home/david/Documents/GitHub/creator-lazer-tag/venv/lib/python3.10/site-packages/discord/ui/view.py", line 375, in _scheduled_task await item.callback(interaction) File "/home/david/Documents/GitHub/creator-lazer-tag/cogs/message.py", line 55, in confirm_callback modal=MyModal(title="Link to Minecraft") File "/home/david/Documents/GitHub/creator-lazer-tag/cogs/message.py", line 14, in __init__ super().__init__( File "/home/david/Documents/GitHub/creator-lazer-tag/venv/lib/python3.10/site-packages/discord/ui/modal.py", line 57, in __init__ self._weights = _ModalWeights(self._children) File "/home/david/Documents/GitHub/creator-lazer-tag/venv/lib/python3.10/site-packages/discord/ui/modal.py", line 260, in __init__ children = sorted(children, key=key) File "/home/david/Documents/GitHub/creator-lazer-tag/venv/lib/python3.10/site-packages/discord/ui/modal.py", line 259, in <lambda> key = lambda i: sys.maxsize if i.row is None else i.row AttributeError: 'function' object has no attribute 'row'
and it does reload ur cog whenever u change it
Yep
i have a function that i use in a couple of different listeners that checks if a message is emoji-only. it's in a cog i have for this called emoji.py. so i in my Emoji class i have my async def emoji_catch(self, msg), and then listeners for on_message and on_message_edit and stuff. when i try to call my emoji_catch function though like this: await Emoji.emoji_catch(self, message), i get an error TypeError: 'module' object is not callable??
am i calling the function wrong here?
looks like this
over the function itself you mean? like a decorator?
yea
self.emoji_catch?
ohhhhhh that might be it
self.emoji_chatch ..... Learn Python pls
object oriented programming is not in most tuturials
only reason i know it is cuz i learned kotlin
that's literally what i'm doing lol
would you suggest i spend dozens of hours reading theory books or actually writing code
this is how i'm learning
self.emoji_catch giving me the same exception... rly weird
don't name your cog Emoji, there's already discord.Emoji
name it like EmojiCog or something
ohhhhh thank you

STILL getting module object not callable... wtf
if it's not a static method you need to use self
i think those take sefl
self iirc
wouldn't it be unable to use self.bot.db.execute though, if i'm not giving it self?
yes
so many i don't use staticmethod lol
either way it can't do that
*maybe
my on message works with self but idk
you can call it self but it's really cls and it won't work
on_message isn't static
when you use self.your_def() your dont need them too
i'm very lost lol
can i use commands groups in multiple cogs?
wait, is it something wrong with stripped_msg = unidecode(msg.content)??
yeah, i've imported it though
there's probably a function in the module you're trying to use
you might have to do somthing like unicode.unicode
from unidecode import unidecode
when i had the same function my import looked exactly like this
*same function in another file
yea
before i separated this into a cog
No problem, I hope you learned a little bit too 😊
i definitely did - quite unused to classes so it takes a bit of getting used to
can someone tell me why pylance underlines me most of my code red?? like whats wrong there
I am trying to reload all slash commands without having to restart the bot and the following code only adds the new functions when its not a slash command, but when it is a slash command it does not load it. How can I reload all commands from inside the code? I already tried syncing
# Restarts cogs
@commands.slash_command(description="Restart cogs")
@isDeveloper()
async def reload(self, ctx):
cogs = [ext[:-3] for ext in listdir("./cogs/") if ext.endswith(".py")]
embed = discord.Embed(color=0x3C3D41, timestamp=discord.utils.utcnow())
embed.title = 'Reloading Cogs!'
await ctx.respond(embed=embed, ephemeral=True)
for cog in cogs:
try:
self.bot.reload_extension(f"cogs.{cog}")
embed.add_field(name=f"Reloaded: `{cog}`", value="\uFEFF", inline=True)
await ctx.interaction.edit_original_message(embed=embed)
except Exception as e:
embed.add_field(name=f"Exception ocurred: ", value=e)
await ctx.interaction.edit_original_message(embed=embed)
embed.title = f'Synced All Commands!'
await ctx.interaction.edit_original_message(embed=embed)
is there any way to have 2 sets of multiple choices on a slash command? like have 2 options with multiple choices to choose from
is there a way to load n messages from a certain channel into the internal message cache on startup?
I don't see why not, have you tried it?
why? just fetch it, or do get then if it's None fetch
wrote code for on_reaction_add(reaction, author): and it seems that if the server is active the message people are supposed to react to gets pushed out of the cache, restarting the bot doesn't help because then the message it's supposed to be looking at definitely isn't in cache
I don't want to rewrite a ton of stuff because I do things like interacting with the reaction object that on_reaction_add passes and there isn't a reaction object in the payload parameter of on_raw_reaction_add
you don't have to rewrite anything, you can just call on_reaction_add from on_raw_reaction_add
boi
just create the reaction object and pass it
is there a get reaction? because on_raw_reaction_add doesn't give it to you
the solution is on_raw_reaction_add, trying to prefill the cache isn't going to be reliable
a get reaction?
yeah only one shows the options, other doesnt
can you send your code?
what's in the reaction object you need that's not in the payload?
the methods, such as .remove
the payload object only contains the emoji and the author, not the actual reaction itself
you'd have to call remove on the message
I don't want to remove the entire message, just the reaction
on_raw_reaction_add doesn't even pass the message object, only the id
@commands.slash_command(description="Sets the bots presence")
@discord.option("status", description="Set the status of the bot", choices=["online", "idle", "dnd", "invisible"])
@discord.option("actvity", description="Sets the activity of the bot", choices=["playing", "watching", "listening", "competing", "streaming"])
@isDeveloper()
async def presence(self, ctx, status: str, activity: str, name: str):
statuses = {
"online": discord.Status.online,
"idle": discord.Status.idle,
"dnd": discord.Status.dnd,
"invisible": discord.Status.invisible
}
activities = {
"playing": discord.ActivityType.playing,
"watching": discord.ActivityType.watching,
"listening": discord.ActivityType.listening,
"competing": discord.ActivityType.competing,
"streaming": discord.ActivityType.streaming
}
status = statuses[status]
activity = activities[activity]
presence = discord.Activity(name=name, type=activity, status=status)
await self.bot.change_presence(activity=presence)
await ctx.respond(embed=discord.Embed(title="Set presence!"), ephemeral=True)
I don't use the discord.option decorator, I use the Option typehint, and that's always worked for me
so maybe try that
oh so i just import from discord import option and then just do opton and the stuff
oh thats it
this is what I was talking about py async def presence(self, ctx, status: Option(str, choices=["online", "idle", "dnd", "invisible"], activity: Option(str, choices=["playing", "watching", "listening", "competing", "streaming"], name: str):
@prisma flicker fetch_message can't be called without a ctx object which isn't passed into on_raw_reaction_add
false, guild has a fetch_message method
you were saying?
sorry, it's in channel
something like await bot.get_guild(guild_id).get_channel(channel_id).fetch_message(message_id)
this will get the message, and it has the reactions array
await client.get_channel(payload.channel_id).fetch_message(payload.message_id)
however there's no way to determine what reaction just occurred
how do you figure? you have the emoji, member, and message
reactions array only shows you count, not users
I'm looking for a reactions object to call .remove on
is there a remove somewhere else I can call?
msg has a remove_reaction
you would call remove_reaction on msg yes
yea it doesn't take user_id though
well yeah, you need to turn user_id into a user
it takes a discord.User not an int
yea the user object is exposed in the raw_reaction_add payload so that's simple to pass in
thanks
For some reason VS code tells me I have 4 arguments when in this code I only have three on the line
@Client.command()
@commands.Cooldown(1, 5, commands.BucketType.user) #This is the line
async def withdraw(ctx : commands.Context, amount: int):
wallet, bank, maxbank = await get_balance(ctx.author)
try:
amount = int(amount)
except ValueError:
pass
if type(amount) == str:
if amount.lower() == "max" or amount.lower == "all":
amount = int(bank)
else:
amount = int(amount)
bank_res = await update_bank(ctx.author, -amount)
wallet_res = await update_wallet(ctx.author, amount)
if bank_res == 0 or wallet_res == 0:
return await ctx.send("No account was found so one was made for you")
wallet, bank, maxbank = await get_balance(ctx.author)
em = discord.Embed(title=f"{amount} coins have been withdrew")
em.add_field(name="New Wallet", value=wallet)
em.add_field(name="New Bank", value=f"{bank}/{maxbank}")
await ctx.send(embed=em)
@commands.Cooldown(1, 5, commands.BucketType.user)
TypeError: Cooldown.__init__() takes 3 positional arguments but 4 were given
Error. ^^^
I looked it over and can only see three there.
should it be @commands.cooldown()?
Can someone help me if I have a list in like this: ["a", "b"] and want to fill it to a certain length with the same pattern? Length 4 ["a", "b", "a", "b"] or Length 8 ["a", "b", "a", "b", "a", "b"]. I don't know how to do it
just do ["a","b"]*4 or whatever
=>>> x=['a','b']
>>> x*4
['a', 'b', 'a', 'b', 'a', 'b', 'a', 'b']```
how do i make it so i can have multiple buttons on the same command beacsue currently i have one command that is /homepage and when the command activates i have the button thats is log in but i wanna make multiple buttons instead of just one here is the code i have if anyone wants to fix and write back!
class MyView(discord.ui.View):
@discord.ui.button(label="login", style=discord.ButtonStyle.primary, emoji="")
async def button_callback(self, button, interaction):
await interaction.response.send_message("no log in yet sorry!")
@bot.slash_command()
async def homepage(ctx):
await ctx.respond("homepage", view=MyView())
just add another button, with a unique callback name
sorry im kinda new to coding lol, can u explain further
how do i do the call ack just take async def button_callback(self, button, interaction): and replace what?
yeah but don't name it button_callback
okay thanks let me try this!
I would name your first one login or login_callback
Thanks. So simple 😂
@discord.ui.button(label="get,code", style=discord.ButtonStyle.primary, emoji="👩🏻💻")
async def poop_callback(self, button, interaction):
await interaction.response.send_message("cant get code yet!")
i have that and got syntax error did i do it wrong
what's the syntax error say
looks like your indentation is wrong
@prisma flicker on_raw_reaction_remove passes none as the member in the payload object
and you can't just fetch the user apparently
author = await client.get_user(payload.user_id)
TypeError: object User can't be used in 'await' expression
get doesn't need await
when i use this decorator, does it only affect on every user or only onto the executor?
@commands.cooldown(1, 15, commands.BucketType.user)
that's every user, but you can use dynamic_cooldown to create a custom function that would be able to differentiate between users or other criteria
so just replace cooldown with dynamic_cooldown?
i'm pretty sure he is asking about Who will get slowmoded cooldowned
BucketType.user only affects the executor
however, .guild (or its .server not sure) affects whole guild
so just leave it as it is?
yea
okay thanks
this should work on prefixed commands, but i didn't test it with / ones
it'll work with slash too
i only use slash
all ext decorators will
hello, does anyone here have a code that could make something like this with a box like that with words in it?
pls what
huh
mean an embed??