#General Help
1 messages Β· Page 16 of 1
just dont use replit
yea, use heroku instead
yea that would be alr ig
heruko is pretty decent
is it multiplayer?
what?
so uhh, i got a slash command which is utilizing autocomplete, the next argument's option choices will be determined by the previous argument's selected option choice, the problem is the users can simply fill any argument first, which will then bring error since the previous argument's option choices havent been selected yet
is there any workaround? or do i have to implement it differently?
You can use
elif ...
That's what I tried first but it doesn't work.
I was also told that you need except and try.
FIXED
Is there a method to pass the parameter into the callback as shown below?
i'm doing something like await channel.send()
so.. what's stopping you?
any recommendations on how to present a user with a list that is >25 options but is not a slash command autocomplete option?
i actually have a different problem now. im trying to pass the parameter blue from my discord bot object
however i end up with this error
Autocomplete is your only option.
π¦ am considering paginating the options in a select, then, but it's such a faff
One simple question, are classes in python necessary? Can I code without using classes?
It isn't necessary but it makes your code easier to understand? idk
I see most developers using object oriented programming these days
Everything is an object and belongs to a class
what version of pycord?
in ur terminal do pip list and send the version of pycord you use
also if you have discord.py uninstall it
and then uninstall py-cord
then reinstall from here
Install pycord:
pip uninstall discord.py
pip install py-cord
Install pycord beta:
pip uninstall discord.py
pip install py-cord==2.0.0b7
Install pycord alpha from git:
pip uninstall discord.py
pip install git+https://github.com/Pycord-Development/pycord
What is the permission to timeout a member? I cant seem to find it on the permissions section on docs
moderate_members
Thanks, member.timeout isnt working either?
question about modals is there anyway to pass an option from a slash command into the callback of the modal?
for role in ['Tokyo Fart Sniffers', 'Baltimore Bughas']:
oldroles = discord.utils.get(ctx.guild.roles, name=role)
await player.remove_roles(oldroles)
is this not a valid way to remove roles in a list?
i don't think its doing anything when i use my command
hello?
I'm getting and error that says discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: Forbidden: 403 Forbidden (error code: 50013): Missing Permissions when I use await ctx.author.timeout_for()
even the bot has all permissions and intents
what roles member that you want to timeout have?
Normal member that has nothing permission
just the default ones
@here
Bro...
can i somehow set the ephemeral timeout?
could it be that the bot hasnt the permissio in the guild he is interacting?
did u invite him as admin
it has
it has admin permissions
did but, same issue
hm but what does the bot exactly?
what means?
and when I use timeout instead of timeout_for discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'datetime.timedelta' object has no attribute 'isoformat' is happens :)
has this changed?
i believe you need a member object
not a user objecct
whats the difference?
well they have different attributes
and members are people in a guild
while the user is just user
ahh
what i need to change then?
https://docs.pycord.dev/en/master/api.html?highlight=member#discord.Member here are the attributes
thats what i am currently doing
thanks.
one sec
message.author should work
but read the note that is underneath
i am confused to why its not working then
is the channel a private channel?
nope.
its meant to be ctx.author not message
(think so at least)
make sure the roles ur giving are below the bot role
Its a message event π
oh mb
yes They Are
how do i grab all dms sent by the bot?
Hi, just want to ask -- is it possible to send a message to a specific channel in the on_message event? So let's say I wanted to send a message to channel with ID 881735375947722753, how would you do this?
channel = bot.guild.get_channel(881735375947722753)
Ooo thanks! Then I'd just do channel.send (I'm guessing)? I'll have a look, thanks
^
get the channel first and then use
await channel.send("foo")
Nice, sounds good. Thanks!

