#Basic Pycord Help (Quick Questions Only)
1 messages · Page 78 of 1
i could not find any async pillow packages, can i use threading module for pillow?
I would use asyncio.to_thread to call the blocking function
This puts it in a separate thread
So main thread which has the event loop is not blocked
does it return the value?
Got it. Thank you so much! I really appreciate it
You can even return values
Yes was just typing that 😂
thx
Np
just adding another option - you can use a thread/processpool executor and set up an asyncio queue to await on for results
asyncio.to_thread manages everything for you
The threadpool executor and returning of result
Even context vars
Yeah - but processpool specifically means you're not hogging your eventloop CPU if that's something you're worried about
Process pool is difficult to work with imo. Because io between processes is not easy
Objects need to be pickled and sent through a pipe
result = await loop.run_in_executor(my_process_pool_executor, my_pillow_task, timeout)
for trivial objects the pickling is rarely an issue
Hmm
yeah didn't mean to troll the help channel though, sorry!
So if i use asyncio.to_thread with this function it should work?
def join_images(urls, r_id):
images = []
for i in range(len(urls)):
bytes_ = httpx.get(urls[i]).content
image = Image.open(io.BytesIO(bytes_))
images.append(image)
canvas = Image.new("RGB", (512 * 3, 512))
for i in range(len(images)):
canvas.paste(images[i], (512 * i, 0))
canvas.save(f"/tmp/{r_id}.png")
return f"/tmp/{r_id}.png"
Is pillow written in C? 🤔
Because then a process pool could be the best, as GIL might be released
I would save to a BytesIO object and return that. But I'm not sure how this plays if you use a process pool
just meant that if your pillow task is CPU intensive then to_thread is probably not the best solution
True
https://docs.python.org/3/library/asyncio-task.html#running-in-threads
This coroutine function is primarily intended to be used for executing IO-bound functions/methods that would otherwise block the event loop if they were run in the main thread.
No issues lol. Informative and helpful messages are always welcome
Why not fetch the image contents using async in the main event loop, and just do the pillow stuff in this function
This will be faster

