#Basic Pycord Help (Quick Questions Only)
1 messages · Page 70 of 1
This is probably an error that happends very often but why did i get the error function bot.load_extension was never awaited? When i change my code from bot.load_extension o await bot.load_extension it says await outside function? That doesn’t really makes sense for me
what?
Basically if i write bot.load_extension() without await in my code the error is courutine bot.load_extension() was never awaited and if i do it with await it says await outside function.
And sorry for my englisch i really don’t know how courutine is spelled i hope you can understand it
pip list in terminal/command prompt/powershell and send output
do you know basic python?
bro im about to shoot myself, stop asking that question.
lol
I use a hoster to yk host the bot and this panel doesn’t have a terminal. I can input something in a field below the console but it doesn’t do anything
code?
you are not responding to the buttons and why do you use "/" as a prefix for prefix commands?
Idk how to do that
how do i make it respond to the buttons
use response?
Learn all about implementing buttons in your Discord Bot using Pycord.
^
I got it somehow
you have discord and discord.py installed
What should i deinstall? And i didn’t import any of these i just imported pycord
? uninstall discord, discord.py and py-cord and reinstall py-cord
Ok sec
pip uninstall discord.py discord py-cord -y
pip install py-cord
It works now thank you both
Can I edit a specific follow up?
Like prompt = await interaction.followup.send()
and then await prompt.edit()
or is my IDE tricking me about it not being possible?
Hello Guys Quick Question how can i put my easy~pil coded picture in a embed like how do i get the url
?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)```
yes
file path is this C:THispc/User/projects thing?
am i right?
yes
where is the image gonna be send in then
output or discord
ohhhh
the path is the place where the picture is located
good
i tought it is gonna be saved there
i made an code easy-pil but how do i make a easy-pil co´de to a picture
that's not Pycord related.
danke
what is this called (in terms of web dev)?
Preview or preview embed I think
Great question tho
It's a meta element
doesn't seem like it
that seems to be it, thanks
Does anyone know if a custom commands handler where you can create custom commands that even supports arguments? Kind of like Carl’s typescript.
If I have snowflakes of channels I want to delete, can I just do:
channel = discord.abc.GuildChannel(id)
await channel.delete()
?
yes
Btw that is dpy. Not py-cord
You should do this too ^
Check this
https://github.com/phenom4n4n/TagScript
Yes that is possible because followup.send returns the webhook message object
Can pycord wait for message?
.rtfm wait_for
show how you used it
try:
amount = await bot.wait_for("message", timeout=20) # 30 seconds to reply
except asyncio.TimeoutError:
await ctx.respond("Pertanyaan tidak dijawab, Ulangi!")```
that try have indent
All intents
hm
Which one wrongs
you didnt use checks
you bot could be getting messages from any server, any channel, any user
i suggest using a check for ctx.author and ctx.channel
.rtfm wait_for
Im makin message command
that has an example
message command like the context menu msg cmd?
Ye ikr, thx
Yep
you could use modals yk
oof 
Bruhhhh
Just an easy check that return message content
BRUHHH it do read
It read the bot message
:l
It read itself like bruh
That's why you need a check
That depends on what conditions you want to wait for. You might also need to check if it's the right channel, if it's the right member sending the message, if it's in the right server.
.tias
Yep
You can't use Discord emojis in the footer. It has to be a unicode character
you can get the unicode emoji version if you put a \ before emoji and send it
copy paste that
eg send \💰 to get \💰
\💰
will work
I can't send a keyboard interrupt to stop the bot process. Is this a new thing with pycord?
do you have a bare except: anywhere?
change that to except Exception:
Because a bare except: will suppress a KeyboardInterrupt
but KeyboardInterrupt is not a subclass of the base Exception class
unlike most other errors
Nope i don't, but I think I've discovered the function that's causing it. This below:
# main.py
bot.loop.create_task(DatabaseAdapter().ainit())
async def ainit(self):
self.reports_conn = await aiosqlite.connect(self.reports_db)
async with self.reports_conn.execute("SELECT id FROM report") as cur:
self._all_records_ids = await cur.fetchall()
self.infractions_conn = await aiosqlite.connect(self.infractions_db)```
I don't see a reason why that would suppress keyboard interrupt though
hmm yea i dont see it either
try adding a print statement to see till where the code is being run. or use a debugger
Exception handler is loaded
Help.cog is loaded
Infractions.cog is loaded
IO.cog is loaded
Reports.cog is loaded
Setting up DB connections.
DB connections set.
+-------------------------+
| Prototype is on standby |
+-------------------------+```
async def ainit(self):
print("Setting up DB connections.")
self.reports_conn = await aiosqlite.connect(self.reports_db)
async with self.reports_conn.execute("SELECT id FROM report") as cur:
self._all_records_ids = await cur.fetchall()
self.infractions_conn = await aiosqlite.connect(self.infractions_db)
print("DB connections set.")```
function definitely finishes executing
Oh I see
Database setup <Connection(Thread-2, started 20580)> and <Connection(Thread-3, started 14204)> []```
the connections are in different threads for some reason
is there a function I could implement that gets invoked before the bot shuts down? (think I need to .close() the connections)
Also isn't aiosqlite supposed to be single threaded?
yes
you would need to subclass bot
and override the init
so smth like this
async def close(self):
# stuff
await super().close()
thats true
Gotcha, this does get invoked when a keyboard interrupt is sent right?
yes
try passing bot.loop to the connect function
async def ainit(self, bot):
if self.reports_conn is None:
self.reports_conn = await aiosqlite.connect(self.reports_db, loop=bot.loop)
async with self.reports_conn.execute("SELECT id FROM report") as cur:
self._all_records_ids = await cur.fetchall()
if self.infractions_conn is None:
self.infractions_conn = await aiosqlite.connect(self.infractions_db, loop=bot.loop)
print(f"Database setup {self.reports_conn} and {self.infractions_conn}.")```
set it to this ^
still seems to be threaded 😮💨
Is it possible to set an ApplicationCommand visibility to only owner?
Not possible
You could do Administrator but that would be kinda for the Owner of the Server
And you didn't say for which Owner
Which owner?
Ohh
My bad, i meant the bot owner (this is a restart command)
aiosqlite does run a thread in the background for the actual sqlite connection
Ah I see
I've never had this problem previously with aiosqlite
which is very peculiar
add reaction problem:
Yes the bot have the perms to react
Andreas got reacted perfectly fine
Luc was supposed to get the same reaction but it prompted this error instead
Any clues as to what could be causing this?
I mean Bot or Server Owner ^^ and no that is not possible
"reaction blocked"
if he blocks the bot it will prompt this error?
does the bot has the permissions to add emojis?
yes.
it got admin perms
ok apparently he blocked the bot, so thats why it prompted this reaction blocked
Gotcha, how about with server roles?
Only permissions sadly
How about permissions to see specific channels?
yes but this is with discord permission and not py-cord one
i have stored
"hello" : "🪙"
in a json and it return weird characters when i access them.
it returns - 🪙
oh no I meant slash commands specific to only those who can see a channel, or to specific channels
encoding="UTF-8"
is there a guide to export a log file from the bot upon a command?
like I want the bot to send the file logs.log after the command ~~log
Im not sure if this is possible
and how
alright, thanks eitherways 👍
Is there a component just to display large text (not input) for modals?
nope
https://docs.pycord.dev/en/stable/api/data_classes.html#discord.File
just pass filename and send it
Some classes are just there to be data containers, this lists them. Unlike models you are allowed to create most of these yourself, even if they can also be used to hold attributes. Nearly all clas...
So... I just ran into a weird issue. I am getting an exception for an unknown interaction when sending a reply, but the line it tags does reply...
python error messages make no sense.
send code and traceback
if guild is not None:
await interaction.response.send_message(content="This guild has already been registered.", ephemeral=True)
return
```The code.
can you show more?
do you use that in a button/menu/modal or slash command?
thats literally the first line in a slash_command. dont think its relevant.
also the guild var isnt a discord.Guild. its a model.
but it always returns none or a model
do you use discord.py or py-cord?
Here's the slash basic example.
wow. thats why. thank you! 🙂
Right, and uh, the example doesn't show it, but does the slash decorator also allow you to specify permissions for the command or descriptions for the autocomplete?
Learn all about Slash Commands and how to implement them into your Discord Bot with Pycord!
Does someone know how i can use these timestamps fpor my bot? (i mean these: <t:8639998955999:R>)
this answers my question about description, but not permissions.
Do I just need to handle checking in my command function?
going to check discord.Options I guess. There really should be a basica example of that.
its like the normal prefix commands with discord.default_permissions
Never once used prefixed though. And I checked the pycord guide page for prefixed commands and did not see an example either. :/
Here's the slash perms example.
Got it for perms. So actual role checking cant be done in a similar way? I have looked at the other examples in the repo.
But you know basic python?
Look, you are being awfully rude about this. Stop telling me to rtfm when the manual is clearly lacking. I'm asking for a pretty basic thing: Do I need to just check for a role in the command itself, or can I can use the decorator to simplify things?
First, you linked me to pycord guide. Which did not have the answer I asked for. Then you told me "oh, its like the (legacy) prefixed commands. Okay, so I check that page on pycord guide. Nope. Then, instead of replying that it was an example only on github for some reason, you use a bot command which still didnt answer me.
I'm not stupid. Stop treating me like it in a help channel.
It is no big deal if I have to check. I just wanted to know if there was a better way that wasnt clearly documented. :/
for prefix commands it would be commands.has_permissions and for slash commands discord.default_permissions what would hide the slash command from users
but Im not sure if you still can see them and if they are 100% working like the commands.has_permissions one
right but thats only default permissions it appears. I'm trying to check for a custom role. So like, restricting access by roleid.
for that you could do "if else" or has_role
again, I know how to check in function. point was if there was a shortcut in the decorator similar to permissions, description, name, etc.
clearly there isnt. so nevermind.
at the slash command one?
I think I am also a little confused x3
I have way to much open at the same time
Hi guys, is it possible to edit a message (via interaction.response.edit_message from a slash command) so it contains a Paginator ? I do with Paginator.respond for now but it sends another message, I would like it to be edited in the original response
Thanks 😄
I'm current trying to move a role (custom_role) until it's above another role (bottom_divider) with this code:
while custom_role <= bottom_divider:
print(True, custom_role.position)
await custom_role.edit(position=custom_role.position+1)
This is the output:
True 1
True 1
True 1
...
Why is this happening and how can I fix it?
Or, are there any ways of consistently setting a role's position to be right above another role?
await custom_role.edit(position=bottom_divider.position) does not work consistently: the role is sometimes placed a few roles below bottom_divider
Maybe your bot's role is under the role you are trying to reach so it can't ? (i'm not sure if it's the same as users who can't change roles above them even if they are admin)
Nope, my bot's highest role is above both roles
hmm sorry in that case i can't help :/ (never used this ^^)
alr, appreciate your help anyways
Is the <= operator comparing the positions ? As I see underneath u use custom_role.position, maybe use while custom_role.position <= bottom_divider.position
from the documentation
yeah just saw while looking so nvm u are right
Use unix in python then format it into the designated form.
.rtfm utils.format
not really ngl
the paginator isnt implemented the best way it should have been
||whatever happened to @rare ice improving it 💀 ||
Ok ok thanks, that’s what I thought, it’s not considered a view so we can’t just pass it into edit_message, I’ll just delete the old response then (it’ll be a little ugly since it’ll respond to a deleted message but meh it’ll do)
eh you might get stuff to work using some workarounds
paginator is actually a subclass of discord.ui.View
Oh ok thanks. yeah I’ll try a workaround then, I’ll tell you if I can make it ^^
yea cool. go through the source of respond and send and see what all is happening
oh fuck wait
.rtfm paginator.edit
Wtf wait a sec lmao
so sorry lol
Nah it’s me lmao I didn’t look in depth at the documentation (I used vscode with autocompletion and the description of the methods so I must’ve missed the edit)
Thanks a lot then ^^
haha
Although this doesnt use interaction.response.edit_message
so you will have to defer and then use the edit method
Nice thanks 😃
@proud mason i think u can help me now, sorry for ping
I remembered that if suddenly the host is somewhat unstable and I need to somehow connect to the message with the button so as not to restart the button cmd
check your DM's
Here's the persistent example.
See this ^
TY ❤️
I can't achieve it (sorry :x), seems like it can't create the message in the method (the interaction.message isn't None but the methods returns None (so i think it can't create it))
I think you would need to defer before editing
I tried too same problem
but I'll just delete the old and send a new
Do you access reactions via await msg.reactions[0].users().flatten() or something? Since when i do that it says list index out of range
Snippet of code im using (not full):
channel = ctx.guild.get_channel(12345) #this isn't the problem
msg = await channel.send(f"{giveawayrole.mention}", embed=embed) #nor this, this works
await msg.add_reaction("🎉")
await ctx.respond ("Giveaway created!", ephemeral=True) #I do defer before this
await asyncio.sleep(time*86400) #Time is chosen by user in the inputs
users = await msg.reactions[0].users().flatten() #This is where the error happens
```Nobody else can add reactions in my case
There are reactions on the message when the error happens
nvm i figured out a way to do it
So the command worked successfully but afterwards it showed that message any fixes?
Except await ctx.defer() -> cause then the bot is thinking...
do you respond to the slash command?
do you use ctx.respond?
No,ctx.send
you have to use ctx.respond
Can you explain why?
interactions require a response.
you have to respond to interactions
Slash Commands are a type of interaction.
What ctx.send does is send a message in the channel, not related at all to responding to the interaction.
Yeah, I realized that was very retardedto ask ty guys
it's not.
Say I want to resolve a snowflake to a channel and then delete it, what would that look like?
I tried:
channel = discord.abc.Snowflake(id)
await channel.delete()
``` but I get protocols cannot be instantiated.
I see that there is a class for discord.abc.GuildChannel, but when I use that I see constructor takes no arguments.
~~ You can use Partial objects. https://docs.pycord.dev/en/master/api/clients.html#discord.Bot.get_partial_messageable ~~
Bots: Attributes activity, allowed_mentions, application_flags, application_id, auto_sync_commands, cached_messages, cogs, debug_guilds, description, emojis, extensions, get_command, guilds, intent...
Actually nvm. I think you actually need the channel object itself
okay, so I just need to make two calls? one to grab and one to delete?
I need to do something similar for roles. wasnt sure if there was a way to save on calls though.
since I am doing it in batch, assume fetch_roles then grabbing what I need is better than two calls per role. I dont remember if roles had a plural equivalent. I need to look
ah, it does. good.
too bad there isnt a batch delete.
okay so uhm;
icon_url=ctx.guild.icon.url
I basically have that in my embed footer but I realised that this does not work for servers without a set icon... how do I fix this?
ctx.guild.icon returns NoneType when the guild has no server icon set 
nvm just put an if statement which only shows the footer text without an icon if the ctx.guild.icon == NoneType
How can I get a dictionary object of a discord.Message’s data?
I feel like I am probably using defer wrong:
await ctx.defer()
seems to hang. Do I actually have to specify ephemeral and invisible or something?
as in, infinite loop. nothing else in the function or any other executes.
Show your code
Sure. Sorry for the delay. had to step away for a bit.
async def configure(self, ctx: discord.ApplicationContext):
await ctx.defer(ephemeral=True)
#...code
If I change this to ctx.respond(content) and just use edit_original_message later, it works with no issues.
How do you send the response after deferring?
Try message.__dict__
See what you get
is there any way to get a message just from it's id?
Only if it's cached, Otherwise you need the Channel/Guild IDs
ah ok thanks
how this bot have no online status ?:>
i mean if this is websocket playing that will be so epic
hi om nom, It doesn't matter. I am not getting input from other functions either. I cant even see a print after.
They are using the interaction endpoints only by receiving HTTP POSTs rather than over a Gateway with a Bot user.
there is any way to make it with pycord or edit in the activity functions to make something like this "examples will help :>"
atm, nope
This has nothing to do with activity/status.
how they did that 
You were literally told how they did it here
When I use any of the following two lines to move a newly created custom_role right below the top_divider role:
await custom_role.edit(position=top_divider.position-1)
await guild.edit_role_positions(positions={custom_role: top_divider.position-1})
The custom_role is always moved a few roles below the top_divider, and not directly below it. Why is this happening and how can I fix it?
huh
yeah something weird is going on. I am getting outputs now, but something inexplicably broken
to do smth like that, you would need an aiohttp webserver or smth like fastapi/quart
/flask (they have async support, afaik)
flask async isnt great. but yes, since it wont be paired with a discord bot, it should be fine
okay, so I have an update. it seems to be hanging when creating the roles. if I disable the create role line it works. tf
for key, role_template in role_templates.items():
print(role_template['name'], type(role_template['hoist']))
role = await guild.create_role(name=role_template['name'], hoist=role_template['hoist'])
print(role)
role_templates is just a dict mapped with role names and hoist for now. If I comment out the role creation line, it loops through all entries. If I dont, it goes through one iteration and stops. No exceptions or errors. 
modals can have dropdowns 🤨
Why slash commands may not be updated?
Does anyone have any ideas on how I can make adding and removing the select menus better or is this already a good way to do it? 🙂
how can I get the members avatar URL as png?
I've tried this:
profile_picture_url = str(member.avatar_url_as(format='png'))
thanks
is it a good practice to put all the imports into separated classes?
Anyone an idea? 🙂
Task exception was never retrieved
Traceback (most recent call last):
File "D:\DiscordBots\EconomyBot\cogs\economy_commands.py", line 38, in on_timeout
await self.message.edit(view=None)
^^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'edit'```
```py
class Pagination(discord.ui.View):
def __init__(self):
super().__init__(timeout=5.0)
self.current_page = 1
async def on_timeout(self):
await self.message.edit(view=None)```
Got into an error
can you add ```py
for child in self.children:
child.disabled = True
nope doesnt work
async def on_timeout(self):
for child in self.children:
child.disabled = True
await self.message.edit(view=None)```
what is the py-cord version?
2.4.1
I fixed it
It seems that when i edit a message with the view it doesnt register the message
bug? prolly?
wait did you fix it or just find the issue?
both ig
.tag slashnoshow
Checklist for Application Commands Not Showing Up:
• Does your bot have the application.commands scope?
• Are you loading cogs before on_ready and on_connect?
• Is on_connect not overridden?
• Did you update to the newest version of py-cord (tag: install)?
• Is User Settings > Accessibility > Chat Input > Use legacy chat input turned off?
• Did you share your code and errors?
• Do you still have libraries that conflict with the discord namespace (e.g. discord.py)?
Different topic but same checklist
view.message is not set when it is sent by editing a message
so what can i do then
There is an open PR to fix this
Till that time, you can do
view = MyView()
await message.edit(... , view=view)
view.message = message
i did something like this
def __init__(self, msg):
super().__init__(timeout=5.0)
self.msg = msg
async def on_timeout(self):
await self.msg.edit(view=None)
view = Pagination(msg=ctx)
await ctx.edit(embed=embed, view=view)```
i guess it works
Not possible with Slash cmds. Input type can be a single type only
Discord limitation
Oh okay
Why does the example show double types
Does discord.VoiceChannel here refer to text channels inside voice channels?
That is because they are both Channels. You were doing channel and role. That is not allowed
One of my cogs in not loading, but I don't know why. I'm guessing there's an error, but it's not displaying in console. I remember there was a way to show errors in cogs, but can't remember how
Do you have a try, except around your load_extension(s)? If you do, remove it and the error will be printed.
I'm running this and doing the command, it simply does nothing
yes right below the flavor command it has the bot.run(token)
it does nothing
discord.Bot with a prefix lol
it was empty before, so how do I call a command without a prefix?
just say the word and thats it?
discord.Bot are slash commands not prefix commands
discord.Bot would register commands as a slash command.
If you are looking for text-based commands, you would be looking for commands.Bot
Or on_message if you don't want a prefix
Not recommended (slow) and discord might not verify if you want to use onymessage tho
no, they will verify you and your bot will simply not work.
?tag client
discord.Client # just for events
discord.Bot # events + slash/user/msg commands
commands.Bot # above + prefixed commands
bridge.Bot # above + bridge commands (application commands and text commands in one)
https://docs.pycord.dev/en/master/intents.html
https://discord.com/developers/docs/topics/gateway#gateway-intents
import discord
from discord.ext import commands
# Get specific intents for fine control
intents = discord.Intents()
intents.emojis = True
intents.guilds = True
intents.messages = True # Required for prefix commands!
...
# Get all non-priveliged intents; this excludes presences, members and message_content
intents = discord.Intents.default()
# Set priveliged intents: these must be enabled on dev portal
intents.members = True
intents.presences = True
intents.message_content = True # Required for prefix commands >= 2.0.0b5
# Get all intents; all intents must be enabled on dev portal.
intents = discord.Intents.all()
# Apply intents when creating your bot
bot = commands.bot(prefix="?", intents=intents)
In version 1.5 comes the introduction of Intents. This is a radical change in how bots are written. An intent basically allows a bot to subscribe to specific buckets of events. The events that corr...
Don't forget those ^ @worldly schooner
No, I dont
I have already identified my problem, but I would like to have errors in the future
thanks for all the help!
Are you setting the store parameter to True when loading cogs?
Also what Py-cord version?
No
2.4.0
To clarify, I do get errors when the cog loads correctly, but something goes wrong during command handling. But I don't get errors when the cog fails to load
Is there a way to have a slash_command visible only for the bot owner?
for owner commands as an example
or just dont use slash commands, use prefix commands instead right?
you could register owner only slash cmds to a private guild with only you and the bot
Another problem I have, is autocomplete for options in slash commands don't really work. Only the first 25 options are shown, no matter what the user wrote.
async def test_autocomplete(ctx):
return [str(x) for
x in [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30]]
@discord.slash_command(
name="test",
description="test",
)
async def test(
self,
ctx,
test: discord.commands.Option(
str,
description="Thing you want to test",
autocomplete=test_autocomplete,
required=True,
),
):
await ctx.respond("test", ephemeral=True)
Am I doing something wrong?
only the first 25 options will be shown. filter the list you show based on what the user types
that doesn't happen automatically?
is there a guide for that?
no. easy way would be adding if str(x).startswith(...) ... would be user input for the option
just add guilds_ids=[12345] to the command decorator
where 12345 is the guild id
tysm!
is there any way to do this better?
I use it to prevent any formatting in an embed based on user input obtained somewhere
~~Hey guys quick question: I use bot.get_user() with an ID to get a user's avatar (using the guild.fetch_member() is too long for some reason it takes 5s for 23 members) but bot.get_user() returns None each time (with both ids of ppl who are in the test server and ids of ppl who aren't), do you have any idea what I might be doing wrong ?
Here's the part of my code that uses it
tmp = self.bot.get_user(id)
print(id, tmp) # debug
if tmp != None: self.set_thumbnail(url=tmp.display_avatar.url)
The goal is to display the user's avatar on an embed (and my test server uses another server database to try so the members ids are not all on the test server (so guild.fetch_member is not a good idea + it's too long for some reason)~~
nvm found the answer (using bot.get_or_fetch_user())
Well to avoid copy / pasting I would use a list (+ it's easier to add or remove new char / substrings) but otherwise idk another method to do it
I would do something like that
# Define all unwanted chars / substring here or somewhere else
UNWANTED_SUBSTRINGS = ['*', '_', '~', '`', '|', '>', '[', ']']
def sanitize(text: str) -> str:
for substring in UNWANTED_SUBSTRINGS:
text.replace(substring, "")
return text
But maybe there's a method in pycord to avoid formatting
meh, thought there was some kind of built in function which would allow me to do this :P
Nonetheless thank you :)
Maybe there are, i'm pretty sure I already saw something about formatting (but maybe it was the other way around)
You can't do that with py-cord
oh
will that come tho
in the future for pycord
Hmm I'm not sure
do u know any other api wrapper that have linkedroles
I don't think so, but check PRs and Issues if smth is open
None of the ones ik offer that
Regex could be nice
Regex?
yeah regex
regular expressions
it is used for pattern matching
can be used for simple stuff as well as really complex shit
it is a built in python module
has a method for substitute
Is there any way to get an asset by it's cdn.discordapp.com link?
perform a GET request on the link
use aiohttp
hmm I'll look into it thanks
bot join the voice but plays nothing what is wrong?
channel = client.get_channel(int(NONE))
voice = await channel.connect()
source = FFmpegPCMAudio('NONE.mp3')
player = voice.play(source)
await ctx.send("Playing audio")
Hey, there in my bot every time an user create a ticket it gets stored in a .json file with this code.
ticket_data = {
"creator_name": interaction.user.name,
"creator_id": interaction.user.id,
"create_time": time.strftime('%H:%M:%S')
}
with open("data\created.json", "r") as file:
data = json.load(file)
data[ticket_channel.id] = ticket_data
with open("data\created.json", "w") as file2:
json.dump(data, file2, indent=2)
Anyway i would like to add a filter so an user can't create more than X tickets, so i need to check in this file how many keys creator_id have x value. But i really don't know how i would do it. Anybody could please help me. Thanks
oh by the way; you forgot to modify the original string.
UNWANTED_SUBSTRINGS = ['*', '_', '~', '`', '|', '>', '[', ']']
def sanitize(text: str) -> str:
for substring in UNWANTED_SUBSTRINGS:
text = text.replace(substring, "") # Here you forgot to put text = ...
return text
oops yeah sry
?tag nojson
Why not to use json files for data storage
JSON files are commonly used to store data that is read by a program, however, they are unsuitable for storing dynamic data due to a number of reasons.
It is recommended to use a DBMS (Database Management System) as they come with optimized technologies for storing and retrieving information.
Advantages of using a database:
- Database tables can be related, making it easy to separate your information into multiple tables and only fetch what you need
- Databases allow you to use a query/data processing language to make complex data operations easier with less code
- One misplaced character will corrupt an entire file. A database very rarely experiences corruptions due to their automatic handling of data integrity
- Transactions in SQL databases allow you to revert unwanted changes and prevent data corruption in the case of an error
- Databases have support for indexes, allowing retrieval of some data to be extremely fast
- It is very easy to update existing data in a database, as opposed to re-writing a file
- Databases are reliable
Popular database management systems:
- SQLite3
- MongoDB
- PostgreSQL
- MySQL
- MariaDB
- Microsoft Access
lol no worries just thought of telling you xD
iirc, your source needs to be like this
source = discord.PCMVolumeTransformer(discord.FFmpegPCMAudio(query))
examples/basic_voice.py lines 76 to 79
source = discord.PCMVolumeTransformer(discord.FFmpegPCMAudio(query))
ctx.voice_client.play(
source, after=lambda e: print(f"Player error: {e}") if e else None
)```
Does anyone have any ideas on how I can make adding and removing the select menus better or is this already a good way to do it? 🙂
I'm trying to install pycord on my server with this command: python3 -m pip install -U py-cord
But it only install pycord 1.7.3 and not 2.4
I'm getting this error
Task exception was never retrieved
future: <Task finished name='Task-35' coro=<ApplicationCommandMixin.on_application_command_auto_complete.<locals>.callback() done, defined at /home/runner/MCPedia/venv/lib/python3.10/site-packages/discord/bot.py:853> exception=NotFound('404 Not Found (error code: 10062): Unknown interaction')>```
But everything works. Is this something that I've done, or is this some issue with the library?
Traceback:
Traceback (most recent call last):
File "/home/runner/MCPedia/venv/lib/python3.10/site-packages/discord/bot.py", line 856, in callback
return await command.invoke_autocomplete_callback(ctx)
File "/home/runner/MCPedia/venv/lib/python3.10/site-packages/discord/commands/core.py", line 1011, in invoke_autocomplete_callback
return await ctx.interaction.response.send_autocomplete_result(
File "/home/runner/MCPedia/venv/lib/python3.10/site-packages/discord/interactions.py", line 1017, in send_autocomplete_result
await self._locked_response(
File "/home/runner/MCPedia/venv/lib/python3.10/site-packages/discord/interactions.py", line 1090, in locked_response
await coro
File "/home/runner/MCPedia/venv/lib/python3.10/site-packages/discord/webhook/async.py", line 219, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction```
what is the python version?
that happend the most of the time if the python is not 3.8+
I have a .yml config file where the user should be able to define the color of the button, i already have parsed it but i dont know how to concat it without getting an error
button_color: green
style=discord.ButtonStyle. < What i put here?
.green
Maybe i didnt explain it very well, i want to get the value of button color in the style of the button. But i dont know how to achieve it, so for example if the user select danger it should change
You can't do it like that, that's not how code works. You need to store a dict of the corresponding values to your strings
Traceback (most recent call last):
File "/home/container/.local/lib/python3.10/site-packages/discord/ui/view.py", line 427, in _scheduled_task
await item.callback(interaction)
File "/home/container/cogs/Create.py", line 92, in callback
await Creation.generate_make_ticket(
File "/home/container/cogs/Create.py", line 271, in generate_make_ticket
channel = await guild.create_text_channel(
File "/home/container/.local/lib/python3.10/site-packages/discord/guild.py", line 1355, in create_text_channel
data = await self._create_channel(
File "/home/container/.local/lib/python3.10/site-packages/discord/guild.py", line 1213, in _create_channel
payload = {'allow': allow.value, 'deny': deny.value, 'id': target.id}
AttributeError: 'NoneType' object has no attribute 'id'```
I broke it, halp. 
oh no
what version of pycord is this? (this isn't relevant but update anyway)
oh wait i see
did you pass overwrites to create_text_channel?
Yes it's being passed
class DropdownServersList(discord.ui.Select):
def __init__(self,bot,title,check_linked,answered_questions):
self.bot = bot
self.title = title
self.check_linked = check_linked
self.answered_questions = answered_questions
super().__init__(options = None , placeholder="Click Here",min_values = 1,max_values=1)
async def callback(self, interaction: discord.Interaction):
#Now all the info has been collected eg the questions answered actually make the ticket
await Creation.generate_make_ticket(
self.bot,
interaction,
interaction.guild,
interaction.user,
self.title,
self.check_linked,
self.answered_questions,
server_name=self.values[0]
)```
can you show how you've defined overwrites?
#SetChannelPermissions
overwrites = {guild.default_role: discord.PermissionOverwrite(view_channel=False,send_messages=False, read_message_history=False)} ```
#PhsyicallyMakeTheChannel
try:
channel = await guild.create_text_channel(
name=f"{ticket_type_info['ChannelShortname']}-{newticket_num}",
overwrites=overwrites,
category=category
)
except (discord.HTTPException, discord.Forbidden):
if not autogenerated:
return await interaction.response.send_message(content=f"**Error** : We currently have too many of those tickets - please try again shortly",ephemeral=True)
if not autogenerated:
member_id = member.id
member_name = member.name
else:
member_id = None
member_name = None```
I have these two sections
is guild.default_role returning a real role?
it looks like it's None
yeah but what happens when you try to print it, for example
Issue we're having is that, all categories except for payment support aren't working.
https://i.imgur.com/FRyVInd.png
I've confirmed that the bot has access to the categories and correct permissions, the category ID's match up and it's intents are on.
aight lemme lay it out a bit clearer
This is your errorpy File "/home/container/.local/lib/python3.10/site-packages/discord/guild.py", line 1213, in _create_channel payload = {'allow': allow.value, 'deny': deny.value, 'id': target.id} AttributeError: 'NoneType' object has no attribute 'id'In this code, only target.id can cause the error. So we first figure out what target is in the function:py for target, perm in overwrites.items():this is looping through each key-value pair in your overwrites dict, which is py {guild.default_role: discord.PermissionOverwrite(view_channel=False,send_messages=False, read_message_history=False)}As such, target is guild.default_role
and thus, guild.default_role must be None for some reason when you're creating the channel
so how does default_role work? all it does is attempt to return a role matching the guild's ID, the @ everyone rolepy @property def default_role(self) -> Role: """Gets the @everyone role that all members have by default.""" # The @everyone role is *always* given return self.get_role(self.id)If this isn't working, it means your role cache is disabled for some reason
Am I able to create a gc with you and the owner to speak about this? 😅
uhh you don't really need to, if you want you can open up a forum thread via #969574202413838426 or we can just troubleshoot here idk
Inviting owner here
Hey @cyan quail I'm owner of the discord that the bot is running in
all
it was working and it randomly stopped
it works for our payment support tickets but not our others
hmmm it shouldn't really be a category issue...
could you try printing
guild.rolesguild.default_role
and let me know the results
but our linking system is also down (at the same time)
when i try doing the link command to pull their steam64 that's linked to their discord it gives this error
Traceback (most recent call last):
File "/home/container/.local/lib/python3.10/site-packages/discord/client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "/home/container/main.py", line 47, in on_command_error
raise error
File "/home/container/.local/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 1350, in invoke
await ctx.command.invoke(ctx)
File "/home/container/.local/lib/python3.10/site-packages/discord/ext/commands/core.py", line 1023, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "/home/container/.local/lib/python3.10/site-packages/discord/ext/commands/core.py", line 238, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'members'```
not sure if it has any connection
can you show the code triggering that?
that could troubleshoot the issue further
import re
import json
import logging
import discord
import asyncio
from discord.ext import commands,tasks
import logging
logging.basicConfig(level=logging.INFO)
with open("config.json", "r") as f:
data = json.load(f)
client = commands.Bot(command_prefix="+", intents=discord.Intents.all())
with open("config.json", "r") as f:
client.data = json.load(f)
client.embed_hex = int(client.data["Hex_Color"].replace("#", "0x"), 16)
@client.event
async def on_ready():
print(f"\nWe have logged in as {client.user}\n")
@client.event
async def on_message(message: discord.Message):
if message.author.bot or not message.guild:
return
await client.process_commands(message)
@client.event
async def on_command_error(ctx, error):
if isinstance(error, commands.MissingRequiredArgument):
await ctx.send("Please pass in all required arguments")
elif isinstance(error , commands.CommandNotFound):
return
elif isinstance(error, commands.errors.MissingAnyRole):
await ctx.channel.purge(limit=1)
await ctx.send(f"{ctx.author.mention}, You don't have perms for this command ")
else:
raise error
extensions = [
"cogs.AddRoles",
"cogs.BotStatus",
"cogs.StaffCommands",
"cogs.SyncFromMain"
]
async def main():
if __name__ == "__main__":
async with client:
for ext in extensions:
await client.load_extension(ext)
await client.start(client.data["BOT_TOKEN"],reconnect=True)
asyncio.run(main())
Line 47: else: raise error
well that's just the error handler
ofc
but the error itself is being caused by the command
not quite sure which since that doesn't seem to be the full traceback
ERROR:discord.client:Ignoring exception in on_command_error
Traceback (most recent call last):
File "/home/container/.local/lib/python3.10/site-packages/discord/ext/commands/core.py", line 229, in wrapped
ret = await coro(*args, **kwargs)
File "/home/container/cogs/StaffCommands.py", line 19, in linked
StaffList = await utilmisc.build_stafflist(self)
File "/home/container/utils/util.py", line 29, in build_stafflist
Member_List_From_Roles = Management.members + Operations.members + SAdmin.members + Admin.members + TAdmin.members + SMod.members + Mod.members
AttributeError: 'NoneType' object has no attribute 'members'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/container/.local/lib/python3.10/site-packages/discord/client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "/home/container/main.py", line 47, in on_command_error
raise error
File "/home/container/.local/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 1350, in invoke
await ctx.command.invoke(ctx)
File "/home/container/.local/lib/python3.10/site-packages/discord/ext/commands/core.py", line 1023, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "/home/container/.local/lib/python3.10/site-packages/discord/ext/commands/core.py", line 238, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'members'```
could it be the fact we don't have smod.members anymore?
the array
could be getting confused?
so presumably all those variables are roles
correct
meaning you either deleted a role or you got the ID wrong
"CommunityRoleID":1049046310709366857,
"Management_role_id": 896145297128955974,
"Operations_role_id":959002629533499402,
"SAdmin_role_id": 896145295543533588,
"Admin_role_id": 895995833382748241,
"TAdmin_role_id": 899385196313452575,
"SMod_role_id": 896145522870603816,
"Mod_role_id": 895995793339715614,```
could that be the main issue for this bot?
possibly
try printing all of those variables (Management, Operations, SAdmin etc.)
and see which show up as None
okay I fixed that
so back to the original question, does printing guild.default_role show the correct role?
let me double check
it's not defined anywhere
i mean when you have e.g. interaction.guild or ctx.guild in some function
what shows when you print interaction.guild.default_role, for example
nothing
what if you change it to print interaction.guild.roles
where am i printing this btw?
sorry, I'm not a developer he's currently asleep but we have active players trying to make ticket's that's all 👍 so just trying to look for a fix
basically any command function or button/dropdown callback that has interaction or ctx in the args
might be better to open a separate thread for this
yeah
could I not screenshare this for you?
overwrites = {guild.default_role: discord.PermissionOverwrite(view_channel=False,send_messages=False, read_message_history=False)}
for role_id in ticket_type_info["RolesInChannel"]:
overwrites[guild.get_role(role_id)] = discord.PermissionOverwrite(view_channel=True,send_messages=True,read_message_history=True,embed_links=True,attach_files=True)```
only thing I see with
guild.default_role:
is this ticket_type_info["RolesInChannel"]
or if not, do show how it's defined
that's from the linking system
so someone deleted a role 😦
as long as all the IDs in there are real roles and integers, your tickets should work again.
makes sense
got it, it was one it was meant to be removing
let's see if it fixes it
Done all that, fixed all the roles within config, still doesn't work
same error
ERROR:discord.ui.view:Ignoring exception in view <DropdownServersViewList timeout=60 children=1> for item <DropdownServersList placeholder='Click Here' min_values=1 max_values=1 disabled=False options=[<SelectOption label='Atlas - US 5x | No BPs | Kits | JUST WIPED 04/11' value='Atlas - US 5x | No BPs | Kits | JUST WIPED 04/11' description=None emoji=None default=False>, <SelectOption label='Atlas - EU 5x | No BPs | Kits | JUST WIPED 08/04' value='Atlas - EU 5x | No BPs | Kits | JUST WIPED 08/04' description=None emoji=None default=False>, <SelectOption label='Atlas - AU 5x | No BPs | Kits | JUST WIPED 04/04' value='Atlas - AU 5x | No BPs | Kits | JUST WIPED 04/04' description=None emoji=None default=False>, <SelectOption label='Atlas - Development' value='Atlas - Development' description=None emoji=None default=False>, <SelectOption label='Atlas - US 2x Main | Vanilla | 03/21' value='Atlas - US 2x Main | Vanilla | 03/21' description=None emoji=None default=False>, <SelectOption label='Atlas - US Mondays 3x | No BPs | Just Wiped! 02/27' value='Atlas - US Mondays 3x | No BPs | Just Wiped! 02/27' description=None emoji=None default=False>]>
Traceback (most recent call last):
File "/home/container/.local/lib/python3.10/site-packages/discord/ui/view.py", line 427, in _scheduled_task
await item.callback(interaction)
File "/home/container/cogs/Create.py", line 92, in callback
await Creation.generate_make_ticket(
File "/home/container/cogs/Create.py", line 271, in generate_make_ticket
channel = await guild.create_text_channel(
File "/home/container/.local/lib/python3.10/site-packages/discord/guild.py", line 1355, in create_text_channel
data = await self._create_channel(
File "/home/container/.local/lib/python3.10/site-packages/discord/guild.py", line 1213, in _create_channel
payload = {'allow': allow.value, 'deny': deny.value, 'id': target.id}
AttributeError: 'NoneType' object has no attribute 'id'```
in this for loop, can you add py print(role_id, guild.get_role(role_id))and try the button again
it's saying these @cyan quail
896145297128955974 Manager
896145295543533588 Senior Administrator
895995833382748241 Administrator
899385196313452575 Trial Administrator
896145522870603816 None
895995793339715614 Moderator
992961996687417394 Trial Moderator
but 896145522870603816 isn't defined in my config?
well it must be
it's not? 😂
are you 100% sure you edited RolesInChannel
"Guild_ID":870207685541363732,
"Operations_Role_ID":959002629533499402,
"Roles":[
870539877337399296,
896145297128955974,
896145295543533588,
895995833382748241,
899385196313452575,
895995793339715614,
992961996687417394
],
"RemoveOnClaimed":[
895995793339715614,
992961996687417394
]
},```
you might need to restart the bot then
wait
that's not even the right one though
the code is referring to a different config file
I've restarted it,
Roles = the ones who get added to the ticket
Removedonclaimed = id's who get removed?
"SMod_role_id": 896145522870603816,
that's in the config you sent
that's not a config file @limber urchin that's a print error that the loop is picking up
Is this not a config file?
no it's just a dict
but the ID is in that dict
yeah but it's irrelevant because the code's iterating through a list
so it's not that
yes
either there's another config file containing RolesInChannel or you straight up missed it in the same file
that is what you have to edit
Let me go on a search 😂
If only you could have varible values in the errors 
well that's why debuggers exist
I would use a debugger. Smth like vscode debugger
but eh we're too far gone
Yea lol I was saying the same 
or simply put RolesInChannel in the config file? 😒
Yeah haha not my code but yeah
if it was GMT timezone wouldn't be an issue
developer would be online
Hmm
#If the ticket type has questions then send a model with input boxes else make ticket
ticket_type_info = self.bot.questions_data["Categories"][ticket_type]
if ticket_type_info["Questions"]:
try:
return await interaction.response.send_modal(ModelWithQuestions(self.bot,ticket_type,ticket_type_info["Questions"],check_linked))
except discord.errors.NotFound:
return
else:
return await Creation.generate_make_ticket(self,interaction,guild,member,ticket_type,check_linked)
async def generate_make_ticket(
bot = None,
interaction: discord.Interaction = None,
guild: discord.Guild = None,
member: discord.Member = None,
ticket_type: str = "",
steam64: str = "0",
questions: dict = None,
autogenerated:bool = False,
autogenerated_info:dict = None,
server_name:str = "None",
autogenerated_reportID: str = None,
) -> None:
if not guild:
guild = bot.get_guild(bot.data["StaffListInfo"]["Guild_ID"])
#FindCategoryFromConfig
ticket_type_info = bot.questions_data["Categories"][ticket_type]
category = bot.get_channel(int(ticket_type_info["TicketCategory"]))
#TicketNumber
newticket_num = bot.ticketnum + 1
if newticket_num == 1488:
newticket_num = 1489
if this helps
FOUND IT!!!
nice
it works now
nice
thank you @cyan quail
here is an ice cream 🍨
if only...
add me back

I see you are trying regex. I recommend replacing things like * with \* So the user can still use the characters but it will escape the formatting. (Yeah I know this is old XD)
lol I will thx xD
wassup, How can i detect command usage other bots (like /bump) ?
what, I dont think other bots can execute slash commands :P
message.interaction
.rtfm message.interaction
I'm so confused rn
Why?
how can I remove @everyone role from guild's roles list?
ctx.guild.roles.pop(0) is just returning @everyone role
or am I doing something wrong?
The pop method returns the removed item
i always thought that pop is for remove, ty
yeah I get it
hello, is it possible to use a datetime argument for a slash command ?
for what?
in order to pass a date/time to the arg
but I found an issue on github https://github.com/discord/discord-api-docs/discussions/3303
thank you so much :)
How do I get server ID / where is it in the docs
guild.id where guild is a guild object
how do I get guild object?
im assuming its like ctx.guild or something
I saw somewhere that it's ctx.interaction.guild.id, is that different?
nope
i see
ctx.guild is just a reference to ctx.interaction.guild. so both are the same
because uh im trying to put the id into a sql db and its giving me errors
https://possiblepanda.hoponamong.us/🤨/747vxle8.png
hmm. full traceback?
yes
okay
File "C:\Users\possi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\bot.py", line 1114, in invoke_application_command
await ctx.command.invoke(ctx)
File "C:\Users\possi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\commands\core.py", line 375, in invoke
await injected(ctx)
File "C:\Users\possi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\commands\core.py", line 132, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: ProgrammingError: Could not process parameters: int(1030942556307062925), it must be of type list, tuple or dict```
ah
move that , between the two )
btw guild id is already an int
ah, let me try that
yeah but I was getting that error before so I was trying it
so you could do val = (ctx.guild.id ,)

i think you forgot the VALUES part of the query?
nope. same error
that is a issue, but not related to this
oh, what's that?
you would put a ? after VALUES
yea but you need to put that in the sql query too
wait wdym
so smth like INSERT INTO table_name (column) VALUES (?)
replace table_name and column
the ? is a specifier for the parameter
so yeah keep it like that
read this if you are interested https://docs.python.org/3/library/sqlite3.html#how-to-use-placeholders-to-bind-values-in-sql-queries
hmm

kinda sus
https://possiblepanda.hoponamong.us/🤨/nzwqtfw6.png do I gotta do this?
AHA
no errors anymore but it's saying no database selected
and I can fix that
ty @proud mason ❤️
ohh right mysql uses that 💀
im so sorry
all good! lol
i thought it was sqlite lel
lmaoo
https://possiblepanda.hoponamong.us/🤨/2pgg4grf.png
bro wtf you're joking
na mysql hates me rn lol
https://possiblepanda.hoponamong.us/🤨/b2dxv0dm.png
is something configured wrong??
wtf going on lol
brb
back
Say I have an interaction that my bot responds with an ephemeral message that is supposed to be added or changed later. If the user dismisses the message, does that count as the original being deleted for the context of a followup or edit? edit: typos
Should I just check for a not found exception and then just post the message with ctx.respond?
sql sucks, use mongodb
mongodb sucks. just put everything in memory and dump state to/from disk on shutdown/restart and give chrome a run for its money with memory usage. /s edit: typos
then maybe not self host your mongodb?
I was clearly making a joke. I have no opinion on mongo.
"clearly"? we using a text chat app where i can't see your emotions
no shit i cant tell
dude there is a /s. as in sarcasm. thats pretty clear and common.
ok?
Hello, I just want to add a link button to an embed. Can someone tell me how to do it? (I tried to search for help but the example in link.py requires a "query".)
how can I use discord.utils.format_dt() to display the current time? I noticed that datetime.utcnow() gives me a time 2 hours shifted from my actual time
use discord.utils.utcnow() instead of datetime.utcnow()
ok noice
It’s the same concept, just remove the variable
Thank you, I didn't understand much.
How can I add a view from the bot object in either the __init__ or the setup() of the cog?
bot.add_view works fine in init
no
it says there is not event loop running
Traceback (most recent call last):
File "/home/container/.local/lib/python3.9/site-packages/discord/cog.py", line 786, in _load_from_module_spec
setup(self)
File "/home/container/cogs/ticketsv2.py", line 67, in setup
bot.add_cog(TicketsV2(bot))
File "/home/container/cogs/ticketsv2.py", line 21, in __init__
bot.add_view(CreateTicketView(bot))
File "/home/container/cogs/ticketsv2.py", line 9, in __init__
super().__init__(timeout=None)
File "/home/container/.local/lib/python3.9/site-packages/discord/ui/view.py", line 183, in __init__
loop = asyncio.get_running_loop()
RuntimeError: no running event loop```
Then just do it in on ready with wait until ready
i cant
Why
Then make it an on ready listener in the cog
Im doing it every time like that x3
My bot is supposed to grab the message of users (on_message) and send them in a channel (without any editing).
If a user sends a message with e.g. a imgur link (image) it doesnt display the embedded image in the channel but only the hyperlink.
How its supposed to be:
https://i.imgur.com/aKrQpCs.png
How it is sent:
https://i.imgur.com/BUAvy74.png
Any ideas how I can fix it?
I think your embed is overriding the image embed.
What is the name of the function, with which the buttons will turn off at the right time for me.
what?
Hey guys,
How can i create a post in a forum channel?
on_timeout?
.rtfm create_post
Target not found, try again and make sure to check your spelling.
.rtfm ForumChannel.create
Hey, how would I handle the discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions error?
if isinstance(error, discord.Forbidden):
await ctx.author.message("Please add read channel permissions to the bot.")``` I have tried this
commands.ThePermission
Does @discord.ui.button have a url argument?
Something the python says is missing.
The decorator does not, because a url button can't have a callback
oh..((
how can i get the forumchannel?
The same way you get a normal channel.
like that?
channel = discord.utils.get(ctx.guild.ForumChannels, id=int(config_todo['channel']))```
.tias
I would rather use guild.get_channel
```Command raised an exception: TypeError: 'method' object is not iterable````
channel = discord.utils.get(ctx.guild.get_channel, id=int(config_todo['channel']))```
why get_channel?
#998272089343668364 message
that is not what @proud mason means
and what does he mean?
Im not really sure that a ForumChannel is
so you don't know what a forum channel is?
I mean this
channel = discord.utils.get(ctx.guild.ForumChannels, id=int(config_todo['channel'])) this should be fine for it?
guild.get_channel is a method
^
.rtfm get_channel
discord.ext.commands.Bot.get_channel
discord.ext.bridge.AutoShardedBot.get_channel
discord.ext.commands.AutoShardedBot.get_channel
discord.AutoShardedBot.get_channel
discord.AutoShardedClient.get_channel
discord.ext.bridge.Bot.get_channel
discord.Guild.get_channel
discord.Guild.get_channel_or_thread
discord.Client.get_channel
discord.Bot.get_channel
ok i think it should be something like that:
channel = ctx.guild.get_channel(id=int(config_todo['channel']))```
but theres still an error (unexpected arg)
You don't pass it as a kwarg
how does that work again?
Remove the id=
thx
Now i have an other problem:
code:
channel = ctx.guild.get_channel(int(config_todo['channel']))
thread = await channel.create_thread(name=f"{who.mention} - {strength}", reason="Todo", message="Hey")
await thread.send(f"{what}")```
Command raised an exception: TypeError: ForumChannel.create_thread() got an unexpected keyword argument 'message'
i would use on message and make a if request (if its in a forum channel). or go to the docs
https://docs.pycord.dev/en/stable/api/models.html#discord.ForumChannel.create_thread
It is content= not message=
Models are classes that are received from Discord and are not meant to be created by the user of the library. Attributes key, url. Methods def is_animated, async read, def replace, async save, def ...
How can I fix that?
.rtfm on_thread_c
You will need to check if it is in a forum Channel though.
You could add the image to the embed
.rtfm Embed.set_image
yeah but I'm unable to figure out which one. it's just a problem when someone uses a slash commands in a channel the bot doesn't have access to
What should I do to fix this?
discord.errors.InteractionResponded: This interaction has already been responded to before
A button that responds with something after clicking then disables it
I used await interaction.response.edit_message(view=self) to edit the view, but I think that's the cause. I am not sure what to do, can someone help?
.rtfm interaction.edit_original_message
I didn't understand, can you explain?
Hello, how to edit responded interaction through the paginator.edit()?
i've tried paginator.edit(ctx.message) and paginator.edit(ctx.interaction.message)
Hello all been doing some googles and not found anything. There anyway to return all users assigned to a tag such as @LoremIpsum (return all users)
What you don't get? It's a method, works the same as edit_messagr
You pass the interaction or context not the message
Users assigned to a tag? You mean role?
yeah, i know, but how to pass the responded message
.rtfm Paginator.edit
Role
ctx.message doesn't work?
.rtfm Role.members
So I would want to use Guild right to return all members with that role?
yeah
Traceback (most recent call last):
File "C:\Users\ilush\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 124, in wrapped
ret = await coro(arg)
File "C:\Users\ilush\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 978, in _invoke
await self.callback(self.cog, ctx, **kwargs)
File "d:\moneyrain\Harrison\leveling.py", line 130, in leaderboard
await paginator.edit(ctx.message)
File "C:\Users\ilush\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\pages\pagination.py", line 1058, in edit
raise TypeError(f"expected Message not {message.__class__!r}")
TypeError: expected Message not <class 'NoneType'>
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\ilush\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 1114, in invoke_application_command
await ctx.command.invoke(ctx)
File "C:\Users\ilush\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 375, in invoke
await injected(ctx)
File "C:\Users\ilush\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 132, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: expected Message not <class 'NoneType'>
Try passing await ctx.interaction.original_response()
I need to just replace it right?
What's followup and how do I use it?
Hello all, I am trying to return all users with a role. This is my code:
@bot.slash_command(name="createclass")
async def createclass(
ctx: discord.ApplicationContext,
role: discord.Role
):
role = discord.utils.get(ctx.message.server.roles, name="mod")
if role is None:
await bot.say('There is no "mod" role on this server!')
return
empty = True
for member in ctx.message.server.members:
if role in member.roles:
await bot.say("{0.name}: {0.id}".format(member))
empty = False
if empty:
await bot.say("Nobody has the role {}".format(role.mention))
Getting this error: discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'NoneType' object has no attribute 'server'
Yes
It's a followup webhook to send extra responses with interactions. It works the same way as.normal
It's guild, not server
And use ctx.guild
There's no need to use ctx.message.guild
Read the docs
so ctx.guild.roles for example?
Its only returning the first user
@bot.slash_command(name="createclass")
async def createclass(
ctx: discord.ApplicationContext,
role: discord.Role
):
role = discord.utils.get(ctx.guild.roles, name= str(role))
if role is None:
await ctx.respond(str(role) + ' is not a valid BUD/S Class on this server!')
return
empty = True
for member in ctx.guild.members:
if role in member.roles:
# Check if SA/SR only as INSTRUCTOR has tags also
print(member.nick)
# Create NAME TAG
# SEND INTO ZIP
#await ctx.respond("{0.name}: {0.id}".format(member))
empty = False
if empty:
await ctx.respond(str(role) + ' is Empty!')
else:
await ctx.respond(str(role) + ' is Not Empty!')
You're overcomplicating a simple code
members = role.members
if len(members) == 0:
return await ctx.respond("This role has no members")
parsed_members = [f"{member.name} {member.id}" for member in members]
await ctx.respond(content="\n".join(members))```
It's as simple as that
You definitely need to learn more python
Indeed, I am learning more everyday. But its throwing this error
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: sequence item 0: expected str instance, Member found
Full error
Code
And If you don't know python, you shouldn't be coding a Discord bot
I fixed it however it is only returning one user. My mate mentioned something about SERVER MEMBERS INTENT could be the reason why it is not returning more then one person
I've turned it on and it seems to have no change
You have to turn it on in your code too
Are you passing the intents to the bot instance?..
?tag intents
https://docs.pycord.dev/en/master/intents.html
https://discord.com/developers/docs/topics/gateway#gateway-intents
import discord
from discord.ext import commands
# Get specific intents for fine control
intents = discord.Intents()
intents.emojis = True
intents.guilds = True
intents.messages = True # Required for prefix commands!
...
# Get all non-priveliged intents; this excludes presences, members and message_content
intents = discord.Intents.default()
# Set priveliged intents: these must be enabled on dev portal
intents.members = True
intents.presences = True
intents.message_content = True # Required for prefix commands >= 2.0.0b5
# Get all intents; all intents must be enabled on dev portal.
intents = discord.Intents.all()
# Apply intents when creating your bot
bot = commands.bot(prefix="?", intents=intents)
In version 1.5 comes the introduction of Intents. This is a radical change in how bots are written. An intent basically allows a bot to subscribe to specific buckets of events. The events that corr...
sorted it, simply forgot to assign the intents. Thanks for the help!
Hello, how to override slash commands without turning off the bot?
You mean syncing?
.rtfm sync
discord.SyncWebhook.send
discord.SyncWebhook.session
discord.SyncWebhook.source_channel
discord.SyncWebhook.source_guild
discord.SyncWebhook.token
discord.SyncWebhook.type
discord.SyncWebhook.url
discord.SyncWebhook.user
discord.Bot.get_desynced_commands
discord.Bot.sync_commands
discord.SyncWebhookMessage
discord.SyncWebhookMessage.activity
discord.SyncWebhookMessage.add_reaction
discord.SyncWebhookMessage.application
discord.SyncWebhookMessage.attachments
discord.SyncWebhookMessage.author
discord.SyncWebhookMessage.channel
discord.SyncWebhookMessage.channel_mentions
discord.SyncWebhookMessage.clean_content
discord.SyncWebhookMessage.clear_reaction
Changing the code in command in cog
.rtfm sync_commands
Yeah that's syncing
You could also reload a cog but sadly thats a part of the Pycord library which is a bit broken.

.rtfm extension
discord.ExtensionError
discord.ExtensionError.args
discord.ExtensionError.with_traceback
discord.ExtensionFailed
discord.ExtensionFailed.args
discord.ExtensionFailed.with_traceback
discord.ExtensionNotFound
discord.ExtensionNotFound.args
discord.ExtensionNotFound.with_traceback
discord.ExtensionNotLoaded
discord.ExtensionNotLoaded.args
discord.ExtensionNotLoaded.with_traceback
discord.ExtensionAlreadyLoaded
discord.ExtensionAlreadyLoaded.args
discord.ExtensionAlreadyLoaded.with_traceback
discord.ext.commands.Bot.extensions
discord.ext.commands.Bot.load_extension
discord.ext.commands.Bot.load_extensions
discord.ext.commands.Bot.reload_extension
discord.ext.commands.Bot.unload_extension
the reload_extension, you could also make a load and unload command which should unload of load a cog but it doesn't because as I said. Pycord Library issue :/
How do I get the current username from the user id, if I can?
Hey guys!
Could anyone tell me how to change the tags of a forum thread?
Thanks for help. I tried reloading extension but it didn't work
you fetch it :P
.rtfm fetch_user
discord.ext.commands.Bot.fetch_user
discord.ext.commands.Bot.get_or_fetch_user
discord.ext.commands.AutoShardedBot.fetch_user
discord.ext.commands.AutoShardedBot.get_or_fetch_user
discord.ext.bridge.Bot.fetch_user
discord.ext.bridge.Bot.get_or_fetch_user
discord.ext.bridge.AutoShardedBot.fetch_user
discord.ext.bridge.AutoShardedBot.get_or_fetch_user
discord.Client.fetch_user
discord.Client.get_or_fetch_user
discord.AutoShardedBot.fetch_user
discord.AutoShardedBot.get_or_fetch_user
discord.AutoShardedClient.fetch_user
discord.AutoShardedClient.get_or_fetch_user
discord.Bot.fetch_user
discord.Bot.get_or_fetch_user
Yeah that's an issue I have now too... Still waiting for a fix .-. but I suppose there are bigger issues at the moment.
... good question I haven't thought about threads and bots so much myself.
i've found this, but how can i add the actual tag?
await interaction.channel.edit(applied_tags=[""])```
I'm looking through the docs myself rn lol hold on
Models are classes that are received from Discord and are not meant to be created by the user of the library. Attributes key, url. Methods def is_animated, async read, def replace, async save, def ...
Thanks
wait i found it, i just have to add the ids of the tags to the list
Yeah I was trying out an example at the moment xD good job I'm proud.
# Get the thread you want to edit
thread = client.get_channel(THREAD_ID)
# Define the new tags you want to apply
new_tags = [discord.ForumTag(name="new_tag_1"), discord.ForumTag(name="new_tag_2")]
# Edit the thread and apply the new tags
await thread.edit(applied_tags=new_tags)
but how can i get the tag 
ah with name
Here
smart
Yeah I am not sure if that works but I suppose it should work. 
Lemme know if it works.
Forgot to ping you ig.
np

it's very weird, i tried your code, but nothing hapens, no error and the code continues
well I suppose add some print statements to know what it does.
debugging at its best
for example after defining the thread you wish to edit you can try printing the Thread variable
also make sure the bot has permissions to edit threads :P
Manage Threads permission is required for that.
well it returns the name (the id is needed), but if i add an .id the response is 0
why not just use the ThreadId variable you defined before for the ID if you need that again?
?
THREAD_ID = 123456789
#Get the thread you want to edit
thread = client.get_channel(THREAD_ID)
print(f"The ID of {thread} is {THREAD_ID}")
@lost lodge
but i need the tag id?
oh right tag id, sorry understood you wanted to get the thread id again
I'm not entirely sure if tags have ID's...
i need the id of a forum tag, not necessary via pycord (via the discord app is also good)
they have
oh damn
hmmm
It seems that the ForumTag class does have an id attribute.
So I assume you can do this;
new_tag = discord.ForumTag(id=TAG_ID)
but how can i get the id
still looking at that rn
ok
guild.fetch_forum_tags() ?
that doesn't exist
me too
wait what about this;
https://docs.pycord.dev/en/stable/api/models.html#discord.ForumChannel.available_tags
Models are classes that are received from Discord and are not meant to be created by the user of the library. Attributes key, url. Methods def is_animated, async read, def replace, async save, def ...
WHat
i have it
this works
Guys who worked with the database, what is better to use for a massive database for collecting identifiers, and a message counter, and what is easier to apply in coding (who says json (pls run away in forest 😅)
?tag nojson
Why not to use json files for data storage
JSON files are commonly used to store data that is read by a program, however, they are unsuitable for storing dynamic data due to a number of reasons.
It is recommended to use a DBMS (Database Management System) as they come with optimized technologies for storing and retrieving information.
Advantages of using a database:
- Database tables can be related, making it easy to separate your information into multiple tables and only fetch what you need
- Databases allow you to use a query/data processing language to make complex data operations easier with less code
- One misplaced character will corrupt an entire file. A database very rarely experiences corruptions due to their automatic handling of data integrity
- Transactions in SQL databases allow you to revert unwanted changes and prevent data corruption in the case of an error
- Databases have support for indexes, allowing retrieval of some data to be extremely fast
- It is very easy to update existing data in a database, as opposed to re-writing a file
- Databases are reliable
Popular database management systems:
- SQLite3
- MongoDB
- PostgreSQL
- MySQL
- MariaDB
- Microsoft Access
there are some
for absolute massive amounts of data I suppose MongoDB can help you
does that help?
and he was never heard from again...
Thanks and seems i can use Postgre in replit but is there anything free 
I don't want to create json, I really don't like how it works and sometimes if it collects more than 50k user data, my host burning 
... sqlite3 for beginners... but I suppose at your seize MongoDB is good.
today its one ping and button press i had to run the code from my phone because it has two streams per output
❤️ i try it

You have to transfer json data to mongodb?
that's actually quite good for you, as they support that --> https://www.mongodb.com/compatibility/json-to-mongodb
Idea counts messages in history entry error 4xx

Next time i create and collect data in db
jesus christ, 50K userdata???
boi
you're in for a ride
We have 138k users on server 
just to hold events and create a barrier for tweak accounts, we decided to create a verification level, and since the idea with the history failed so that the discord restricted access to messages, it was decided create db and after couple months add in verify code limit for messages
No, now i looking for the best and best free option
I can create json but how long will hosting with 0.5 cpu
ok for hosting, really you gotta figure that out ig you can use an aws server, if you have amazon prime nonetheless but other than that figure it out ig. MongoDB is what you should use for databases.
for bigggg databases
otherwise I can recommend a lightweight database Sqlite3
TY u best❤️
Now i need open vpn and learn db❤️
Mongo is definitely not necessary in your case. Just use an SQL based database if you don't already know how to use Mongo
And for hosting, don't use AWS. It's relatively speaking overpriced and most of it's features are useless for a simple project like a Discord bot. Use something like DigitalOcean, GalaxyGate, Vultr etc.

The big hosting providers like Google Cloud, AWS, Microsoft Azure, Oracle Cloud etc. will typically make you pay more. Although being more reliable and robust, they're rarely worth it and you can find hosts for way cheaper.
And as for databases, NoSQL databases tend to create a lot of unnecessary complications with little payoff. 138k users is not even close to being considered a "big" database. When you start reaching hundreds of millions, or even billions of rows.. that's when NoSQL might come in handy. I highly recommend using a simple SQL based database instead, such as Postgres, SQLite or MariaDB.
Hm, yes.
But what if there are multiple files/images/gifs attached?
Or just don't send an embed at all
Is there a way to see if a message’s author is a webhook?
i have a discord.ui.View class with an on_timeout function that disables all buttons but when i go to apply these changes im getting AttributeError: 'NoneType' object has no attribute 'edit'
i have no idea what's happening, i've checked all intents on the developer page and in main
i am getting this error when i try to reload a cog containing a bridge command
:'BridgeCommand' object has no attribute 'name'
the code is:
@bot.bridge_command()
async def reload(ctx, cog: str):
try:
bot.reload_extension(f'cogs.{cog}')
await ctx.send(f"{cog} has been reloaded.")
except Exception as e:
await ctx.send(f"Error reloading {cog}: {str(e)}")```
.rtfm message.webhook
1st
How are you sending the view?
Yes that is a known issue
any fixes?
Not that I know of unfortunately
so i cannot unload bridge commands using cogs?
stop, I didn’t wake up, a person can be the initiator of creation, but not as a non-author, or I’m somewhat outdated, but only a bot or a web can send.
If you want to get user data to embed and send via webhook then the question is completely different
await ctx.respond(embed = images, view = ImageScroll(timeout = 60))
im almost certain it's worked before but i don't remember :/
I don't think so
Are you deferring ?
yes
maybe update to latest version?
Ah there is an open PR to fix that
ah so it's a known issue
But for the time being, you can do
view = View()
msg = await ctx.respond(...)
view.message = msg
This is only if you defer
Yes
oh I think if you defer, you do webhook.send, which we didn't assign the message object to the view, right?
alright thanks i guess ill just wait for it to get fixed then
has this been fixed?
I'm just needing to know if a deleted message was sent by a webhook. I'll check out that webhook_id bit that was linked to me, because it sounds like exactly what I need
@meager heron but u can use same msgs
This embed in commands/events
And send in any channel/guilds and dms
if u want send in dms
for a webhook, all you need to do is send the already prepared data and display it
I know how to create webhooks and send messages from them. This is specifically for reducing my database calls by only making them when a webhook message is deleted. It's very specific for my use case
how to make it so that Either role or channel argument (only one of them) can be passed
yes. ##1997 fixes it