Yep or whatever the strings name is.
oh yeah if it returns None then the channel's not cached
in that case you can use await bot.fetch_channel(id)
just be weary this makes an API call
Perfect, thanks for letting me know
Ah, moderation-bots this is gonna suck
Guess there's no choice π
try using get_channel first
any1 know?
by grab you mean fetching them from an async iterator?
Yeah something like that.
a old dev mass dmed with my bot and i need to delete the DM's
How to create a forum like this one guys
in that case you'd have to do anything like
for user in bot.users:
async for message in user.dm_channel.history():
if user == bot.user:
await message.delete()
It might be wrong, im in class rn and i just did a simple thing
how many dms can i delete before getting rate limited u think?
you can set a limit or a date to check for in the user.dm_channel.history()s kwargs
ahh
you could use a non blocking timer on the iterator like await asyncio.sleep() so it does it in intervals and not all at the same time
Use #app-commands
people be getting wayy too pressed over this π its a help channel, that bots helping me quick scan pyc docs
technically its help 
@slender lintel Use #app-commands from now on
@honest moat whatever you did, stop it too
is there a way to assign roles via ID?
role id?
doesnt even throw me an error or nun just doesnt add the role
if yes then you can
role = ctx.guild.get_role(role_id)
await member.add_roles(role)```
i think i tried this, ill try again tho
yea doesnt work, no error either
show code please like full code
@client.event
async def on_member_join(member):
gid = member.guild.id
conn = sqlite3.connect('data.db')
c = conn.cursor()
c.execute("SELECT Guildid, Rolename FROM autorole WHERE Guildid=?",(gid,))
send = c.fetchone()
if send is None:
return
else:
try:
role = member.guild.get_role(send[1])
await member.add_roles(role)
except:
return
using SQLITE3, the db isnt the issue as i can print the role id
is the role id a string or a int?
int
ill quickly test it with the actual role id instead of my db one
remove the try and except
so you can get an error
ah ok i see the error
its getting the role, failing to add it to the user
are you sure the role id is the actual role id?
ill put the actual role id there to test
k
it worked like that, but the id in my DB is identical to the role id
im gonna try drop my table and remake it
ayy works now
bot = commands.Bot(command_prefix = "?",intents=intents)
role = bot.get_role(893545812200677417)
AttributeError: 'Bot' object has no attribute 'get_role'
I'm confused
how should the bot know on which guild it should search for the role
So I presume I would put it as
guild = bot.get_guild(12345)
role = guild.get_role(1235)
Thanks!
how do i send a dm to a user
message.author.dm_channel.send(embed=embedvar)
this doesnt work
message.author.send(embed=embedvar)
How do i get an argument from ctx without discord.Member in case using *
@commands.command()
async def said(self, ctx, target:discord.Member=None, *, args):
if target is None:
target = ctx.author
await ctx.send(f"{target.name} said {args}")
like when ctx author doesn't mention user he becomes the target, but still get the args
easiest way i can think of is not using the member converter at all,
Just look if there is a mention in the message and split from there
It worked thanks
/slashcommand?
How do I get a dropdown to be deleted after a modal is sent when an option from the modal is chosen?
also is it possible to have bold text in a modal text field placeholder?
import discord
from discord.ext import commands
from discord.commands import slash_command, Option
import aiohttp
import aiosqlite
import logging
import os
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("discord")
handler = logging.FileHandler(filename="discord.log", encoding="utf-8", mode="w")
handler.setFormatter(logging.Formatter("%(asctime)s:%(levelname)s:%(name)s: %(message)s"))
logger.addHandler(handler)
async def get_prefix(client, message):
db = await aiosqlite.connect('database/prefixes.db')
async with db.execute("SELECT * FROM prefixes") as cursor:
async for row in cursor:
if row[0] == message.guild.id:
return commands.when_mentioned_or(row[1])(client, message)
return commands.when_mentioned_or("x!")(client, message)
class MyClient(commands.Bot):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.session: aiohttp.ClientSession = None
self.help_command = None
self.case_insensitive = True
self.command_prefix = get_prefix
async def close(self):
await super().close()
await self.session.close()
async def on_connect(self):
self.session: aiohttp.ClientSession = aiohttp.ClientSession()
async def on_ready(self):
logging.info("ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ")
logging.info(f'Connected to bot: {self.user.name}'.center(55))
logging.info(f'Bot ID: {self.user.id}'.center(55))
logging.info("ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ")
client = MyClient(intents=discord.Intents.all())
@slash_command(name="ping", guild_ids=[965061411430600824])
async def ping(ctx: discord.ApplicationContext):
await ctx.respond("pong")
@client.command(name="pong")
async def pong(ctx):
await ctx.reply("ping")
client.run(os.environ["DISCORD_TOKEN"])```
Hi, can anyone take a look at my code to see why slash commands arent registering?
Idk why this time when I make a new bot no slash commands are registering and yes I do have applications.command scope on
it doesn't even register in dms too
Lets say user X uploads 4 attachments and a message.
Is it possible to remove attachment 2 from user X without deleting his message/losing other attachments
You're overriding on_connect and not registering the commands
That is very weird as I made other bots with same setup and they still work
I donβt think thatβs the problem but Iβll try it when I wake up
If you prefixed command works.
Then that's the issue. You're not registering the commands.
Ye
Anyone know why I get discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: edit() got an unexpected keyword argument 'nick' from a simple line await recruit.edit(nick=f"[19th] {oldNick}") I only get this nickname error when using it in this command:
@client.slash_command(guild_ids=[641329842058428416],description="Enlists recruit")
async def conscript(ctx,
regiment:Option(str,"Choose a regiment",choices=["19th Green Howards","King's German Legion","33rd Wellington's Own"]),
recruit:Option(discord.Member,"Recruit Discord username"),
recruiter:Option(discord.Member,"Recruiter Discord username")
):
#ROLES
oldNick=recruit.nick
recruit=discord.utils.get(ctx.guild.roles, id=811623854426161184)
nteenStaff = discord.utils.get(ctx.guild.roles, id=885856695853645864)
britishArmy = discord.utils.get(ctx.guild.roles, id=863760593785323530)
#19th Green Howards Custom
nteenChannel=client.get_channel(862732931389849640)
secondBrig=discord.utils.get(ctx.guild.roles, id=938845984274907216)
nteenRole=discord.utils.get(ctx.guild.roles, id=862704039334641704)
nteenDepot=discord.utils.get(ctx.guild.roles, id=862787244233588736)
if regiment=='19th Green Howards':
if nteenStaff in ctx.author.roles:
await recruit.edit(nick=f"[19th] {oldNick}")
await recruit.edit is editing a role
not a member
recruit=discord.utils.get(ctx.guild.roles, id=811623854426161184)
You change it to a role in that line
Slash commands seem to not like me making a button
- version is V2 rc1
- im using the template
class View(discord.ui.View): # Create a class called View that subclasses discord.ui.View
@discord.ui.button(label="Click me!", style=discord.ButtonStyle.primary, emoji="π") # Create a button with the label "π Click me!" with color Blurple
async def button_callback(self, button, interaction):
await interaction.response.send_message("You clicked the button!") # Send a message when the button is clicked
@bot.slash_command() # Create a slash command
async def button(ctx):
await ctx.respond("This is a button!", view=View()) # Send a message with our View class that contains the button
"this application could not respond". When i made it into a prefix command it worked fine
right now my command goes through and the button interaction works properly but it says the application did not respond?
await interaction.response.defer()
# bunch of stuff
await interaction.message.edit(content = None, embed=embed , view=None)```
i tried `await interaction.followup.send(content = f'{ctx.author.mention}')` as well to ping the author and then embed but same thing
Try interaction.respond().
respond not response?
Do you use debug_guilds in the Bot-object? The error could occur because the slashcommand has not been loaded yet.
Yes, respond.
yeah i have that
debug_guilds=[serverid]
i'll probs try it out later incase my bots bugged
Ok, I am wrong. This method is for ApplicationContext.
That should work: interaction.response.send_message()
-> https://docs.pycord.dev/en/master/api.html?highlight=interaction#discord.InteractionResponse.send_message
can't respond since it says the interaction has already been responded to
Could you send your Code again? What did you change?
rn i changed the last bit all to interaction.followup.send()
since i need it for interaction.defer()
no interaction.mesage.edit()
with that however, it says it didn't respond without clicking my button
Sry, I do not understand your explanation.
before it used to say it didn't respond after i clicked a button
that was with
await interaction.response.defer()
# bunch of stuff
await interaction.message.edit(content = None, embed=embed , view=None)```
i tried ```py
await interaction.response.defer()
bunch of stuff
await interaction.followup.send(content = None, embed=embed , view=None)```
but now it gives me that message before
how do I
a) delete the ctx.respond message? I tried it with message = ctx.respond(...) and then await message.delete() but it doesnt work
b) can iset the timeout for ephemeral message
a) await ctx.delete() #deletes original response message
b) yes. default timeout for ephemeral is 15 minutes
if i wanna set the timeout should i just pass timeout in seconds ? ty btw
yes i think
itβs just i didnβt find a timeout attribute for a respond in docs
nvm itβs done via view
anyone know how to solve this error for replit
trying to host my bot there
these are my packages
No soz i dont use repl
i also downloaded the pycord package on replit
?tag replit
Read this to find out how you can install Pycord in replit - https://namantech.me/pycord/installation/#replit
How to install the Py-cord library - Pycord Guide
is that outdated
because I can't create a .replit file
it says theres already one created
but its a fresh project
yes it is.... i will brb
ok i solved it
good
i just did python3 -m pip install -U py-cord --pre in shell
my code just wont work
is author.bot to check if the user is a bot or does it refrence the bot itself as in the bot thats running?
author.bot returns a bool value
so if its true a bot sent the message?
If the user is a bot, its True if the user isn't its False
yes
yea
Ah okay.
It's true if a bot send the msg
yes
so you could do message.author == bot.user:
ah okay.
so the bot doesn't loop in an on_message event
why does this not work then?
can you try printing the message.author.bot
yeah this is definetly not the issue. I removed on_connect and they still do not register
interaction.followup.send_modal()
Not working , whats the alternative
there is nothing like this... only interaction.response.send_modal
how i can defer it
you cant
since bot getting crashed when many are using the button
if the defer the button , modal will also be defered ?
defer is counted as a response
an interaction cannot response twice
so what you suggest for a fix ..
when more members are interacting with a button at a same time , where it responds a modal.. bot getting crashed
you can defer it after the submit button is pressed
so if i defer the button , the problem will be solved ...
is my understanding right ?
I have issue
Happened after attempt of me to install py-cord, i uninstall it after
But now when i start new command in cog And run it, it gives me error that command not found
@commands.command(aliases=["p", "latency")
async def ping(self, ctx):
ping = round(self.bot.latency * 1000)
await ctx.send(f"{ping}ms!")
Am using replit by the way
Read this to find out how you can install Pycord in replit - https://namantech.me/pycord/installation/#replit
How to install the Py-cord library - Pycord Guide
Why NOT to use Repl as a hosting platform
You should not use Repl.it to host your bot.
It may be a nice option as its "free" but you should use something else considering the major flaws.
- The machines are super underpowered.
-
- This means your bot will lag a lot as it gets bigger.
- You'll need a web server alongside your bot to prevent it from being shut off.
-
- This isn't a trivial task, and eats more of the machines power.
- Repl.it uses an ephemeral file system.
-
- This means any file you saved via your bot will be overwritten when you next launch.
IMPORTATNT
- They use a shared IP for everything running on the service.
This one is important - if someone is running a user bot on their service and gets banned, everyone on that IP will be banned. Including you.
Please avoid using repl.it to host your bot. It's not worth the trouble.
If you're looking for free options, consider using AWS/Google Cloud Platform/Azure and its respective free tiers or just pay for an actual VPS.
if i defer the button which is going to send a modal .. then the bot wont crash due to heavy surge right ?
i dont think so..
if your bot is crashing, get a better hosting service
its running in a high performance server
problem is bot is still online
but its saying failed interaction
defer just prevents failed interaction from showing up... wont increase preformance
got it , i think defer a button can solve my issue
btw is that possible i can get the bot = discord.Bot(intents=intents) inside a cogs?
and i wanna use bot.get_channel(id) in db.py
bot is passed as an argument to cogs just do this
class Moderation(discord.Cog):
def __init__(self, bot):
self.bot = bot
do you have any idea how to defer an modal interaction ?
so self.bot.get_channel?
okie thx
eh wait, the db.py is not a cogs...
ctx.bot also works withing a command iirc
what?
if its in a command that you need it
@slash_command
async def hello():
ctx.bot.XXX
its a bit hidden so it took me a secoind to find it.
in the callback (after the user hits submit)
interaction.response.defer()
let me check ser
code:
@bot.command()
async def testin(ctx, user: discord.Member = None):
my_image = Image.open("wanted.jpeg")
asset = user.avatar_url_as(size=128)
data = BytesIO(await asset.read())
pfp = Image.open(data)
pfp = pfp.resize((125, 125))
my_image.paste(pfp, (36, 80))
my_image.save("profile.png")
await ctx.send(file=discord.File("profile.png"))
error:
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Users/luke/PycharmProjects/bot/venv/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 344, in invoke
await ctx.command.invoke(ctx)
File "/Users/luke/PycharmProjects/bot/venv/lib/python3.10/site-packages/discord/ext/commands/core.py", line 927, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/Users/luke/PycharmProjects/bot/venv/lib/python3.10/site-packages/discord/ext/commands/core.py", line 190, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Member' object has no attribute 'avatar_url_as'
how can i fix?
thx
user.avatar.with_size(128).url
ok thx
So I want to say "if someone gets a score higher than fifty in this round, they double their points but if they get higher than 75, they triple their points"
so this but the also saying that the limit is until 75: if scores >= 50:
how would I do that?
can you help me to defer a modal
its not working
await interaction.response.defer(modal) TypeError: defer() takes 1 positional argument but 2 were given
You don't provide any argument.
i need to send the modal as a response in button click
Then send the modal on button click?
to send the modal use ```py
await interaction.response.send_modal(modal)
β¦ respond.send β¦
I want to defer it , since when many are trying to use the button the interaction is failing
await interaction.followup.send_modal(modal)
this too not working
@worthy basin
Is it possible for a bot to use another bot's application commands?
hmmm how to defer a ctx?
Nope, its "response"
await interaction.response.send_modal()
I think you want response not followup. Also you cannot send a modal and a response to a modal. Discord limitation :/
how can i defer it thats the question
then it cannot be deferred ?
my button response is a modal
so how i can defer and follow up
And do you want the button to be deferred or the modal?
button response is a modal
await interaction.response.defer()
await interaction.followup.send_modal()
This interaction has already been responded to before
error
Oops, edited my code above it should work now
for modal inputs, I'm guessing the maximum text thing you can have are 5?
this is what i tried before :
Error
await interaction.followup.send_modal(modal) AttributeError: 'Webhook' object has no attribute 'send_modal'
Yes
do you want the others to click on the button or only the user that used the command?
Hmm, it appears that you cannot defer the modal sending.
it would cause bad ui
Your modal takes longer than 3 seconds to send?
ya so when many are trying to hit the button ... the interaction gets failed
how can i fix that
no it takes less time
yes
sending in the thread
#984479774456033370 message
whats the fastest way to edit mass message in a time?
Is there a guide on how to migrate to permissions v2? I just updated pycord to the first release candidate and I'm getting this error
AttributeError: module 'discord.commands.permissions' has no attribute 'has_role'
you can try using await asyncio.gather(*coros) where coros = [message.edit(), message.edit()...]
If you want to do a bot-typed check (no customization for users), use a discord.ext.commands decorator. If you want them to customize it, discord.default_permissions decorator.
Examples:
https://github.com/Pycord-Development/pycord/blob/master/examples/app_commands/slash_perms.py
https://docs.pycord.dev/en/master/ext/commands/api.html#checks
Will i got rate limited?
probably, yes
What im doing rn is creating a loop for each message
Thanks!
Why do you need to edit the message?
Ah well, what i wanted to do is editing mass message quickly
hello! is mysql a good db for pycord?
I have a source tracking bot that checks every N second to the server, and had to edit message to update it with the new query
if you are using an asynchronous implementation of it, yes
I suppose you can add a button to the message called "Update" instead?
Nope
async is not implemented for mysql from what i read here https://dev.mysql.com/doc/x-devapi-userguide/en/synchronous-vs-asynchronous-execution.html
so should I still use mysql, or what are the recommended db i could use?
if you insist on using mysql as a database, there is https://pypi.org/project/aiomysql/
ahh, thanks!
well, I don't see any other way to not get ratelimited unless you add an asyncio.sleep between each execution
btw does this mean that any other library I want to use must have an async implementation?
Well, it's recommended. Using sync may slow down your bot
"When you execute something synchronously, you wait for it to finish before moving on to another task. When you execute something asynchronously, you can move on to another task before it finishes."
ohh, i see
Having 0.2s sleep for each of edit 
I was thinking maybe every 3 edits, use a sleep.
How long should the sleep be
is it possible to implement async on a synchronous library or should I just find another library that have async implemented? (sorry if I sound dumb, im new to this async thing)
doesn't matter, just some delay
just find an async lib
Woke, i'll take a look later π
alright thanks alot π
how i can use music-cord
ask whoever made that lib
Hey how i can use cooldown in button interaction?
any example
?tag ex
Bot examples: https://github.com/Pycord-Development/pycord/tree/master/examples
Slash command/context menu examples: https://github.com/Pycord-Development/pycord/tree/master/examples/app_commands
Buttons, dropdowns example: https://github.com/Pycord-Development/pycord/tree/master/examples/views
since im done with defer modals
Should be under bot examples
You can implement your own cooldown manually. there is no current cooldown for buttons.
print(message.content) using this line to try and find the content off a message and in the console it is just showing an empty string (like there is nothing shown in console) any help?
any specific code file ser
?tag message-content
As of PyCord beta 5 (which uses API v10), specifying the message content intent will be required for receiving message content.
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
Docs: https://docs.pycord.dev/en/master/api.html#discord.Intents.message_content
not even my first bot, i totally forgot, thanks lol
wait i already had that, now im confused
i dont want a modal ser , since ii cannot be defered
did you pass in intents?
more like button press to receive a string from the users
then no.
its more convenient to use a global error handler to handle frequent cases like this
Well, there are slash command options that can take a string
which is probably the best if you want to defer a response
yea , thats fine , looking for more like button
where?
no, not that I know of. Unless you would like the old school message approach
?tag 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)
?tag edit message-content
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
tag message-content edited.
and how?
such as getting the time and adding time to it and checking whether the time has passed
Yes but this button should still use several?
wdym several
Will be a feedback button means people leave feedback yk
ok, so what's the problem?
No people should spam yk
it's literally just if statements
whether the user has already interacted with the button=
?*
I don't understand what you mean
I want that you can press the button only every 12 hours
ok, so what's wrong?
Have you not been listening to me for the last few minutes? :((
This is wrong
or?
.
WDYM BY SEVERAL
No people should spam yk
Ok? and?
and that's why I want a cooldown but only for individual players
ok, then implement that
i am here to know how to do it.. oh never mind forget it thanks anyway
simplest way is to store the user id along with a timestamp of when the cooldown ends in a database somewhere
No, at one hand it would be a security problem which could led to easy abuse
On the other hand it was never meant that bots interact with other bots
how could i purge every message the bot has sent within dms, is there a way to fetch all messages sent within dms?
you can fetch the history
Same thing
For normal
Commands
no for a button there is no command
Oh
What event catches interaction errors?
if docs are correct, there are none
except on_application_command_error
which is probably not what you are looking for
Unfortunately, it isn't catching this error
(Though I expected it to catch it, so I'm a little surprised atm)
you can always use a try except
isn't on_error inside of a view a thing?
right
I could, but this was intended to reduce code duplication
I'll check out on_error
Ah, I think I figured it out. I'm using a paginator, and that prints it out by default
yeah, since paginator is a subclassed view you can use on_error there as well
isn't the proper term "child"?
and as far as I remember, that's inheritance and Paginator is a child
tbh i think it can be called either afaik
I believe different places teach it differently. In my opinion, "subclass" sounds vague, but they mean the same thing, I guess.
Subclass is perfectly cromulent
eh it's how I learned it, makes more sense to me but to each their own
i cant invite robobruce help
ty
which is its prefix?
b!
https://url.privatepastebin.com/ws
This is a project that we're doing! Here is what im trying to accomplish for this project.
A game similar to pokemon. I want the user to fight bosses, gain stats, and beat the game.
Here is the rubric for this;
Visit this link to see the note. Giving the URL to anyone allows them to access the note, too.
#help-rules
Help may not be provided with homework or exams.
do someone know what this error mean?
raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embeds.0.url: Not a well formed URL.```
it's self explanatory
Looks like you're sending an embed and some URL is wrong?
How do i get a select menu message to be deleted when the user selects something?
You're providing no context on that error. I can just assume.
Provide the full traceback then.
who?, me?
Yes..
Are you subclassing discord.ui.view?
gonna send ya to dm
And when is this happening
i sended...
When is the error happening is what I mean
can you just send the full traceback
dm
Can you provide your code
well i think https://support.glitch.com/t/discord-embed-not-well-formed-url/27621 have the best problem solver by "download and save the image locally beforehand"
Yes
@countrygroup.command() # TODO: Add support for other entities (orgs, characters, etc)
async def add(self, ctx: ApplicationContext): # maybe make an option for the message to not be ephemeral?
"""Send a modal to the user to add a country/entity"""
class CountryAddView(discord.ui.View):
@discord.ui.select(
placeholder="Pick which entity to play as",
min_values=1,
max_values=1,
options=[
SelectOption(label="Country", description="Play as a Country"),
SelectOption(label="Organization", description="Play as an Organization"),
SelectOption(label="Character", description="Play as a Character"),
],
)
async def select_callback(self, select, interaction: Interaction):
modal = CountryAddModal(select.values[0], title="temp")
modal.title = f"Add new {select.values[0]}"
await interaction.response.send_modal(modal)
view = CountryAddView()
await ctx.respond("Select an entity below and click the button to create a new country/entity.", view=view, ephemeral=True)
this is the function in question
Unfortunate
You could try tho
as long as the modal is sent first you should be able to
select.disabled = True
await interaction.response.edit_message(view=self)
Hello, is it possible to get buttons to work after the bot restarted?
You're looking for persistent views.
Here's the persistent example.
one of my application commands could not load
I know how to make the buttons have no timeout but after i restart the bot he doesn't know how to react to the buttons
Not working
just like my
@sudden path
Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - pycord/persistent.py at master Β· Pycord-Development/pycord
Am I missing something?
discord.errors.ExtensionFailed: Extension 'jishaku' raised an error: AttributeError: module 'discord.ui' has no attribute 'TextInput'
Itβs InputText
ah there must've been a change
or at least i might have to fork jishaku
https://github.com/Gorialis/jishaku/blob/master/jishaku/shim/paginator_200.py#L345-L349
PS C:\Users\Fammy\Desktop\Keni> & C:/Users/Fammy/AppData/Local/Programs/Python/Python310/python.exe c:/Users/Fammy/Desktop/Keni/bot.py
Traceback (most recent call last):
File "c:\Users\Fammy\Desktop\Keni\bot.py", line 1, in <module>
import discord
File "C:\Users\Fammy\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\__init__.py", line 25, in <module>
from .client import Client
File "C:\Users\Fammy\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 53, in <module>
from .webhook import Webhook
File "C:\Users\Fammy\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\webhook\__init__.py", line 12, in <module>
from .async_ import *
File "C:\Users\Fammy\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\webhook\async_.py", line 52, in <module>
from ..channel import PartialMessageable
ImportError: cannot import name 'PartialMessageable' from 'discord.channel' (C:\Users\Fammy\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\channel.py)```
How do I disable buttons after timeout?
the one thats in the docs doesnt seem to be working
hello i want to know what is BytesIO(await asset.read()) changed to
I'm trying to make a song selector using dropdown menus, and keep coming across this error from using the example:
AttributeError: 'SongSelect' object has no attribute '_underlying'
As i said doesn't work
oh so you want to ignore interaction failed?
ig you cant remove them unless you respond the interaction
I want to make a Ticket system with buttons, but when i restart my bot the buttons doesn't work that where send before the restart
The code you send me doesn't work idk if i am doing something wrong or maybe it is outdated
show your code
PLZ help me here: https://discord.com/channels/881207955029110855/984744337629921291
I copyed this 1 by 1 (Just wrote my token inside the run function) and the command didn't even work.
My Ticket (only button) Code:
- Button function -
class main(View):
def __init__(self, ctx, time, bot):
super().__init__(timeout=time)
self.ctx = ctx
self.bot = bot
async def on_timeout(self):
await self.ctx.send(f"Button Timeouted time was set to {self.timeout} Seconds")
async def on_error(self, error: Exception, interaction: discord.Interaction) -> None:
await interaction.response.send_message(Exception)
@discord.ui.button(label="Ticket", style=discord.ButtonStyle.green, custom_id='TICKET')
async def tick(self, button: discord.Button, interaction: discord.Interaction):
- My Code -
- Command -
@commands.command()
@commands.guild_only()
# @commands.cooldown(1,10,commands.BucketType.member)
async def ticket(self, ctx):
await ctx.message.delete()
view = main(ctx, None, self.bot)
await ctx.send('My Text',view=view)```
ovs becoz the buttons gets timeouted when you restart the bot / reload cogs.
Yes, is there a way to fix that?
Mmmm ye when you restart the bot just you need to readd the views on listener.
view also has to have no timeout
he said about restarts.
# 1) The timeout of the View has to be set to None
# 2) Every item in the View has to have a custom_id set
How would i make that?
thats a persistent view my guy
check docs bottom codes in examples/views/buttons.py
I always have a custom id
point number one my friend
i said about this https://github.com/Pycord-Development/pycord/blob/master/examples/views/button_roles.py
Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - pycord/button_roles.py at master Β· Pycord-Development/pycord
I'll look into
ok i dont see that sorry
Np, i think i need a listener or something?
Because i just create the button but how is the bot actually reading it
because its added to the bot via add_view()
Hmmm lemme see
How can I get the id of the channel where the bot is invoked with a slash?
Working, thank you a lot @slender lintel, @half marsh, @crimson gale
welcomewelcome!
@smoky path Will you help me here? https://discord.com/channels/881207955029110855/984744337629921291
is it possible to fetch all messages in a channel and look for a specific content or do i have to iterate over every single message
my code```py
@bot.command()
async def testin(ctx, user: discord.Member = None):
my_image = Image.open("wanted.jpeg")
asset = user.avatar.with_size(128).url
data = BytesIO(await asset.read())
pfp = Image.open(data)
pfp = pfp.resize((125, 125))
my_image.paste(pfp, (36, 80))
my_image.save("profile.jpg")
await ctx.send(file=discord.File("profile.jpg"))
error
```py
Traceback (most recent call last):
File "/Users/luke/PycharmProjects/bot/venv/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 344, in invoke
await ctx.command.invoke(ctx)
File "/Users/luke/PycharmProjects/bot/venv/lib/python3.10/site-packages/discord/ext/commands/core.py", line 927, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/Users/luke/PycharmProjects/bot/venv/lib/python3.10/site-packages/discord/ext/commands/core.py", line 190, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'str' object has no attribute 'read'
anyone know why my shards are not coming online?
Strange request but... is it possible to limit what commands are available based on the discord server?
Using Slash Commands?
Or regular commands?
either
im in the conceptual stages of the bot. Want it to perform similar tasks in 2 different servers but some of the commands should be exclusive to the one server or the other. Trying to work out if it would need 2 different bots.
You wanting to hind the slash command or show it but show a different message?
uh
I want to move a channel at the end of a category, though the end kwarg in .move() does not do anything for some reason(I set it to True) neither does begging do anything(when set to False)
for it to be hidden/unavailable
i know you can disable slash commands
not too sure how though
For slash commands there is a kwarg guild_ids = []where you can just input the guilds ids you want that can use those slash commands
For normal commands just include a check that sees if the guild is right or not and then return if it is the wrong guild
You can do that
So
use a database.
yes ^
And set what you want to send to the key which should be the guild id
And then you check the guild the member is in and send the message based off of that
Smart. Thanks for the help
Np
Can anyone help in #984784278858645504
What? Why
My teacher literally said your allowed to google and research if you donβt know what to do
All good though
So im planning on adding auto modderation to my pycord discord bot but tbh i dont know where to start
could i just use like message.context and if its == "a bad word" do this
?
well comparing the entire message.content to a singler word will almost never work unless they are saying just the "bad word"
so create a list
and all my bad words into it
?
or a dict
what I would do is just create a list of bad words and just iterate through it. so like
bad_words = ["F###", "S###"]
for word in bad_words:
if bad_words in message.content:
do_something```
ye
ok thx
i think there is a better way because these kind of things can easily be bypassed
ima customize so they cant byepass
like alterante
words
like shii
or shit like that
ill come back if i need help thx tho cya]
np
Here is something that you should prob use
?
read it
wtf is fuzzywuzzy
its a library
used for text comparison
so you can compare if a word is close to another word
oh ok
fuzz.<a onclick="parent.postMessage({'referent':'.fuzzywuzzy.fuzz.ratio'}, '*')">ratio('London is a big city.', 'London is a very big city.')
ok but like
wtf is that lmao
name is weird :P
ya ill def look into it'
thx
np
if bad_words in message.content:
do_something```
so for this part
nvm
from email import message
from enum import auto
import discord
import datetime
from discord.ext import commands
from discord.commands import SlashCommand
from discord import default_permissions
client = commands.Bot()
class auto_mod(commands.Cog):
def __init__(self, client):
self.client = client
async def auto_mod(self, ctx, member: discord.Member, minutes: 1440):
bad_words = []
for Shit in bad_words:
if bad_words in message.content:
duration = datetime.timedelta(minutes=minutes)
await member.timeout_for(duration)
embed=discord.Embed(title="Bad word detected β", description=f"@{member} That word has been filtered. Please refrain from using this kind of language, Thx. ", color=discord.Color.dark_gold())
await ctx.send(embed=embed)
def setup(client):
client.add_cog(auto_mod(client))
``` SO i have this but i cant get it to work?
uh you want a on_message event
@command.Cog.listener()
and it only takes the params
self, message
it gives me sytax error
discord.errors.ExtensionFailed: Extension 'cogs.auto_mod' raised an error: NameError: name 'command' is not defined
commands
oops
commands
yup
@commands.Cog.listener()
async def on_message(self, message):
``` is what you want
@commands.Cog.listener()
async def on_message(self, ctx, member: discord.Member, minutes: 1440):
bad_words = []
for Shit in bad_words:
if bad_words in message.content:
duration = datetime.timedelta(minutes=minutes)
await member.timeout_for(duration)
embed=discord.Embed(title="Bad word detected β", description=f"@{member} That word has been filtered. Please refrain from using this kind of language, Thx. ", color=discord.Color.dark_gold())
await ctx.send(embed=embed)
thats whats i have so far
but its still not working
ok
?
@commands.Cog.listener()
async def on_message(self, ctx, member: discord.Member, minutes = 1440):
bad_words = []
for Shit in bad_words:
if Shit in message.content:
duration = datetime.timedelta(minutes=minutes)
await member.timeout_for(duration)
embed=discord.Embed(title="Bad word detected β", description=f"@{member} That word has been filtered. Please refrain from using this kind of language, Thx. ", color=discord.Color.dark_gold())
await ctx.send(embed=embed)```
no
one error i found

@commands.Cog.listener()
async def on_message(self, message):
duration = 1440
bad_words = []
for Shit in bad_words:
if Shit in message.content:
duration = datetime.timedelta(minutes=minutes)
await message.author.timeout_for(duration)
embed=discord.Embed(title="Bad word detected β", description=f"@{message.author} That word has been filtered. Please refrain from using this kind of language, Thx. ", color=discord.Color.dark_gold())
await message.channel.send(embed=embed)```
oh it was on_message sorry i thought it was command
between is there any way to add bridge_command in Cogs
NameError in last line should be
message.channel.send
oh ye
AttributeError: module 'email.message' has no attribute 'content'
ya
im conffused
send code
from email import message
import discord
import datetime
from discord.ext import commands
client = commands.Bot()
class auto_mod(commands.Cog):
def __init__(self, client):
self.client = client
@commands.Cog.listener()
async def on_message(self, ctx):
duration = 1440
bad_words =[]
for Shit in bad_words:
if Shit in message.content:
duration = datetime.timedelta(minutes=duration)
await message.author.timeout_for(duration)
embed=discord.Embed(title="Bad word detected β", color=discord.Color.dark_gold())
await ctx.send(embed=embed)
def setup(client):
client.add_cog(auto_mod(client))
oh you changed message parameter to ctx
in your code just change all the ones that have message to ctx
what
oops
Not at all
or rename your message import to email_message and change the attribute to message
Thats what i would do
jjea message is not messagable
ya so its still not working
from email import message
import discord
import datetime
from discord.ext import commands
client = commands.Bot()
class auto_mod(commands.Cog):
def __init__(self, client):
self.client = client
@commands.Cog.listener()
async def on_message(self, message):
duration = 1440
bad_words = []
for Shit in bad_words:
if Shit in message.content:
duration = datetime.timedelta(minutes=duration)
await message.author.timeout_for(duration)
embed=discord.Embed(title="Bad word detected β", color=discord.Color.dark_gold())
await message.channel.send(embed)
def setup(client):
client.add_cog(auto_mod(client))
heres
all of my code
im loke just conffused cuz auto mod so much dif
then slash commands
heres all of it
what is the error
tell me what is ur goal, if user entered a banned word
ok
i just always have
send that
du you use bot.load_extension() ?
yes
do you have message_content intent
import discord
import os
from discord.ext import commands
from discord.commands import SlashCommand
client = commands.Bot(activity=discord.Game(name='Watching for / commands'))
@client.event
async def on_ready():
print(f"{client.user}Bot is loaded")
for file in os.listdir("./cogs"):
if file.endswith(".py"):
print("Loaded successfully")
print(file[:-3])
client.load_extension("cogs." + file[:-3])
client.run)
no intents
i was struggling like this π¦
f
intents = discord.Intents.all()
intents.members = True
client = commands.Bot(activity=discord.Game(name='Watching for / commands'), intents = intents)```
im an idiot it was so obvious
:P
same
@slender lintel it would be the best you donβt paste code snippets with bad language, because itβs forbidden here as well.
And tbh if the new Automod gets released, you donβt need a bot to check for it.
blur the words out next time π
ok
ya dude idk
And remove your shadow variable names it can lead to weird errors that are hard to bonk
from discord.ext import bridge, commands
class Test(commands.Cog):
def __init__(self, bot):
self.bot = bot
@bridge.bridge_command()
async def say(self, ctx, *, text):
await ctx.send(text)
def setup(bot):
bot.add_cog(Test(bot))
I think i am doing it right way?
ye
oh way
wait no
ok
i had the same problem with discord js, (reason was i dont know javascript correctly)
Ya true im still learning py
lmao
ik basics tho
and how to get arrount
arround
ik basics of js
?tag lpp
No tag lpp found.
?tag lp
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)
hmm
@bridge.bridge_command()
async def say(self, ctx, *, text):
if isinstance(ctx, commands.Context):
await ctx.send(text)
elif isinstance(ctx, discord.ApplicationContext):
await ctx.respond(text)
oh well i used code accademt
i like it
When I pass the attachments argument to the message edit method, can I specify attachments from other messages or do they need to be from the message I edit?
from email import message
import discord
import datetime
from discord.ext import commands
client = commands.Bot()
class auto_mod(commands.Cog):
def __init__(self, client):
self.client = client
@commands.Cog.listener()
async def on_message(self, message):
duration = 1440
bad_words = []
for Shit in bad_words:
if Shit in message.content:
duration = datetime.timedelta(minutes=duration)
await message.author.timeout_for(duration)
embed=discord.Embed(title="Bad word detected β", color=discord.Color.dark_gold())
await message.channel.send()
def setup(client):
client.add_cog(auto_mod(client))
ya i have so far but its not working for mr
i guess we need experience, i use codeacademy for js
remove client declaration
im only 14 so
remove
from email import message```
I hate js it makes me cry
it makes me null
I don't hate js im too lazy learn it. Just know the basics :P
py easier
i am good with web or better than node.js
my next is either lua or mysql
cuz im in the porcesse of a website
guys talk in #general please, or staff is prob going to warn us for getting off topic :P
k
I also know a bit.
But the implicit type conversions make me suffer internally.
Bro guys its still not working
did you remove the import yet?
wait 1 sec
imas try again
nope
import discord
import datetime
from discord.ext import commands
class auto_mod(commands.Cog):
def __init__(self, client):
self.client = client
@commands.Cog.listener()
async def on_message(self, message):
duration = 1440
bad_words = []
for Shit in bad_words:
if Shit in message.content:
duration = datetime.timedelta(minutes=duration)
await message.author.timeout_for(duration)
embed=discord.Embed(title="Bad word detected β", color=discord.Color.dark_gold())
await message.channel.send(embed)
def setup(client):
client.add_cog(auto_mod(client))
did you put in the intents
and enable them yet
in your developer portal
uhh yes in main
yes i did in dev
not main
...
import discord
import os
from discord.ext import commands
intents = discord.Intents.all()
intents.members = True
client = commands.Bot(activity=discord.Game(name='Watching for / commands'))
@client.event
async def on_ready():
print(f"{client.user}Bot is loaded")
for file in os.listdir("./cogs"):
if file.endswith(".py"):
print("Loaded successfully")
print(file[:-3])
client.load_extension("cogs." + file[:-3])
oops
bruhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
im go reset
that real quick
client = commands.Bot(
activity=discord.Game(name='Watching for / commands'),
intents=intents
)```
you forgot to pass it in ._.
can i get an example of if running
uh 1 sec if i can get pycharm to start
ok
do i have to pass intents for auto_mute cog?
no
it just cloes !!
LMAO
?
await self.start(*args, **kwargs)
File "C:\Users\GameScript\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 658, in start
await self.connect(reconnect=reconnect)
File "C:\Users\GameScript\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 599, in connect
raise PrivilegedIntentsRequired(exc.shard_id) from None
discord.errors.PrivilegedIntentsRequired: Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.
Exception ignored in: <function _ProactorBasePipeTransport.del at 0x000001D84A27CF70>
Traceback (most recent call last):
File "C:\Users\GameScript\AppData\Local\Programs\Python\Python310\lib\asyncio\proactor_events.py", line 116, in del
self.close()
File "C:\Users\GameScript\AppData\Local\Programs\Python\Python310\lib\asyncio\proactor_events.py", line 108, in close
self._loop.call_soon(self._call_connection_lost, None)
File "C:\Users\GameScript\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 750, in call_soon
self._check_closed()
File "C:\Users\GameScript\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 515, in _check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
Exception ignored in: <function _ProactorBasePipeTransport.del at 0x000001D84A27CF70>
Traceback (most recent call last):
File "C:\Users\GameScript\AppData\Local\Programs\Python\Python310\lib\asyncio\proactor_events.py", line 116, in del
File "C:\Users\GameScript\AppData\Local\Programs\Python\Python310\lib\asyncio\proactor_events.py", line 108, in close
File "C:\Users\GameScript\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 750, in call_soon
File "C:\Users\GameScript\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 515, in _check_closed
Integrate your service with Discord β whether it's a bot or a game or whatever your wildest imagination can come up with.
oh shit
wtf
i did enable the,
:
Here's the bridge commands example.
ohhhhhhhh
its
client.bridge_command()
:P
@strong totem
ok
ok
so first if is checking for normal command
and seconds for slash commands
thanks
π
so when i try to Say Shit it gives
discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
so
ye
your bot
has no permission
to mute someone
it dose
give it admin or something
and amke sure the role
i did
is above the suer
Also you are probably the owner
it is
so it cant time out the owner
of the server
lol
yes
so
thats why
yeah
you are missing permissions
OH!!!
its cuz i said shit
lmao
mhm
my bot needs to be higher than my role
and i cant cuz the main owner of our server has it on privte LMAO!!
im co owner
ah
lol
my bot name is Pankakers
lol
intersting
lol
bot role should be on top if i am correct
make a new server
FUCK no
this server took so long
to make
its all about modding
gtav forza and shit like that
and all games
pretty much
can i send you friend request? conversation ended not going offtopic
lol
OMG
it worked
wow
thx guys
btw how to check the text channel is nsfwf or not in code?
like if ctx.channel.is_nsfw :?
no i mean the commands should work on not nsfw channel too
it can be nsfw or not nsfw
so if the content is nsfw i wanna block it
Well basically
i think yes if.ctx.channel.is_nsfw should work
i have a api
- You can use something to see if channel is marked nsfw or not which lets the command be used but not work if channel isnt nsfw
- The bot might throw an error in not being able to send since content is nsfw but you should still try the first bit
- Have an API/ai to scan content
i mean that, but is it only nsfw or is_nsfw
b!rtfm nsfw
I couldn't find a documentation with the name nsfw! Maybe you used to command wrong? Correct Usage: <prefix>rtfm <docs> [<term>] (eg. b!rtfm py cool)
List of Documentations you can search:
python
pycord
discord.py
yarsaw
nextcord
disnake
b!rtfm pyc nsfw
i have the api and its why i know
rtfm pycord is_nsfw
b!rtfm pyc is_nsfw
b!rtfm pycord is_nsfw
ye it is
lmao why did u rerun the command π
Hey, for some reason my shards are not coming online, this is my code, none of them want to start up.
https://cdn.discordapp.com/attachments/984782973503160320/984782973742219264/unknown.png
idk i think im askin on discord.py server
oh internet down that sec
sharding in pycord is hard tho for me
i think u dont need that if ur bot <500 server
mine is in 2.2k servers π
nice then , you should shard it
Dont want to be an ass
but why arent you using dotenv or enviroment secrets
I don't see a point in it π
why not?
in my eyes there is no major reason for me to do that.
I mean you might accidentally leak your token
Such as when you ask us for support or just when you publish source code and whatnot
If your bot is in 2.2k server that could be 2.2k servers that are nuked
@slash_command()
async def testt(self, ctx : ApplicationContext, category: Option(str, "select a category!", choices=["Moderation", "Miscellaneous"], required=True), Moderations: Option(str, choices=["ban", "clear"], required=True), Miscellaneouss: Option(str, choices=["owners", "clear"], required=True)):
if category == "Moderation":
await ctx.respond("Zrobiono szefie!")
self.client.reload_extension(f"Commands.{category}.{Moderations}")
elif category == "Miscellaneous":
await ctx.respond("Zrobiono szefie!")
self.client.reload_extension(f"Commands.{category}.{Miscellaneouss}")
i have a problem with this command
0 error
s
because those are the rules in this server.
What is the problem?
import discord
from discord.commands import slash_command
from discord.ext.commands import Cog
class Ban(Cog):
def __init__(self, bot):
self.bot = bot
@slash_command(name="ban", description="Bans a member")
async def ban(self, ctx, member: discord.Member,*,reason):
if ctx.author.guild_permissions.moderate_members:
await member.ban()
await member.send(reason)
await ctx.respond(f'{member} has been banned from felbcord', ephemeral=True)
else:
await ctx.respond('You do not have the correct permissions for this',ephemeral=True)
def setup(bot):
bot.add_cog(Ban(bot)) ```
I dont see why my command isnt showing up, It used to work fine?
nvm got it
I am now getting
This command is outdated, please try again in a few minutes
using this code
import discord
from discord.commands import slash_command
from discord.ext.commands import Cog
class dmCog(Cog):
def __init__(self, bot):
self.bot = bot
@slash_command(name="dm", description="DM's someone")
async def dm(self,ctx,member: discord.Member,*, message):
if ctx.author.guild_permissions.administrator:
await member.send(message)
await ctx.respond(f'{member} has been dmed', ephemeral=True)
else:
await ctx.respond('You do not have the correct permissions for this', ephemeral=True)
def setup(bot):
bot.add_cog(dmCog(bot))```
try again in a few minutes π
yeah figured that, LMAO i am stupid
ty
haha np
Why am i getting 2 errors saying commands is not defined? I have the correct imports, is this an indentation error
you havent actually imported discord.ext.commands, just a class from it
use from discord.ext import commands
thanks
hi i need help with a problem.
i have a button which should send a message to another guild channel.
but i dont know how to access the bot object (button is placed in a cog file) in the button class
On you cog class constructor add bot parameter, and add bot attributes yourself
hmmm i need the bot to fetch the guild and tbh i dont know how to do that
class cogs(commands.Cog):
def __init__(self, bot):
self.bot = bot
Then you can acces the bot within cog class
You can also do the same on button class
the problem is that the button is outside the cog class and i tried it with cogs.bot...
and it said that this class has no attribute bot which is
weird?!
Do the same but inherit from discord.button
How do you define your button? Subclassing or instancing?
hmm but if im adding the bot in the button as attribute i need to pass it if im calling the class right
Yep
well imma try ty
light mode π
sooo my bot just decided to unregister all of its commands... I was working on one of the commands but not in any way that it would've unregistered all the commands from every cog. Now whenever I start it, it connects just fine and is able to send messages but when I enter / the bot doesn't even show up as having any options. Just wondering if anyone else is seeing this.
only thing I can think of is I added:
guild_ids=[<my server id>]
to the new command I was working on. Would that force a complete refresh for all of the bots commands?
They came back after I kicked and re-joined the bot. Not really sure what that was all about.
Is there anyway to see who's talking in a VC with a bot?
If I defer my interaction and then send a followup message, is it possible to delete that followup message?
Traceback (most recent call last):
File "c:\Users\darkm\OneDrive\Desktop\Skyler v1\bot.py", line 75, in <module>
async def languageEU(ctx, test=None):
File "C:\Users\darkm\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 914, in decorator
result = command(**kwargs)(func)
File "C:\Users\darkm\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 1551, in decorator
return cls(func, **attrs)
File "C:\Users\darkm\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 604, in __init__
validate_chat_input_name(self.name)
File "C:\Users\darkm\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 1633, in validate_chat_input_name
raise ValidationError(
discord.errors.ValidationError```
help? XD
code?
@client.slash_command()
async def languageEU(ctx, test=None):
if ctx.author.guild_permissions.manage_messages:
if test is None:
test = "EU"
db = sqlite3.connect('main.db')
cur = db.cursor()
cur.execute(f"SELECT languag FROM Language WHERE guild_id = {ctx.guild.id}")
res = cur.fetchone()
if res is None:
sql = ("INSERT INTO Language(languag, guild_id) VALUES(?,?)")
val = (test, ctx.guild.id)
cur.execute(sql, val)
embed = discord.Embed(description=f" You successfully updated Lang to **English**", color=0x23d953)
embed.set_author(name=f"{ctx.author.name}#{ctx.author.discriminator}", icon_url=ctx.author.avatar)
await ctx.respond(embed=embed)
elif res is not None:
embed = discord.Embed(description=f" You successfully updated Lang to **English**", color=0x23d953)
embed.set_author(name=f"{ctx.author.name}#{ctx.author.discriminator}", icon_url=ctx.author.avatar)
await ctx.respond(embed=embed)
db.commit()
db.close()
return
else:
embed=discord.Embed(description=" you have no Permissions for this Command", color=0xa3281a)
await ctx.respond(embed=embed, delete_after=10) ````
how do i get an "Options" menu like this in Pycord?
from discord.commands import Option
And you can do
async def func_name(ctx: first: Option(str, choices=[])):
str, βdescription in these quotation marksβ, choices=[]
Where does the description show up in the one I showed you?
O
Hmm
Iβm not sure then
Currently at work if you still need help then Iβll look for it in the docs
Thoughts on this error?
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/commands/core.py", line 126, in wrapped
ret = await coro(arg)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/commands/core.py", line 856, in _invoke
await self.callback(self.cog, ctx, **kwargs)
File "/home/runner/TESTENV-NFTDiscordBot/cogs/raffle_admin.py", line 57, in quick_setup
await ctx.send_response(embed=em, view=view, ephemeral = True)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/interactions.py", line 665, in send_message
payload["components"] = view.to_components()
TypeError: to_components() missing 1 required positional argument: 'self'
you didn't initialize the view class
omg