I need to store information about some settings that apply to the entire server. For example a specific channel for a specific command. A familiar advised me to use Json instead of Sqlite3. What is the best way for me to use?
sqlite is lite yet powerful enough for most discord bots
Json is not meant to be modified programmatically. It is ideal for network communication, but not as a database
Thank you
I have a small problem. I need to have only one row of data in the table, which is set when the bot is turned on. Is it possible to set variable values immediately when creating a table? It's Sqlite3
wouldn't you just do another instruction then commit last
I'm sorry, but what do you mean?
hm perhaps im misunderstanding
are you trying to create a table and insert a row into it at the same time?
theoretically you could use CREATE TABLE ... AS https://stackoverflow.com/questions/59560811
but i think you should just CREATE then INSERT after
Hey, quick question. How do i send dms using pycord?
.rtfm user.send
Alright, Thanks
hey guys how can I send a followup message like ctx.followup.send for like pagination?
I mean like
import discord
from discord.ext import commands, pages
bot = commands.Bot(...)
@bot.slash_command()
async def slash(ctx: discord.ApplicationContext) -> None:
await ctx.defer()
pagination = pages.Pagination(["one", "two"])
await pagination.send() # what must I pass as parameter?
await ctx.followup.send()
maybe you mean interaction.followup.send()?
even if you've defered, you still use paginator.respond https://docs.pycord.dev/en/master/ext/pages/index.html#discord.ext.pages.Paginator.respond
ctx.interaction
okay let me try
it works thanks
Hey uh. How do i get the name of the server where a command is sent?
.rtfm applicationcontext.guild
Ty
.rtfm guild.name
1 more question lol, whats the best way to store member data?
with a db?
I use MongoDB
Alright
Its not 100% great for this but ok for me
I need to store a string
How can I save time to Sqlite3 database?
store the timestamp?
Yes
I couldn't do it last time so I saved the month and day separately
pretty sure sqlite has BIGINT datatype
that happily accepts timestamps for me
even discord ids and stuff
sqlite also has a DATETIME column type, but i always found it weird to use
I couldn't work with Datetime
Are these big numbers?
yes
i think you have to pass an ISO datetime string to it. i recommend searching on google about this
Thank you
How can I refer to a category by its ID? Method get_category(id) doesn't exist
you just use get_channel because categories are a type of channel
But I need this to create a channel in an empty category
that doesn't change anything...
Do categories count as channels?
yes
Oh, I'm sorry. Thank you for the help
Is there any way to acknowledge a button push, but not send a text reply?
I'm looking to have a button that may be pushed multiple times in a short period of time and don't want to have to always be sending a message in response as that gets spammy and annoying.
It edits its own message to reflect the change anyway.
you have to send a response
Changing the message is enough. You can change the message without changing anything in it
So if I want to have a button that someone might click multiple times (lets be absurd and say 20), I have to send 20 messages in reply?
yes
but you could auto delete the messages
Well that is less than ideal.
Would this result in an "Application failed to respond" error though?
Its discord and py-cord cannot really do anything about that
mhm. Just wish Discord would have had the foresight to not make it that way.
Try it. I think not
With the editing you can get really fast a ratelimit but Im not 100% sure
You won't be able to quickly press the buttons
^
The error may appear due to the fault of Discord, not bot
And double-clicking can also happen which is quite unpleasant
I could be wrong
Yeah... Editing the original message it seems to result in a "Interaction failed". I get a 404 Not Found.
yes. defer and ignore is actually the best and ideal way
but like others said, you can try and pass no actual change to the edit
try deferring
btw you need to use interaction.response.edit_message to edit it
smth as simple as await interaction.response.edit_message(content=interaction.message.content) might work
but i really recommend defer and ignore
I was wrong again, sadly
How can i get an user by the id with discord.utils?
id=123
ty
discord webhooks can used for interacting with users only if the bot is the hook creator
HOW TO MAKE THEM WITH APP COMMANDS! 💀
the docs have nothing about the webhooks and app commands but if they can interacting so they can make app commands, the idea that i tried to make an request to register a app command with the hook token and the hook id which is made with a normal bot but it fails with 401 :|
although even if its possible how the hook will respond in a channel if it wasn't assigned to..
hmm... this think tbh is the only thing i got can lead for like that
the idea is HOW to get hands on them 🗿
i mean this is the question trigger:|
http bots have a profile stuff :|
ik and this wasn't the issue
i mean how from the api side
Idk never worked with them
1+ 😭
You'd be better off looking for a lib that supports them
just looking to the discoordo api support for that thing~
@cyan quail it was a discord http/interactions application.command scope app with no bot profile (which is discord doesn't like idk why) and it looks like a webhook 🗿
Yes, that's a http bot
btw it would be cool if the hook have a something like that!
It might be supported in v3 but not in v2
you mean the http stuff
Yeah
Specifically you can try to do it in pycord just by inviting the bot without the bot scope
And it might work to some extent, but there's a high chance of running into unusual errors because the library was designed around having an actual bot user
hey we literally had a vulnerability from that.
and hopefully our last
I keep getting an error stating "NoneType has no attribute edit". How can I update the view with the disabled button?
class mobileButton(discord.ui.View):
def __init__(self, address: str):
super().__init__(timeout=2)
self.address = address
async def on_timeout(self):
for child in self.children:
child.disabled = True
await self.message.edit(view=self)
@discord.ui.button(emoji="📱", label="Mobile", style=discord.ButtonStyle.grey)
async def first_button_callback(self, button, interaction):
await interaction.response.send_message(self.address, ephemeral=True)
Is the message ephemeral?
how do you send the view?
await ctx.respond(embed=embed, view=mobileButton(address=address))
is it deferred?
Yes
There is a known bug where the view's message isn't sent if the message was sent by a webhook.
As a workaround, you can set the view's message like so:
view = mobileButton(address=address)
interaction = await ctx.respond(embed=embed, view=view)
view.message = await interaction.original_response()
https://docs.pycord.dev/en/stable/api/models.html#discord.Interaction.original_response
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 ...
Okay, thank you!
I fixed that weee 
You can strap it onto a bot subclass by adding 2-3 extra methods
Eh
Seeing how fundamentally different http bots are, they should be their own class that's even lighter than client or bot
I've done it 
True
Http bots shouldnt use the gateway
That was the original thought behind it iirc
*shouldn't 💀
How do i always forget the "nt" when typing in mobile 😂
Couldn't find anything that worked for me
How can I check if a member has access to a particular permission? Use guild_permissions gives me permissions code but I can't check particular
guild_permissions has an attribute for each permission which returns a boolean
.rtfm guild_permissions
.rtfm discord.Permissions
discord.Permissions
discord.Permissions.DEFAULT_VALUE
discord.Permissions.VALID_FLAGS
discord.Permissions.add_reactions
discord.Permissions.administrator
discord.Permissions.advanced
discord.Permissions.all
discord.Permissions.all_channel
discord.Permissions.attach_files
discord.Permissions.ban_members
discord.Permissions.change_nickname
discord.Permissions.connect
discord.Permissions.create_instant_invite
discord.Permissions.create_private_threads
discord.Permissions.create_public_threads
discord.Permissions.deafen_members
discord.Permissions.embed_links
discord.Permissions.external_emojis
discord.Permissions.external_stickers
discord.Permissions.general
I am trying to get bridge to show descriptions when you use slashcommands
However, when I do this,
and run it as a regular command
I get the following error
discord.ext.commands.errors.BadArgument: Converting to "Option" failed for parameter "command".
Try using the Option Decorators :P
I'm working with bridge
No idea how they work, where can I find the docs?
Gonna need to do a bit of searching there myself :v
nevermind, I think I found it
O alright then :)
nope i lied
Command Permission Decorators: Commands: Shortcut Decorators: Objects: Attributes full_parent_name, qualified_id, qualified_name. Methods@ after_invoke,@ before_invoke,@ error, def get_cooldown_ret...
Got it, thank you
Those should just work with bridge too
I could only
if ('administrator', True) in ctx.author.guild_permissions:
...```
Is this fine?
The hell is that
It's just .ctx.author.guild_permissions.administrator
And that returns a boolean
Thank you
class Question(discord.ui.Modal):
def __init__(self, ...):
super().__init__(???)
self.add_item(discord.ui.InputText(label="String name"))
self.add_item(discord.ui.InputText(label="String name", style=discord.InputTextStyle.long))
async def callback(self, interaction: discord.Interaction):
embed = discord.Embed(title="Title name")
embed.add_field(name="String name", value=self.children[0].value)
embed.add_field(name="String name", value=self.children[1].value)
await interaction.response.send_message(embed=embed)```
I decided to learn modal to be able to work with forms. I want to ask a few questions to make to understand how it works.
1) What does `discord.ui.Modal` pass to the class via super()?
2) Does the function inside a class should be called "callback"?
3) How does "children" work?
- mainly the title. Timeout is optional
- yes the function should exactly be
callback, and should only accept 1 parameter apart fromself childrenis a list of InputTexts you added to the modal usingadd_item. they retain the order they were added in
Is there a maximal time await view.wait() is working?
I have the problem, that the buttons of my view, stopped working after some time (several hours) without that the timeout event triggered. So somehow the thread waiting on that point is just killed after some (longer) time without processing the rest of the code after await view.wait(). I currently have no idea why
that's not really how you're meant to use wait
wait is useful for pausing the current code to wait for the view to end
meaning, if wait is triggered then the view is already stopped.
Yeah thats how I use it, I stop the view if someone presses a button for it, or if a timeout (of several days) is reached. Then some code after it is processed.
My problem is that no event triggerd view.stop() at all, but the buttons stopped working anyway after several hours
because you should be using the callback to process the rest of your code
The modals returns the value of strings in str, but I need to separate str from int. Should I use try-expect-finally?
if you just wait in a random command or other function and try to wait for several days, if something manages to kill that process you'd never know
just convert to int...?
oh i see
either try except, or use isdigit to validate it's an int
Thank you
Yes thats what probably happened.. Something kills that process. But yeah your right, maybe not a good idea to wait that long inside a process. Will shift the code to the timeout section, Thanks
Hi guys, I was toying around a bit with slash_command options and i came to the problem of updating the choices of one input on runtime.
I built a classic slash_command in a cog, following the github examples and it worked flawless with the @option(), constructor and the autocomplete parameter. I implemented it so that the autocomplete is passed a list and whenever i update the value of the options I run the bot.reload_extensions(<the Cog>) and it actually updates in discord. However when I try the same thing with using choices in the functions constructor, it stops updating the data. Is there a significant difference between them updating or am I messing something up?
How many items does the list have and you have to sync the command for choices
the list starts with 0 items and i try adding one or two at max
I will try syncing the command
I tried bot.sync_commands( force = True), however it doesnt seem to update it. From the docs I learned that they have the sync_commands() built in the @on_connect function and with that it surely works. Do you know where I can find the sourcecode for that specific bit so I can check if it looks the same and maybe fix my error?
you can't update choices live
that's why autocomplete exists
ah i see
well i just like the aspect that you cant enter a wrong entry and get stopped right there by discord, while in autocomplete it just gives you hints of what you could enter but doesnt check it live. However its not really that big of a deal, thank you :)
help? I'm creating an afk command but this on_message event don't triggered, the user.id is already in the file but it's only printing until 3, idk why the if condition not triggered.
the data is a json from other files and don't have any problem when i print it
class Utils(commands.Cog):
@staticmethod
async def json():
with open("f.json", "r") as f:
return json.load(f)
def __init__(self, bot):
self.bot = bot
self.load_afk = Utils.json()
@commands.Cog.listener()
async def on_message(self, msg):
if msg.mentions:
print("0")
mentioned = [user for user in msg.mentions if user != self.bot.user]
print("1")
for user in mentioned:
print("2")
data = self.load_afk
print("3")
if user.id in data:
print("4")
await msg.channel.send(f"{user.display_name} is currently in AFK.\nReason: {data[user.id]}")
json keys are strings, but user.id is an int
mhm
ill try
or even better, data.get(str(user.id))
Hi, is there a way to add a custom check inside a cog so i can use it as an instance method ?
I need to get access to the bot variable which is an instance variable, currently i put the check in my main file that instance the bot and load all the extensions so i can access it and then i import the method but it doesn't feel like it's a good move :/
Maybe it's good but if there's a better way i take it
# main file :
if __name__ == "__main__":
# The informations available for the bot
intents = discord.Intents.none()
intents.members = True
intents.guilds = True
intents.messages = True
intents.message_content = True
intents.reactions = True
josix = Josix(intents)
josix.run()
def check_owner(ctx: discord.ApplicationContext):
return ctx.author.guild_permissions.administrator or josix.is_owner(ctx.author)
# extension file
@commands.slash_command(description="test owner")
@commands.check(check_owner)
async def test_own(self, ctx: ApplicationContext):
await ctx.respond("All good")```
cogs can have a cog_check function to run on all commands in the cog
hooo
What do annotations do?
just defines a type for your type checker to verify
in the actual program they don't have a real function because python isn't a typed language
(though there are exceptions when you've explicitly made it functional, e.g. we can annotate with discord.Option)
Thank you
does anyone know how to setup and use ffmpeg on replit?
Can someone help me with this code snippet? It is checking if the token is valid or not. To do so, it connects to the discord api and if it's successfully connected, it disconnects. And that's where I get a problem
def check_token_validity(token):
try:
@client.event
async def on_ready():
print("Valid token. Continuing...")
#add_account_token(token)
await client.close()
return True
client.run(token)
except :
print("Sorry, it seems like this token is not valid.")
return False```
I'm a piece of sht at coding so, if this makes you cringe, excuse me lol
This is the error I get, i forgor to post it Valid token. Continuing... Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x00000248FC3870A0> Traceback (most recent call last): File "C:\Users\sofia\AppData\Local\Programs\Python\Python310\lib\asyncio\proactor_events.py", line 116, in __del__ self.close() File "C:\Users\sofia\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\sofia\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 750, in call_soon self._check_closed() File "C:\Users\sofia\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 0x00000248FC3870A0> Traceback (most recent call last): File "C:\Users\sofia\AppData\Local\Programs\Python\Python310\lib\asyncio\proactor_events.py", line 116, in __del__ self.close() File "C:\Users\sofia\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\sofia\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 750, in call_soon self._check_closed() File "C:\Users\sofia\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 0x00000248FC3870A0> Traceback (most recent call last): File "C:\Users\sofia\AppData\Local\Programs\Python\Python310\lib\asyncio\proactor_events.py", line 116, in __del__ File "C:\Users\sofia\AppData\Local\Programs\Python\Python310\lib\asyncio\proactor_events.py", line 108, in close File "C:\Users\sofia\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 750, in call_soon File "C:\Users\sofia\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 515, in _check_closed RuntimeError: Event loop is closed
Do you know basic python?
why would you validate the token by running the bot, then closing the connection and then starting it again?
if the token is invalid the bot just wont run and pycord will raise an improper token passed error
Checking an event before running the code to even be able to check an event 
Because I need to check if it’s valid, literally
And if it’s not, ask for another one. Because that’d be shit to put an invalid token on the database and just having to go on the json and delete it if it’s not valid
It’s supposed to be a public project, not for me
Else i’d have done simpler
Yeah that’s the point. When it’s raising this error, I catch it and ask for another token
But when it’s valid, I close the connection, put the token in the json and do the rest of the code. So next time, when they’ll run the code, they won’t have to do it all again
Mindfucking isn’t it
You didn’t even try to understand it before saying your nonsense shit
i have never seen this error, what's the potential cause?
using blocking libraries like requests etc will block the bot
?tag blocking
No tag blocking found.
oof
not using blocking, im using aiohttp
any other libraries
hmm
oh and websockets too
it might be due unstable internet too
but that's also async
ah, that must be it
this is completely fine right?
okay great thank you!
Hey there, I have a problem, can I get some help please
so I have a cog
Let me show the code in the cog
import discord
from discord.ext import commands
import asyncio
class Embeds(commands.Cog):
def __init__(self, bot):
self.bot = bot
@discord.slash_command(name="create_embed", description="Send an embed.")
async def send_embed(self, ctx: discord.Interaction):
await asyncio.sleep(1)
await ctx.channel.send("Embed sent!")
def setup(bot):
bot.add_cog(Embeds(bot))
this is the code in the cog
but every time I run the bot and attempt to run th create _embed slash command
it sends the message "Embed Sent", but says "the application did not respond"
any ideas why and how I can fix this?
@strange beacon @grizzled sentinel plz help, helpers
this should be a simple issue, but I can't seem to solve it
😭
I hate being a beginner
I look so dumb
It is a simple issue.
It is ctx.respond not send, you are getting a the application did not respond because you didn't.
wait so, what about an embed though?
it is channel.send(embed=embed) right?
lemme try this fix real quick
and thanks a lot
yes
well I am trying to make an embed builder command where the user sets the title and description and so on
Great, there is nothing in the code you have posted that has any embed code. So I helped with the issue at hand.
When responding to a / command you need to either respond or defer or you are going to get the application did not respond error.
but
I still get the error
oh god, this is tricky
ok, this didn't seem to work, it still says the applicattion did not respond with this code:
I am doing something wrong fr
why is this:
guild = await bot.fetch_guild(guild_id)
print(len(guild.members))```
returning 0, even though i have done
```python
intents = discord.Intents.all()
bot = commands.Bot(intents=intents)```
?
Why are you sleeping?
idk, chatgpt told me that might fix the issue
I'll try removing that
nah still got the error, damn
idk what I am doing wrong
answered in your thread
Can anyone help me in my forum
seems to be quiet around here for the moment, ima try nextcord and dpy servers to see if they know what's wrong with my code
ctx: discord.ApplicationContext
Send me link to there please
Please send me link
still has the error, damn, I am doing something real wrong
aight
Can you show the code again?
You can check mine out
Its in the forum
alright
import discord
from discord.ext import commands
import asyncio
class Embeds(commands.Cog):
def __init__(self, bot):
self.bot = bot
@discord.slash_command(name="create_embed", description="Send an embed.")
async def send_embed(self, ctx: discord.ApplicationContext):
await ctx.respond("Embed sent!")
def setup(bot):
bot.add_cog(Embeds(bot))
how can I do that?
yeah I always restart the bot when I change the code
I'm not that dumb lol
i need help making this code into a button
if the button is clicked it opens a new channelin that channel the /Apply'command would be use to get the embed with the questions
or maybe I am, idk, can't wwork this bug out
any ideas?
did you also save the files?
yes of course
maybe try replicating it
I can send my code if you want
like all of it
I am very frustrated
been trying to solve it so long
and such a seemingly simple issue
what is the py-cord version?
how to add cooldown to sub event? i want to add cooldown for the sub event 1
@commands.Cog.listener()
async def on_message(self, msg):
if msg.channel_id == 123:
if "hi" in msg.content:
await msg.channel.send("hello")
if msg.channel_id == 321:
#sub event 2
so the bot not sending again the hello msg for a specific time
for only one user?
you could save something like a number and use task.loop to change it after some time again
pls dont crosspost
Oky but i am waiting a long time
You waited 2 hours.
Yes
Is there a way to get \n character in slash command option ?
If i put one it's just ignored and print it, it does not add a newline :/
How can I check if an invite is a server vanity url? https://docs.pycord.dev/en/stable/api/models.html#discord.Invite
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 ...
I guess I can compare it to the vanity invite of the guild
How can I make sure that the “this interaction failed” error doesn’t pop up?
This one
My code works normally and it still pops up, I just want to disable it
you cant
Its from discord and not from py-cord
are you not sending a response??
(Or editing the original response)
I’m using some scuffed code that does the job but doesn’t send a response back to discord
scuffed code is never a good idea 

but you do have a solution
just defer the response. message components are not required to send a followup
Wdym
ctx.defer()
uh
buttons dont have ctx...
await interaction.response.defer() that
@violet heron ^
oh
Yeah that the problem
Every time I call that I get button object has no attribute response
subclassing view?
Yeah
the parameter order is self, button, interaction
Yeah
then you might have dpy installed
I don’t
show pip list
aiohttp 3.8.3
aiosignal 1.3.1
argon2-cffi 21.3.0
argon2-cffi-bindings 21.2.0
async-timeout 4.0.2
attrs 22.2.0
cachecontrol 0.12.11
cachy 0.3.0
certifi 2022.12.7
cffi 1.15.1
charset-normalizer 2.1.1
cleo 0.8.1
click 8.1.3
clikit 0.6.2
crashtest 0.3.1
cryptography 38.0.4
debugpy 1.6.5
discord 2.2.3
discord-py 2.2.3
distlib 0.3.6
filelock 3.9.0
flask 2.2.2
frozenlist 1.3.3
fuzzywuzzy 0.18.0
html5lib 1.1
idna 3.4
iso8601 1.1.0
itsdangerous 2.1.2
jedi 0.18.2
jeepney 0.8.0
jinja2 3.1.2
keyring 21.8.0
levenshtein 0.21.0
lockfile 0.12.2
markupsafe 2.1.2
msgpack 1.0.4
multidict 6.0.4
numpy 1.24.1
openai 0.27.6
packaging 23.0
parso 0.8.3
passlib 1.7.4
pastel 0.2.1
pexpect 4.8.0
pip 22.2.2
pkginfo 1.9.6
platformdirs 2.6.2
pluggy 1.0.0
poetry 1.1.11
poetry-core 1.0.8
protobuf 4.21.12
ptyprocess 0.7.0
pycparser 2.21
pycryptodomex 3.16.0
pyflakes 2.5.0
pylev 1.4.0
pyparsing 3.0.9
pyseto 1.7.0
python-levenshtein 0.21.0
python-lsp-jsonrpc 1.0.0
pytoolconfig 1.2.5
rapidfuzz 2.13.7
replit 3.2.5
replit-python-lsp-server 1.15.9
requests 2.28.2
requests-toolbelt 0.9.1
rope 1.7.0
secretstorage 3.3.3
setuptools 63.2.0
shellingham 1.5.0.post1
six 1.16.0
toml 0.10.2
tomli 2.0.1
tomlkit 0.11.6
tqdm 4.65.0
typing-extensions 3.10.0.2
ujson 5.7.0
urllib3 1.26.14
virtualenv 20.17.1
webencodings 0.5.1
werkzeug 2.2.2
whatthepatch 1.0.3
yapf 0.32.0
yarl 1.8.2
turns out it was, idek how
Installing Pycord with Replit (only use replit as a last resort) - pycord-replit-install.md
ive looked throught this
Am I the only one, who has issues with discord.Member at that moment?
The context: I made a slash command, which can add people to voice channels (connect permission), but type=discord.Member stopped working, when I start to type someone, it doesn't show anyone, also, when I try to tag someone, it gives this error back:
'str' object has no attribute 'id'
This issue is related to discord's new name system?
How would I auto start a scheduled event at the event's start time? i.e. Event is created to start in 72 hours and the bot makes the event go live on time.
discord.SlashCommandOptionType.mentionable do nothing either
Code
async def szoba_hozzaadas(self, interaction: discord.Interaction,
first: discord.Option(name='felhasznalo', type=discord.SlashCommandOptionType.mentionable)):
Why you have interaction?
And the option should be first: discord.Option(discord.Member, name="...")
Is message.reactions.me referring to the discord bot itself?
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 ...
it returns True if the bot used this reaction
Thanks!
res = await ctx.reply("Connecting to Database")
Is mentioning/pinging the author off in reply/respond?
How do i mention the author the context of ctx is BridgeContext
slash variant won't mention
unless you physically add a mention but eh
tbh i have no idea how to edit a component response message after sending
because the interaction.response.send_message() returns a interaction object
and i have no idea to edit that boui... :)
however msg.edit()
edits the og cached message that interaction belongs to :|
interaction.edit_original_response
i think also will edit the interaction message
in 2.5(?), we've introduced interaction.respond and interaction.edit to make this more straightforward
no, if you've used response.send_message then edit_original_message will edit that response.
where is 2.5 🤡
not released yet
:)
is there any way for a bot to have this thing or can they only have the title like "playing..."
bots cannot have rich presences. only simple statuses
F 😔
alright ty
Does someone know why this error is occuring ? I check and they inherit from the base Exception
class except Forbidden | NotFound:
TypeError: catching classes that do not inherit from BaseException is not allowed
nvm I just use the wrong syntax for the except
Persistent views are made the same way regardless of cogs or not
and where are the view classes defined?
if you have your views in the same files as cogs, then just add them in an on_ready listener in the cog. like this-
import discord
from discord.ext import commands
class MyView(discord.ui.View):
...
class MyCog(commands.Cog):
...
@commands.Cog.listener()
async def on_ready(self):
self.bot.add_view(MyView())
DO NOT define your views like this
import discord
from discord.ext import commands
class MyCog(commands.Cog):
...
class MyView(discord.ui.View):
...
how should I add the view if the view self takes arguments?
for example if the view is
class testView(discord.ui.View):
def __init__(self, a: int, b: int) -> None:
self.result = a + b
is there more code coming to that or just those lines
There’s more code then, but the problem was in this part
But it’s alright, I found a solution on my own
nice
Hi I have problem with guild.members in main bot file it returns empty list. But when i do same thing in cog it works fine.
target_channel = await client.fetch_channel(values[1])
print(target_channel)
target_guild = await client.fetch_guild(guild_id)
print(target_guild.members)
online_members = 0
for member in target_guild.members:
if member.status == discord.Status.online:
online_members += 1
Fetch guild doesn't return members data
Use get_guild
ok thanks it works
hey!
i have a random bug that i dont know how to fix
im running this code on replit
@bot.event
async def on_voice_state_update(member, before, after):
target_channel_id = 989472704249884672
if after.channel and after.channel.id == target_channel_id:
if not bot.voice_clients:
voice_channel = await after.channel.connect()
print("Voice activated")
voice_channel.play(discord.FFmpegPCMAudio(source='test.mp3'))```
it doesnt print anything and doesnt play the sound
it seems like nothing after ```voice_channel = await after.channel.connect()``` gets activated
Can you show the py-cord Version?
2.1.3
Update to 2.4.1
it didnt do anything...
it works perfectly when i run it on visual studio code
but on replit it goes like this
Replit is really bad
ik but i dont have any other options...
how can i get the id / name of a command thats in a slash group?
the same like a normal slash command I would say
okay thanks
can someone point me towards a place for good embed styling
What do you mean? There are a few websites that allow you to design an embed than you can use that design in your code. Or do you mean the docs?
I dont think there is really a official guide. But my suggestion is you use fields to split up everything that could be split up. Don't mash everything into a description or 1 field.
async def createVerificationEmbed(self, ctx, gameName, currentCountryIcon, targetCountryIcon, currentcountryName, targetName):
res = discord.Embed(
title="Username Verification",
description=f"{ctx.author.mention} change the country flag of {gameName}",
color=discord.Color.dark_gold(),
timestamp=discord.utils.utcnow()
)
res.add_field(
name="From",
value=f":{currentCountryIcon}:: {currentcountryName}",
inline=True
)
res.add_field(
name="To",
value=f":{targetCountryIcon}:: {targetName}",
inline=True
)
return res
thats what m doing rn
I think that looks good. You could add the image of there profile picture
Either hardcode them. Or store the arguments in a db
The only thing that looks a bit weird is the description is so short it looks a bit squished. The image might fix that
That sound great ill put it in
also can i edit the orignal response which did not have any embeds to have an embed?
res = ctx.respond(content="Some text")
res.edit(embed = someEmbed)
can this be done or should the edit only contain the parameters present in the orignal response
i tried using res.edit() and res.edit_original_response() but none worked
they had different parementers than the orignal responses
Yes that's possible
You awaited them right
you can use websites like https://discohook.org to manually build an embed to see how it might look like :P
Hi,
In a multiple selction (discord.ui.select() etc...) there's no way to have values as int for each selection ?
I only see strign or custom ones like role, channel or mentions :/
they have to be string yes
🥲
though nothing stopping you from converting it after
If you use select options you can set a differnt value for display and actual value
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...
yeah but value still has to be a string
yeah i know, but i wanted to have the value parameter as int but it's locked to str
Oh, sorry
Why is this a limitation? As I understand it value is internal
Np ^^
no, value is still passed to discord
Ah ok. Do they do something with it?
well it has to be stored there
same with custom_id
let's say you work with the raw api without any lib features, if you just recieve raw interaction data then you'd need that value from them
I thought it would be something that would only worked when the view was in cache
not necessarily, it's more or less all on custom_id
👍
whenever you add_view you're adding to a dict which uses custom_id (among some other stuff) as the key
so then on_interaction pulls from there
yep awaited them
if you wanted, you could completely ignore pycord's callback system and just use on_interaction listeners
can anyone tell me why my intents arent working?
i load them up like this
# Configure the intents
intents = Intents.all()
# Create the bot
bot = MatrixBot(command_prefix="/", intents=intents, case_insensitive=True)``` yet they still dont work
try discord.Intents.all()
Also it’s recommended to only enable intents your bot needs to function instead of all of them
General Python question. So.. say I'm using a method in a Cog as a callback to another part of the application. It seems the callback is mapped by memory address? ("bound method mycallback of object at 0x12345" etc). So does that mean if I were to reload the Cog, those callbacks are now invalid?
If so, is there any way to assign a callback so that it survives a Cog reload?
Although the old Cog reference does still seem to be 'active', so I guess that's not the problem.
What I'm trying to do is determine if a callback has already been registered. But when I reload a Cog, the existing callback does not == the new callback, and I'm having trouble figuring out the best way of doing so
Hm. callback.__func__.__code__ is equal. But I still have questions on whether the "existing" callback will even fire. It didn't seem to in my testing but I could have been doing something wrong.
I wonder if theres a way to check what functions your bot has so it can determine the least amount of intents it needs... (cuz I am too lazy to scroll trough all of my code to check and see what it does)
nm, I think my whole premise was wrong and there was simply an issue in my callback 😅
But I did learn that I cannot blindly compare the callbacks to determine if it's registered; .__func__.__code__ does allow me to make that determination. Unsure if there's a less convoluted way
How can I find out the ID of a channel just created by the bot? In addition to searching for its ID by name
like via create_text_channel?
Yes
just assign it to a variable ```py
channel = await guild.create_text_channel(...)
now access channel.id```
Thank you
but.. I can't find a channel permissions change where one can specify a channel rather than use the selected one
.set_permissions(target, overwrite, permissions, reason) — there is no parameter for a channel. Then what should I use?
you should get the channel object to use set_permissions on
e.g. use guild.get_channel(id) or discord.utils.get(guild.channels, name="...")
I mean I need to change permissions in a certain channel of a certain role, but I can't find a function that takes both parameters
set_permissions is a channel function already, you don't use channel as a parameter
How could I change permissions in another channel?
https://docs.pycord.dev/en/master/api/models.html#discord.TextChannel.set_permissions
some of the provided examples ```py
await message.channel.set_permissions(message.author, read_messages=True,
send_messages=False)
Deleting overwrites
await channel.set_permissions(member, overwrite=None)
Using PermissionOverwrite
overwrite = discord.PermissionOverwrite()
overwrite.send_messages = False
overwrite.read_messages = True
await channel.set_permissions(member, overwrite=overwrite)```
you need to get the channel; do you have its ID?
Yes
then use channel = guild.get_channel(id)
and then you can do channel.set_permissions(...)
oh, I'm stupid, I'm sorry. Thank you again
How does overwrite work?
see the example i posted above
Overwrite is also useful for modifying specific perms without damaging the whole system
Where does information come from? From category or role settings?
e.g. if you just wanted to edit someone's send_messages perm you want to use overwrites_for: py o = channel.overwrites_for(member) o.send_messages = False await channel.set_permissions(member, overwrite=o)
I get it
this would effectively mute a specific member
Thank you
How to retrieve a webhook URL? I understand retrieving a list of webhook objects from a channel, an ID from a Webhook.Message, but I can't figure out how to get the URL
webhook.url
I'm struggling to target the webhook though. How do I get the webhook object in the first place?
So I just have to select the right one from the list then, eh? I was trying to retrieve the webhook object from a message so that I could edit the message without any extra steps, but that requires getting the webhook object. :/
uhh if it's from a message, let's see...
I thought there would be some way to use the ID to fetch since you can't get URL from WebhookMessage
But it seems you always must use the URL
I tried to use a for loop to checkIDs, but Webhooks aren't iterable
I feel like I'm missing something though because I'm pretty sure discoHook utils does this from just a message object
mmm that's logical
Okay, I'll figure out something! Thanks <3
@cyan quail Found the solution around here! ^-^
#1057705183905329182 message
Can't get the webhook, but can get the WebhookMessage object which is what I need here
ah nice
there is a way to remove the bot profile from the new applications 
are you asking if there's a way or just saying it
asking :\
you can't
never been able to delete a bot user
unless, of course, you delete the whole app
I FOUND ONE !!!
All of the bots I have running just went down at the same time; does this traceback indicate a connection loss or something else?
you
How many bots are they and are you already at the 1000 times starting the bots?
wdym the 1000 times
You have a limit of 1000 times that you can start a bot
im not aware that im up to that
If you have like 100 bots and do that 10 times you are at the 1000 and all your bots shutdown
i dont see why theyd all run fine for a week with no restarts then randomly shut down
can i check what number im on
Idk how
oh and all the bots restarted and now work fine
weird
are you on master branch?
git+pycorddevelipment one
i'll push a fix, but i recommend downgrading to 2.4.1 instead
also, at that time you should have recieved an audit log event; can you check your guild's audit logs and screenshot the event that happened at that time?
sorry I'm not sure what you mean
Ah like discord audit logs
so when the error happened, some event should have occured in the server that all your bots share
yes
the reason this happened is because the audit log entry had a user_id of None, which we thought shouldn't be possible
I'll ask, we were setting up some forms with Dyno earlier so I'd guess it's something to do with rhat
Don't know how it would've went to unknown user, I've never seen anything like that before
interactions messages have an issue with the animated emojis ?
i mean two of the functions are the same, just one of them are configured to work with the interactions and the other one works with the App context
yes they should have the "use external emojis" permission
so why that work's on the first place
the bot has admin tho
webhooks use the @everyone role
wut webhooks
its a normal bot user
let my small brain load that
the message that belongs to a bot comes from a webhook if its followup 🤨
yes
💀
already done
and also probably explicitly enable use external emojis on the bot role
could you just try
oof

can you show the code for the emoji?
what about it being enabled in that channel specifically
lemme try other thing
what is with the a:?
animated emojis require that
oh
unless it isn't animated 
If its not animated, it would explain why its not working
my head hurts me rn 😭
?
for the @everyone role
Is the Emoji really animated?
I mean you own the server so you have admin by default
and two of the messages on the same channel and ye the channel are enabled the external emojis
yes but on the other account
@jaunty jewel
i wouldn't know, but ok then
@normal tusk https://github.com/discord/discord-api-docs/issues/5524 there seems to be an issue when the bot has Administrator affecting guild-channel-webhook permissions
2022.. bonk
it's still open?
well, you could try it without admin and see if it works
nope, i mean this api glitch~ish still exists today
you still cannot see names in the embed if you mention someone
i will just make it send a new message and defer the interaction cuz i have no mind for that 
ye thats true for now
wait the issue are still open
🗿
where the issues starts to appear 
this command are working on dms and.. ugh
aughhhhhhhhhhhhhhhhhhhhhhhhhh
HOW THE WORLD THIS THING EVEN POSSIBLE
THIS IS A DM AND THE BOT JUST SENT ME THE EMOJI BEFORE WUHS WORNG WITH IT!!!!!!!!
(THIS IS A ENTIRE NEW MESSAGE NOT A FOLLOW UP)
girl spamming wont take u anywhere to solve it
Hey there, is possible to use in autocomplete the member object defined in an option before? I don't want to use the member object of the user who is executing the command
Maybe ctx.options[0]?
nvm
i need to use ctx.options["myoptionname"]
this to get the before entred value
auto complete is sort of interaction so ye
Does anyone know how to use permissions for commands and/or buttons? I'm not sure if its possible with commands, but I want it so if a user does not have a specific permission, it will give that "Missing Permissions" errors below the buttons in red.
for buttons (or commands) you will have to compare the permissions for the user to the permissions you want. I dont think there is a way to do this
"Missing Permissions" errors below the buttons in red.
I would create your own "fake" permissions object to compare with the users useing this function
https://docs.pycord.dev/en/stable/api/data_classes.html#discord.Permissions.is_superset
how can i send an interaction to a specific channel?
You can only send an interaction response to the current channel. You can send an addition message to another channel though.
yeah i have a message which gets sent to the current channel with a confirmation, how can i send a message to another channel would it also work with a button?
ctx.channel.send() to send to another channel. And you can still have a view=. Views work on normal messages.
How can I find out a server inside the View class in the __init__ function?
self.message.guild.id doesn't work
What are you trying to do?
I think you would have to pass guild.id when you create the view
okay so then i can't do like
@discord.ui.button(label='Cancel', style=discord.ButtonStyle.red)
async def cancel_callback(self, button, interaction):
await something.channel_to_send.send('cancelled')``` or am i just not understanding
You can but you would still have to respond(send/edit/delete message, etc) to the button interaction. A bit annoying but not much we can do.
that's honestly fine since it will be the final message for the giveaways, there will only be another button to enter, how would i do it though?
Each server has its own database, so I need the server ID. I'm going to get the data from the database in __init__ so I don't have to do it in each button separately
.rtfm Interaction.response
one og those actions. Feel free to ask if you still dont understand
Is the view being created within another interaction?
I didn't think about that, thank you
It doesnot have to be I was just asking
I always create a class separately
yeah, i dont understand
await interaction.send_channel.response(embed=em, view=EnterButton()) the send channel is the channel id i want to reply to
Do you know how to pass an argument to a class (__init__)?
Yes, I will do it
I just thought that you can find out inside the class, it turns out I can't
you would need the channel object not just the id.
bot.get_partial_messagable(id) will get it for you
https://docs.pycord.dev/en/stable/api/clients.html#discord.Bot.get_partial_messageable
ahh okay thanks, ill try
oh but i still dont know how to send it, like do i do interaction.channel_object.response() or followup or i change it entirely
channel_object.send(view=view)
perfect, thank you! now i just gotta see how to access it in the button view class from my commands class
how to run a function when any slash command runs?
To add a new variable to the table on Sqlite3 do I need to recreate it?
For example, there is a table with 5 variables and I need to add 6th
Use an event listener for on_application_command
Do you mean columns?
Yes
Max number of options to choose from with autocomplete?
there is not really a limit for autocomplete, only choices have a limit of 25
awesome, ty
how do I make a utils file with my cogs? like a post log function in a class from another file I can call that sends a message to a channel with given values? how do I pass the bot object?
Utils.utils.PostLogs(self=self, line1="Test Log", line2="Test Line 2")
can I just pass self like this?
then call self.bot in the class?
Use the ALTER TABLE statement
Will this work for this purpose?
import discord, config
class Utilities():
async def PostLog(self, color, header, content, footer):
log_channel = self.bot.get_channel(config.bot_log_channel)
embed=discord.Embed(color=color)
embed.add_field(name=header, value=content, inline=False)
if footer != None:
embed.set_footer(text=footer)
await log_channel.send(embed=embed)
then can I call it with this?
@discord.slash_command(name="test_log")
async def test_logging(self, ctx, header, content, footer, color):
await utils.Utilities.PostLog(self=self, header=header, content=content, footer=footer, color=config.embed_color)
await ctx.respond("Send log!", ephemeral=True)
nvm ^ it does work first try too lol nice
That is a very jank way to do it
it is?
Why use a class?
Yeah lol you don't really need one
better for grouping if i make more utils
They all would still be accessible through utils file
its silly because its in a folder called utils so its Utils.utils.Utilities.PostLog()
Lmao
You can fix that with better imports
i already did
Nice
import cogs.utils.utils as utils
Seeing a lot of warnings of not doing change_presence in the on_ready command, any reason why?
warnings where?
on_ready can fire multiple times on startup
well read the post
oh ok
What function can I use for message ID that works like get_role()?
im creating a giveaway command, how should i go about checking the time if the giveaway has ended?
get_message? 
Did you even search for it at the docs?
is there still a way to play youtube videos with a pycord bot?
Wdym with play, like send the file or an embed?
embed
like a music bot
Send the link then ig
If you mean in the embed image, you can try putting the link there
I doubt that’ll work tho
does anyone have a warning command using mysql that I can look at? I just dont understand tutorials on mysql and it would help me way more of someone had a command to manipulate sql that I can base my warning system after? (it doesnt matter if its dpy or slash commands because im only interested in the sql calls)
?tag how2sql
higher quality image here-> https://pbs.twimg.com/media/E7h1FevWYAQx2zo?format=png&name=4096x4096
that doesn't necessarily help 😭
I first look at the documentation and then I ask a question
probably wanna create the table with the columns, then check if the user is in there, if so u can add or remove warnings from them
I just dont know how to create a table or anything with mysql and need help 😭
.
soo....
import mysql.connector as sql
mydb = sql.connect(
host = "",
user = "",
password = ""
)
cursor = mydb.cursor()
cursor.execute("CREATE TABLE warnings(id int, warns int)")
??
like I said I dont have a clue what im doing so just showing me that isnt very helpful... as I dont know how sql works or how to use it with python
i use postgres so i dont know the syntax for mysql in python so i cant help there, also, int can hold i think 10 digits so not useful for storing user ids
well, then how do I store a longer int?
bigint can store up to 19 digits
How can a bot delete a message what was sent it past run?
client.get_message(id).delete() can't see these messages
what are your intents?
intent = discord.Intents.all()
intent.message_content = True
...```
hmm
are you sure the bot have access to that channel?
btw discord.Intents.all() is more then enough to get the bot up and running with every single intent :/
It has full permissions on the server
After restarting it stops accepting previously sent messages
If a message to be deleted is sent in the same launch where it needs to be deleted, then everything works
try to print the message obj
see if the method is returning a obj or not
if it returns None so the bot aren't able to fetch the message or there is other issue :/
get_message can be None
ik that's why i mentioned that
bot.get_message will only return a message if it’s in the bot’s cache. Use await channel.fetch_message to fetch the message with an API call.
Thank you
well, bot.get_message exist but not bot.fetch_message for a client. only with something like channel.fetch_message
yeah thats what i meant
so im tryna make a scratch command and have this
@bot.command()
async def scratch(ctx):
rewards = ['reward1', 'reward2', 'reward3', 'reward4', 'reward5', 'reward6', 'reward7', 'reward8', 'reward9']
scratched = [False] * 9
async def scratch_button_callback(button: discord.ui.Button, interaction: discord.Interaction):
index = (view.children.index(button))
if not scratched[index]:
reward = random.choice(rewards)
rewards.remove(reward)
scratched[index] = True
button.emoji = '💰'
button.style = discord.ButtonStyle.success
await interaction.response.edit_message(view=view)
view = discord.ui.View()
for i in range(9):
button = discord.ui.Button(style=discord.ButtonStyle.secondary, emoji='📦', label='', row=i // 3)
button.callback = scratch_button_callback
view.add_item(button)
message = await ctx.send('Scratch the boxes to reveal your rewards!', view=view)
``` but when i press any of the buttons it creates, i get:
```Ignoring exception in view <View timeout=180.0 children=9> for item <Button style=<ButtonStyle.secondary: 2> url=None disabled=False label='' emoji=<PartialEmoji animated=False name='📦' id=None> row=1>:
Traceback (most recent call last):
File "C:\Users\Acer\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ui\view.py", line 382, in _scheduled_task
await item.callback(interaction)
TypeError: scratch_button_callback() missing 1 required positional argument: 'interaction'
The callback should only have one argument.
- async def scratch_button_callback(button: discord.ui.Button, interaction: discord.Interaction):
+ async def scratch_button_callback(interaction: discord.Interaction):
oh im stupid, thanks!
imo, from what I can see, your code would be better if you subclass instead of creating button objects
ye sub classing those things can help making the code more readable and easy to debug but its not the best if components have unfixed amount or its uncompleted or doesn't have a callback like link button but at that code subclassing will be kinda weird to make or can be made with tricky ways
how do I properly access a mysql database with a pycord command?
that depends on what library you are using
for mysql
im using mysql.connector
i cant wrap my head around that stuff, i think when i have the command actually working as intended, ill do that. im also having an issue here: whenever i win something, it doesnt change the emoji to the corresponding amount on the button
wtf
why are you doing this in the command callback !?!
where else should i?
@silver moat ?
in a class
I'm not familiar with that library
i will eventually, i tried it earlier in a class and it was so annoying to get it to work
and you still haven't got it to work
very true
its like the default mysql library..
import mysql.connector as sql
mydb = sql.connect(
host = "ip",
user = "user",
password = "pass"
)
cursor = mydb.cursor()
cusor.execute("")
you should be able to access your database just like normal inside of a pycord command callback
so just start the db connection before on_ready()? then i can call the cursor whenever?
something like this a bit better?
I'm not particularly fluent in sql, so I don't know much
You can subclass the discord.ui.Button class instead of the entire view.
pip list and send output
?tag install
- Uninstall discord.py or any other forks of discord.py you might have with the namespace
discord.
python -m pip uninstall discord.py discord -y
2a. Install py-cord
python -m pip install py-cord
2b. Update py-cord
python pip install -U py-cord
Installing other builds:
Note: You need to have git installed. Use ?tag git to find out how to install git.
Updating the module to master branch (unstable):
pip install -U git+https://github.com/Pycord-Development/pycord
step 1
also not sure where you got a py-cord v3 stable
kill terminal
well, v3 is still in alpha so it is missing features.
well, there's no py-cord 2.x.x
yay
Dont know where this question belongs but is there a way to convert this relative timestamp into seconds instead of mins when above 60 seconds
<t:1684657000:R> Gives -> <t:1684657000:R>
also is there any other way of adding a timer to an embeded/text response
There is no way to do that
That's the only "official" way to do it. Unless you're going to edit your message every minute which is not practical this is the best way to do it. Here's an example of how I use it in my code.
epochtime = int(time.time())
timez = (60*60*hours) + (60*minutes) + seconds
new_epoch = epochtime + timez
embed2 = discord.Embed(title ="Moderation Timeout",description=f"You have been timed out in {ctx.guild.name}. It will end <t:{new_epoch}:R>")
now let me ask my own question
How can I kick people from a specific guild? I tried this but it doesn't kick the user.
gulidz = 1094233212257042544
await gulidz.kick(user=user, reason=f"{reason} - {ctx.author}")
i think you need to use
gulidz = bot.get_guild(guild_id)
await gulidz.kick(...)
and then you can use that to kick
or if you are using cogs and have self.bot then
gulidz = self.bot.get_guild(guild_id)
await gulidz.kick(...)
m not sure if get_guild() is await or not but you can check it out
How could you go about locking a thread programmatically?
I don't see a specific method for it under discord.Thread
Nvm, found it.
alr
let me try
yes it worked ty so much
Is there a way yet to access the new global display name?
Any recommendations for shortening big if statements. E.g if role 1 in member.roles:
Do x
.
.
.
To role 20
if any(role in member.roles for role in [1,2,3]): if you're just looking if one of them is added
I need them added to separate lists based on roles
So you have a list like role_a = [] and you wanna add users with the role into it?
Yup
result = {"1": [], "2": [], "3": []} # The roles you're looking for
for i in range(len(result):
if int(i) in member.roles: # Check if the member has the role
result[i].append(member.id) # Add the member to the list
I think that's what you're looking for
Cheers
I want to timeout a user in a specific guild but this is not working. When I tried await guildz.timeout() it didn't work either.
async def synced_timeout(self, ctx, user, reason, hours, minutes, seconds):
guildz = self.bot.get_guild(1094233212257042544)
await user.timeout(guild_id=guildz, reason=f"{reason} - {ctx.author}", until=discord.utils.utcnow() + datetime.timedelta(hours=hours, minutes=minutes, seconds=seconds))
``````py
Member.timeout() got an unexpected keyword argument 'guild_id'
I also tried guild=guildz but that didn't work as well
Is the bot public or not?
You will have to get the member object in the guild
member = guildz.get_member(user)
and set a timeout for the member object
alr let me try that
Will the bot be public or on a privat server?
There is a new release, 22.3.1 to 23.1.2 Does this really matter if I make that change?
And I also installed the python 11 through microsoft, do I need to add it to my varibles now?
Oh I cant even do that...
public
wait
It's for a bunch of servers that are linked together
The servers are public but the bot is only being used for those servers
oh wait
nvm
is something like this possible with pycord?
notsobot uses commands with spaces in them like /a convert or /a identify and i was wondering how this is possible
Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - pycord/slash_groups.py at master · Pycord-Development/pycord
Isn't it just slash commands group? https://guide.pycord.dev/interactions/application-commands/slash-commands#sub-groups
Learn all about Slash Commands and how to implement them into your Discord Bot with Pycord!
;3
ill take a look, thank you
yes, that's what i was looking for
thank you for the links lol
How do I have it close a form post
as a bot or as a user
How to insert items in a view?
Like self.add_item, but with ability to specify position of an item in a row?
eh, with a view class
what?
class SomeClass(View):
def __init__(self):
super().__init__(...)
self.add_item(<Button "World">)
@ui.button(...)
async def hey(self):
...
Button hey will be first than the world button
if you create a new one after the button, the button should be at the right then
just create to buttons and you will see what I mean
?
Is changing a channel's name rate limited?... I just tried changing it every 5 seconds (for testing), and it only changed twice?...
class MyView(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
@discord.ui.button(label="A button")
async def button_callback(self, button, interaction):
await interaction.response.send_message("A button", ephemeral=True)
@discord.ui.button(label="B button")
async def second_button_callback(self, button, interaction):
await interaction.response.send_message("B button", ephemeral=True)
soemthing like this @spring hare
Learn all about implementing buttons in your Discord Bot using Pycord.
you can change a channel name every minute or so. I forgot the exact figures, but that should be in the ball park.
Channel was something like 5 or 10 minutes
Blue button was created with self.add_item
All other buttons and select menu were created inside View class
I wanna place my blue button to the left
Sorry, I should have Googled first. Looks like it might be twice every 10 min? Thanks though 
self.add_item do self.children.append(item) at the end, but I just can't do the same stuff with insert for some reason
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In components.0.components.1: The specified component exceeds the maximum width
If I try to self.children.insert(1, value)
seems like you are trying to add it to the row of the select menu
I use the same row (row 1), but this occurs if I don't use self.add_item
✅ self.add_item row=1
❌ self.children.append row=1
I just don't understand why self.add_item and self.remove_item exist, but not self.insert_item
then make a PR
fair enough
I just don't understand how to insert it
If just self.children.append don't work
Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - pycord/view.py at master · Pycord-Development/pycord
Okay, I found the problem
I need to also add item._rendered_row
Solution (if someone needed)
self.add_item(item)
self.children.insert(pos, self.children[-1])
del self.children[-1]```
or insert self.children.pop(-1)
but yeah wouldn't be too hard to pr an insert method
someone have any idea about a ui builder (library) to build a ui components and export its request?
Discord ui components builder?
Or wdym
Discord moment
fr :\
I still don't understand you
i want to work with a interactions webhook so i need a way to get a ui components request builder
Why you can't just use pycord?
how to export the request :>?
?
I think they want to get json
exactly
I think you can just override _from_data in Interaction class
but for interactions (the image is for commands rigs data)
Ping me if it works
Works?
there is no method called _from_data
Interaction._from_data
Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - pycord/interactions.py at 1fea31b27aa36643692fc45c675d6bac6a98d1b3 · Pycord-Development/pycord
okay but the is an interaction (not ui) and like this to get that request i'll need a working bot
i'm searching for ui stuff
wdym???
This is from official pycord guide
class MyView(discord.ui.View):
@discord.ui.button(label="Button 1", row=0, style=discord.ButtonStyle.primary)
async def first_button_callback(self, button, interaction):
await interaction.response.send_message("You pressed me!")
@discord.ui.button(label="Button 2", row=0, style=discord.ButtonStyle.primary)
async def second_button_callback(self, button, interaction):
await interaction.response.send_message("You pressed me!")
@discord.ui.select(
row = 1,
options = [...]
)
async def select_callback(self, select, interaction):
await interaction.response.send_message(f"Awesome! I like {select.values[0]} too!")```
Buttons get the same interaction as select or modals
from discord import Interaction
def custom_from_data(self, data):
print(data)
self._old_from_data(data)
Interaction._old_from_data = Interaction._from_data
Interaction._from_data = custom_from_data
@normal tusk It works?
bot
As a /close command
tbh i have no idea if it or not cuz i think i have an internet issue and the gateway doesn't wanna connect :|
Interesting, does anyone know why my webhook is returning a Invalid Webhook Token on the 480th message, no matter what that message is?
Webhook Declaration:
history_webhook = await ctx.channel.create_webhook(name="CopyMessages", avatar=None, reason="For CopyMessages")
Inside for loop looping through message history:
await history_webhook.send(content=content, embeds=embeds, files=files,
username=nick,
avatar_url=avatar)
Error
Ignoring exception in command paste:
Traceback (most recent call last):
File "C:\Users\Thiel User\Documents\GitHub\CopyMessages\main.py", line 115, in paste
await loading_message.edit(embed=embed)
File "C:\Users\Thiel User\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\webhook\async_.py", line 899, in edit
return await self._state._webhook.edit_message(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Thiel User\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\webhook\async_.py", line 1945, in edit_message
data = await adapter.edit_webhook_message(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Thiel User\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\webhook\async_.py", line 221, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 401 Unauthorized (error code: 50027): Invalid Webhook Token
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\Thiel User\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\commands\core.py", line 124, in wrapped
ret = await coro(arg)
^^^^^^^^^^^^^^^
File "C:\Users\Thiel User\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\commands\core.py", line 982, in _invoke
await self.callback(ctx, **kwargs)
File "C:\Users\Thiel User\Documents\GitHub\CopyMessages\main.py", line 123, in paste
await loading_message.edit(embed=embed)
File "C:\Users\Thiel User\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\webhook\async_.py", line 899, in edit
return await self._state._webhook.edit_message(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Thiel User\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\webhook\async_.py", line 1945, in edit_message
data = await adapter.edit_webhook_message(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Thiel User\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\webhook\async_.py", line 221, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 401 Unauthorized (error code: 50027): Invalid Webhook Token
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Thiel User\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\bot.py", line 1114, in invoke_application_command
await ctx.command.invoke(ctx)
File "C:\Users\Thiel User\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\commands\core.py", line 375, in invoke
await injected(ctx)
File "C:\Users\Thiel User\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\commands\core.py", line 132, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: HTTPException: 401 Unauthorized (error code: 50027): Invalid Webhook Token
I apologize for that wall of an error
read the last line of the error
you literally wrote the answer here yourself
It is not an invalid webhook tho. If i restart the bot it will work with that webhook perfectly. Like I said, it sends the webhook messages perfectly for the first 479 messages, then sends that error on the 480th.
To clarify, it doesn't create a new webhook every restart. It first checks if theres already an existing webhook with the name CopyMessages. If it does, it doesn't create a new one and instead uses that.
Edit: If the error is valid, and the webhook is invalid, am I missing something? Is there a message limit for webhooks in one session or period of time?
@solemn idol @young bone
hold up, is there a limit to the amount of times a message can be edited?
@discord.default_permissions()
ty
users still see the commands when they type /
they cant use but they see
maybe your webhook got broken because spamming 🤨
add inside of the the default permission
@topaz rune
eg
@bot.slash_command("cool", description="this is my cool command!")
@discord.default_permissions(administrator=True)
async def cool(ctx: discord.ApplicationContext):
# do some cool stuff here
pass
is there a way to get a msg content if the msg is deleted?
for reporting a message log in specific channel
You get the message obj in the on_message_delete event
How would I queue audio for the voice client to play after the current audio has finished?
I have tried using voice_client.is_playing() but it returns false even when audio is being played
Pass a function to the after parameter in the play method
In that function, play the next song
.rtfm voiceclient.play
gotcha thanks
Is there a way to have a slash command option, if one of the options is selected it opens another option?
Not directly, but you could manipulate autocomplete to fill results based on other options
Hello, I have a question. How I can code that the users who authorized this joins a server?
the image didn't load yet.. if you mean OAuth2
so it is Oauth2 flow work with DB :)
Yes I mean OAuth2, how I can join servers for the users wo authorized this?
is there a way to call a page callback(interaction) from a custom_view in a Page?
see on discord devs web there is something called redirect url set it
even if I pass in a reference of the paginator to the view, and call "page_action(interaction)", it doesn't call the page.callback(interaction).
Anyone know the rate limit for editing a single message? (ie. a status post that updates every X seconds)
so i have a bot that uses oauth to give bot access to have them join server how do i actually have them join the server
nope i will not because google not understand code
how can i add reactions to the result of a slash command?
and that's why i used follow up hook
.rtfm response
discord.InteractionResponse
discord.InteractionResponse.defer
discord.InteractionResponse.edit_message
discord.InteractionResponse.is_done
discord.InteractionResponse.pong
discord.InteractionResponse.send_autocomplete_result
discord.InteractionResponse.send_message
discord.InteractionResponse.send_modal
discord.InteractionResponseType
discord.InteractionResponseType.pong
discord.InteractionResponseType.channel_message
discord.InteractionResponseType.deferred_channel_message
discord.InteractionResponseType.deferred_message_update
discord.InteractionResponseType.message_update
discord.InteractionResponseType.auto_complete_result
discord.InteractionResponseType.modal
discord.Interaction.delete_original_response
discord.Interaction.edit_original_response
discord.Interaction.original_response
discord.Interaction.response
Mhm
That is for the slash command question
thank you! couldnt find the docs for this, pycord docs are annoying to navigate
Im on my phone so its kinda hard to find the right one
.rtfm ApplicationContext
discord.ApplicationContext.pins
discord.ApplicationContext.respond
discord.ApplicationContext.response
discord.ApplicationContext.selected_options
discord.ApplicationContext.send
discord.ApplicationContext.send_followup
discord.ApplicationContext.send_modal
discord.ApplicationContext.send_response
discord.ApplicationContext.trigger_typing
discord.ApplicationContext.typing
discord.ApplicationContext.unselected_options
discord.ApplicationContext.user
discord.ApplicationContext.voice_client
discord.ext.bridge.BridgeApplicationContext
discord.ext.bridge.BridgeApplicationContext.app_permissions
discord.ext.bridge.BridgeApplicationContext.author
discord.ext.bridge.BridgeApplicationContext.can_send
discord.ext.bridge.BridgeApplicationContext.channel
discord.ext.bridge.BridgeApplicationContext.channel_id
discord.ext.bridge.BridgeApplicationContext.cog

