#Basic Pycord Help (Quick Questions Only)
1 messages · Page 67 of 1
Do you have members intent?
Yeah, these right?
And the bot has admin permissions
You also need to enable them in your code
Ohhh - then no, I don't think I have
I have not.. needed to do this yet for the / commands and ctx.respond.. I will look at doing that!
Try audio.file.read()
I have personally had similar issues. Wav files saved by vc recording do not get loaded into pydub.AudioSegment or numpy arrays. Normal files do. And the saved files can even be played back
But when saving them as MP3 they can be loaded into pydub
I'm not sure why this happens
ahh okay, so then I'm guessing I should use the MP3 sink and also audio.file.read() . Or could I still use audio.file.read() with the Wave Sink to fix it?
Internally the mp3 sink just saves as wav and converts them using FFMpeg. And that works. Everything is just weird 💀
Try both. If wav works, well and good
If not try MP3 sink
perfect, I will try that. Thank you!
||In case you really want wav, convert the mp3 back into wav using ffmpeg||
Would the command be (to select a member)
async def member_roles(ctx, member: discord.Member()):
...
Or how would you get a discord member using discord.Member() in the bot command?
Remove the ()
Easy as that
Do I need to do this in every cog that uses them, or just when I init the bot?
how to write tests for my bot?
Quick question, how do I send an embed?
Never mind, figured it out
.rftm embed
.rtfm embed
discord.Embed
discord.Embed.Empty
discord.Embed.add_field
discord.Embed.append_field
discord.Embed.author
discord.Embed.clear_fields
discord.Embed.color
discord.Embed.colour
discord.Embed.copy
discord.Embed.description
discord.Embed.fields
discord.Embed.footer
discord.Embed.from_dict
discord.Embed.image
discord.Embed.insert_field_at
discord.Embed.provider
discord.Embed.remove_author
discord.Embed.remove_field
discord.Embed.remove_footer
discord.Embed.remove_image
Just what I needed
#883236900171816970 next time please :)
sorry
I'm going insane : ^ )
I've got to the point where my background task can get the member objects.. But I can't get the permissions to update their nicknames..? My bot is an admin and all intents are enabled..?
Aight - moving the bot up in the list of role priority fixed it. Glad I thought of that first x)
That makes no sense
how can i do bot.loop.create_task(daily()) in a cog?
The same way?...
you cant to this in cogs
why not 🤔
f = discord.File(fp=output_buffer, filename=f"winner-{formatted_date}.png")
em = discord.Embed(title=f"day", description=f"test desc", colour=colour().main, timestamp=datetime.now())
em.set_image(url=f"attachment://winner-{formatted_date}.png")
em.set_footer(text=f"test")
await ctx.send(file=f, embed=em)
when i use this my image is not in the embed
its out of the embed
can somebody help?
?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)```
i exactly did it like this
any errors?
no nothing
are you sure?
isnt fp filepath?
now removed fp=
didnt changed anything
lol found the problem bruh
you cant have a space in the filename
removed the space and now image is showing in the embed
ok
Was the space in the timestamp?
I got the wave sink to work by resampling the audio to 16000hz before writing it
audio_data = audio.file.getbuffer()
num_channels = 2
bytes_per_sample = 2
sample_rate_in = 48000
sample_rate_out = 16000
with wave.open("talk.wav", "wb") as wav_file:
wav_file.setnchannels(num_channels)
wav_file.setsampwidth(bytes_per_sample)
wav_file.setframerate(sample_rate_out)
resampled_data = audioop.ratecv(audio_data, bytes_per_sample, num_channels, sample_rate_in, sample_rate_out, None)[0]
wav_file.writeframes(resampled_data)```
what class to do this
what?
when i click on a user profile, it shows me that section under roles
it’s an experimental feature iirc
if i recall correctly
if discord released a new thing, it would be in their api announcement channel
actually nvm I'm dumb: https://discord.com/developers/docs/tutorials/configuring-app-metadata-for-linked-roles
ty
Ok how should I ask this, i have a code, his work is sending a message to WhatsApp with information, the thing is I need to get the message as soon as possible
import pywhatkit as pw
pw.sendwhatmsg("number", "message", 10, 30)
The last part is the one that gives me trouble, when I put 0,0 python takes it like 12pm
There's like no one here that knows about Whatsapp's api framework. I suggest reading documentation about it or joining a specific python whatsapp server
💀, ty tho
Ohh that's cool
does InputText have live regex validation like how the min max length? or do i only have the choice to do validation after submission?
4000 but if you want it in an Embed you have to limit to 1200 I think. Is that what you mean?
i mean validation on what they type like only numbers allowed or certain format following a regex
you know like those online forms that goes red when you type an invalid character
rn it only does validation for the length of the text you put in the fields
Text and that only ^
i see so i can only validate the content of the text after submission
Yes
would be nice if there's a pattern= argument for that
Is there a way to add more than 2 fields to an modal because if i copy paste a field it doen’t work
You can add 25 fields
Oh sorry
Modal
I thought embed 💀
xD
Modal can have upto 5 input texts
imagine having 25 input text on a modal 🤣
And how do i add more? Thank you for you response
self.add_item()
Ok i try thank you
self.add_item(discord.ui.InputText(label="Name", required=True))
Is there any module that converts a JSON discord embed raw to an Embed object?
Is there a func like setup_hook that I can use in my subclass for commands.Bot
Just like there is in dpy
.rtfm embed.from
What's the best way to silently acknowledge a button/interaction?
I'm assuming editing a message with it's previous content or something like that?
or is there an easier way
not exactly, but you can override the bot.start to smth like this
async def start(self):
... # whatever you want to do
await super().start()
on the master branch you also have @client.listen(once=True)
wym?
Did you tell this to me or Colin?
you
He means to subclass the start method of the bot
if you're running a subclassed bot objct
mhm and where do I add the @client.listen
you wouldn't need it in that case
Alright
assuming you're just looking to run some coroutine when you run bot.start()
defer and forget. defer is a valid response for message components and does not need a followup, unlike app cmds
problem with deferring is that the button stays greyed out until the defer times out
hmm wdym?
I'm just playing around with the way that I respond to user interactions. I'm manipulating a Lobby object that has a lot of methods, ideally the display to the lobby channel is done from within those methods as they can be called by multiple sources, including the button. So I don't want to return a message at all from clicking the button, just run the Lobby method
oh wow i'm sleep deprived
forgot I disabled the button after clicking it if no one else was in the lobby, works as intended
I have a question. I cannot get my bot to mention users and roles in a response to an interaction in a private thread. allowed_mentions are set to all as an option for the bot and are set to all in the ctx.respond() function. However, allowed_mentions is no option in the interaction.response.edit_message function. Anyone know how to fix this?
When you edit a message it will not ping the user or role. So allowed mentions does not matter.
Hello Guys, Is there a way to know which user invite a bot to his server ?
I didn't find this anywhere atm. Thanks for helping
Thanks, I don't know how I missed that... Sorry!
I get: TypeError: FoodieBot.start() takes 1 positional argument but 2 were given when I do run that exact code
heres my code: https://neil.hrzn.pics/tC3F9O7lqH.png
.start() takes in token as an arg cuz if I'm not wrong its called from .login()
oh wait, its ran from .run()
If you had copy pasted the code instead of a screenshot it would have taken less space 😉
didnt feel like copy pasting, did u find a solution tho
change the parameters to (self, *args, **kwargs)
and pass *args, **kwargs to super start
ok
I seem to be getting a Unknown Interaction error everytime I run any of my commands now.
And all of em are guild commands (because I use the debug_guilds kwarg in commands.Bot)
huh?
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction
wait 1s
Traceback (most recent call last):
File "C:\Users\hp\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\hp\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\commands\core.py", line 375, in invoke
await injected(ctx)
File "C:\Users\hp\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: NotFound: 404 Not Found (error code: 10062): Unknown interaction```
here ya go
there should be a bit more 
above the top line
Mhm, you mean like the full full traceback?

And is there any way I can convert an embed to json raw?
.rtfm embed.to
Hi guys . Can anyone post a list of errors.
you need to write a couple of commands like this one.
you mean this?
https://docs.pycord.dev/en/stable/api/exceptions.html
Exception Hierarchy:- Exception,-- DiscordException,-- ClientException,- InvalidData, InvalidArgument, LoginFailure, ConnectionClosed, PrivilegedIntentsRequired, InteractionResponded.,., NoMoreItem...
The following section outlines the API of Pycord’s prefixed command extension module. Bots: Bot: Attributes activity, allowed_mentions, application_flags, application_id, cached_messages, case_inse...
@очистка.error
async def clear_error(ctx,error):
if isinstance( error, commands.MissingRequiredArgument):
await ctx.send(f'{ctx.author.mention},обязательно укажите аргумент.')
if isinstance( error, commands.MissingPermissions):
await ctx.send(f'{ctx.author.mention},у вас нету прав на использование.')
@proud mason thx
🤗
does guild_only() not block the commands from being viewable in DMs?
i thought it used to, but i'm having commands show up using both guild_only() and commands.guild_only()
No. It doesnt block commands from displaying
for some reason, the task loop in my discord bot just, stopped working
it works on my development computer, but on the server i'm hosting it, it just doesn't run (the next_iteration property returns None)
I've tried restarting it, changing the interval, even completely recloning the repository for the bot and restarting it
but it works completely fine on my local computer
np 🙃
pretty sure it used to
Hi, how do I get the embed in a ephemeral msg
Like an embed is sent and the msg is ephemeral, how do I get that embed and modify it like changing the title etc (ik I can do it thru embed.title = "my title here" and then edit the msg)
can you share python version and pip list on both, your computer and server
do you not have access to the embed object?
No because I'm doing it in the view, like clicking a button on the view changes the embed
get the 1st item (if you are only having 1 embed)
does that exist
yea but like HOW do i get the msg
I know .embeds exists
Great ill lyk if it works
cool
Oh yeah and how do I edit a msg after I've sent a response?
interaction.edit_original_response is the best way
||Although that will stop working after 15 mins||
Also I sent a modal as the resp, and I do .wait() on that modal, it doesn't actually end up waiting and just does the code right below it
Oh wait, it wasnt awaited, whoops
Wait uh
How tf do I take data back from the modal class? I tried to set a variable and then access that using ```py
my_modal = ModalClass()
.... # Wait stuff here
answer = my_modal.var_name
thats right
but it returns None
oh and dont forget to put self.stop() at the end of the modal callback
hmm and how do you set it?
async def creation(self, select: discord.ui.Select, interaction: discord.Interaction):
message = interaction.message
embed = message.embeds[0]
if select.values[0] == "author":
author_modal = TextModal(title="stuff here", text="text")
await interaction.response.send_modal(author_modal)
await author_modal.wait()
author = author_modal.text
print(author)
class TextModal(discord.ui.Modal):
text: str | None = None
def __init__(self, title: str, text: str) -> None:
super().__init__(title=title)
self.add_item(discord.ui.InputText(label=text, style=discord.InputTextStyle.long))
async def callback(self, interaction: discord.Interaction):
text = self.children[0].value
self.stop()```
I do that
self hmm, though the text var isnt set as a class var but sure ima change that
Lemme try that rq
Works but the embed errors out, what should I do here as I'm trying to reuse that same modal but just change the kwargs and handle everything in the select
you cant reuse the same modal object
yes I can lol
you will need to create a new one
ah ok
How do I make the modal not error out
send a response?
But like what type of response?
send_message ig
alr its ok ima just re make modal classes for each thing ima do with the select
send a placeholder text like "Received" ephemerally if you dont want to send an actual response
Also is there like a input thingy for links or how do I verify if the link is an asset or smth
Because I basically want to get a png from a modal or some way
nothing which is discord native
you can check stuff using regex
Is there any method or a way to get the author name from an embed?
embed.author.name
Found it!
I have this code here```py
import discord, asyncio, random
from discord.commands import slash_command, Option
from discord.ext import commands
from myfunctions import Load, Save
songs = ["CarelessWhisper"]
class Join(commands.Cog):
def init(self, client):
self.client = client
@slash_command(description="Joins a channel")
async def join(self, ctx):
if ctx.author.voice:
channel = ctx.author.voice.channel
try:
await channel.connect()
except:
await ctx.voice_client.move_to(channel)
Data = Load()
Data[str(ctx.guild.id)] = channel.id
Save(Data)
embed = discord.Embed(
title = "Joined Channel",
description = "Successfully joined channel. You can now enjoy the best music!",
color = discord.Color.green()
)
embed.set_footer(text="Powered by VersaDev.org")
if not ctx.guild.voice_client.is_playing():
ctx.guild.voice_client.play(source=f"file:{random.choice(songs)}.mp3")
Message = await ctx.respond(embed=embed)but when it comes to py
ctx.guild.voice_client.play(source=f"file:{random.choice(songs)}.mp3"), It runs into the error:
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: ClientException: Not connected to voice``` even when the bot is actually in the voice channel
Only py-cord is installed and not discordpy, yet it still does not play music
what is your py-cord version?
2.2.2
update to the new version #library-updates
Great, thanks!
I created a paginator and wanted to have the paginator accutalize the pages at a certain interval. For this I created an update function that loads the new pages and then the view should be updated. Unfortunately this does not work the way I did it. Does anyone have an idea and can help me how to do this?
class PaginatorInfoView(Paginator):
async def __new__(cls, *args, **kwargs):
obj = super().__new__(cls)
await obj.__init__(*args, **kwargs)
return obj
async def __init__(self, bot: discord.Bot):
self.bot = bot
self.pages = await self.update_pages()
view = await self.generate_view()
custom_buttons =[#Code for Buttons]
super().__init__(pages=self.pages, use_default_buttons=False, custom_buttons=custom_buttons, custom_view=view, timeout=None, author_check=False)
asyncio.ensure_future(self.update_loop())
async def update_pages(self):
data = await dab.get_all_spots()
pages = []
spots_per_page = 6
# Erstelle eine neue Seite
embed = discord.Embed(title="Spotübersicht")
.
.
#embed.set_footer(text=spot_text)
pages.append(embed)
# Entferne NULL-Elemente
return [p for p in pages if p is not None]
async def update_loop(self):
while True:
self.pages = await self.update_pages()
self.update()
print("Pages updated")
await asyncio.sleep(30)
async def generate_view(self):
view = SpotDetails(self.bot)
return view```
code
@discord.user_command(name="Account Creation Date", guild_ids=[number])
async def account_creation_date(ctx, *, member: discord.Member):
await ctx.send(f"{member.name}'s account was created on {member.created_at}")```
error
Ignoring exception in command Account Creation Date:
Traceback (most recent call last):
File "/usr/local/lib/python3.8/dist-packages/discord/commands/core.py", line 124, in wrapped
ret = await coro(arg)
File "/usr/local/lib/python3.8/dist-packages/discord/commands/core.py", line 1571, in _invoke
await self.callback(self.cog, ctx, target)
TypeError: account_creation_date() takes 1 positional argument but 3 were given
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/usr/local/lib/python3.8/dist-packages/discord/bot.py", line 1114, in invoke_application_command
await ctx.command.invoke(ctx)
File "/usr/local/lib/python3.8/dist-packages/discord/commands/core.py", line 375, in invoke
await injected(ctx)
File "/usr/local/lib/python3.8/dist-packages/discord/commands/core.py", line 132, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: account_creation_date() takes 1 positional argument but 3 were given```
help pls)
remove the *, and use ctx.respond
Learn all about Context Menus (User Commands & Message Commands) and how to implement them into your Discord Bot with Pycord!
do you know basic python?
only started learning
sorry
without the basic´s of Python you will have many problems creating a discord bot
🤣 i founded problem
Pls learn Python first
And verbs conjugation
view = CreateSuggestionView()
message = await interaction.response.send_message(content=PreviewMessage, embed=suggestion_embed, ephemeral=True, view=view)
view.message = message
send_message doesn't return message, any alternatives?
Like I just want this function here to have the message property
class CreateSuggestionView(ui.View):
async def disable_all_items(self):
for item in self.children:
item.disabled = True
await self.message.edit(view=self)
.rtfm interaction.original_response
What?
Why are you trying to override a function?
What it's supposed to do is disable all the buttons attached to the embed
Am i doing something wrong?
.rtfm View.disable_all_items
damn
that makes my life easier
ty :o
Any idea why i got this error after switching to interaction.original_response btw?
it thinks the message is a coroutine object..?
view.message = interaction.original_response()
I'll still switch to this but i just wanna understand where i went wrong
oh i needed to await it 
nvm thanks for the help
OH
THIS IS PYCORD
why am i here
im a dumbass
Is there a way to listen to the sound the bot hears from the channel live from a different location?
afaik theres no way in pycord to live stream audio only to record it
or there a way to record the sound as a single piece instead of it being specific to the user?
ive been trying to work my own janky solution for voice commands but not much luck so far
Is it impossible to access the sound data without interrupting the conversation
afaik yes
Is it possible to record the entire conversation as a single piece
not like @glossy tusk 's record etc.
i think it should be
I have tried manually combining different recording, but it becomes very chaotic because the recording starts with the sound action.
thank you btw
I know but
This is save audio from sink.audio_data.items()
Different users audio in there
okey thx a lot
Yes. PR is open
##1980
Thx ı'll work on it
Does the library support python 3.10?
Wouldn't this method be faulty if a user joins the conversation and leaves after a very, very short time?
Or my brain had a hard time understanding the prepared algorithm for combining the sounds.
edit: Oh, or does it continue recording until the stop command comes after receiving the first sound from the user?
In other words, is the voice recording of a person who is included in the 50th second of a 100-second speech and comes out at the 55th second, is recorded as 50 seconds instead of 5 seconds? I don't have an environment to test this
Failed to load slashes.py from ./cogs:
Extension 'cogs.slashes' raised an error: ImportError: cannot import name 'InputText' from 'discord.ui' (/home/container/.local/lib/python3.9/site-packages/discord/ui/__init__.py)
Failed to load casino.py from ./cogs/Casino:
Extension 'cogs.Casino.casino' raised an error: ImportError: cannot import name 'SlashCommandOptionType' from 'discord.enums' (/home/container/.local/lib/python3.9/site-packages/discord/enums.py)
Failed to load casino_misc.py from ./cogs/Casino:
Extension 'cogs.Casino.casino_misc' raised an error: ImportError: cannot import name 'SlashCommandOptionType' from 'discord.enums' (/home/container/.local/lib/python3.9/site-packages/discord/enums.py)
Failed to load casino_games.py from ./cogs/Casino:
Extension 'cogs.Casino.casino_games' raised an error: AttributeError: module 'discord' has no attribute 'Cog'
Failed to load miner_only.py from ./cogs:
Extension 'cogs.miner_only' raised an error: ImportError: cannot import name 'SlashCommandOptionType' from 'discord.enums' (/home/container/.local/lib/python3.9/site-packages/discord/enums.py)
Failed to load modals.py from ./cogs:
Extension 'cogs.modals' raised an error: ImportError: cannot import name 'InputText' from 'discord.ui' (/home/container/.local/lib/python3.9/site-packages/discord/ui/__init__.py)
/home/container/cogs/events.py:604: RuntimeWarning: coroutine 'BotBase.add_cog' was never awaited
client.add_cog(events(client))
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Failed to load events.py from ./cogs:
Extension 'cogs.events' raised an error: TypeError: object NoneType can't be used in 'await' expression```
Why would I be getting these erorrs on one hosting service and not the other? Amazon Azure VPS doesn't have these issues but then when I use Bisects VPS it does? Any reasons?
It's hard to know what code is correct if two different host give me code issues..
They're both using PyCord/on the same python version
the environment variables or system paths could be different or the, or the vps service may not allow you to access or auto-access some locations. I think this is not an issue with python or pycord. Contact service providers
Wdum by "the environment variables or system paths could be different"
Shouldn't be a problem
I think this is a clear case of bad installation
Dpy is conflicting with pycord
Uninstall dpy py-cord and any other discord related library. And reinstall py-cord
I have no access to those commands
Oh hmm
well pip uninstall works in the console right
Let me check
Nope
I have these only. But no commands can go into console
I just mention my packages in a requirements.txt
There is a lot of info in https://discord.com/channels/881207955029110855/1087791762615050321
Check that out. If that is confusing, lmk I'll write a summary. It could be beneficial for others down the road
Then create a new python file and put
import os
os.system("pip uninstall discord.py discord py-cord")
After that is done, change it to install py-cord
Yea sure. But make sure to comment other stuff out for the time being
You should consider upgrading via the '/usr/local/bin/python -m pip install --upgrade pip' command.
Found existing installation: discord.py 2.2.2
Uninstalling discord.py-2.2.2:
Would remove:
/home/container/.local/lib/python3.9/site-packages/discord.py-2.2.2.dist-info/*
/home/container/.local/lib/python3.9/site-packages/discord/*
Would not remove (might be manually added):
/home/container/.local/lib/python3.9/site-packages/discord/bot.py
/home/container/.local/lib/python3.9/site-packages/discord/cog.py
/home/container/.local/lib/python3.9/site-packages/discord/commands/__init__.py
/home/container/.local/lib/python3.9/site-packages/discord/commands/context.py
/home/container/.local/lib/python3.9/site-packages/discord/commands/core.py
/home/container/.local/lib/python3.9/site-packages/discord/commands/errors.py
/home/container/.local/lib/python3.9/site-packages/discord/commands/options.py
/home/container/.local/lib/python3.9/site-packages/discord/commands/permissions.py
/home/container/.local/lib/python3.9/site-packages/discord/ext/pages/__init__.py
/home/container/.local/lib/python3.9/site-packages/discord/ext/pages/pagination.py
/home/container/.local/lib/python3.9/site-packages/discord/iterators.py
/home/container/.local/lib/python3.9/site-packages/discord/scheduled_events.py
/home/container/.local/lib/python3.9/site-packages/discord/sinks/__init__.py
/home/container/.local/lib/python3.9/site-packages/discord/sinks/core.py
/home/container/.local/lib/python3.9/site-packages/discord/sinks/errors.py
/home/container/.local/lib/python3.9/site-packages/discord/sinks/m4a.py
/home/container/.local/lib/python3.9/site-packages/discord/sinks/mka.py
/home/container/.local/lib/python3.9/site-packages/discord/sinks/mkv.py
/home/container/.local/lib/python3.9/site-packages/discord/sinks/mp3.py
/home/container/.local/lib/python3.9/site-packages/discord/sinks/mp4.py
/home/container/.local/lib/python3.9/site-packages/discord/sinks/ogg.py
/home/container/.local/lib/python3.9/site-packages/discord/sinks/pcm.py
/home/container/.local/lib/python3.9/site-packages/discord/sinks/wave.py
/home/container/.local/lib/python3.9/site-packages/discord/types/raw_models.py
/home/container/.local/lib/python3.9/site-packages/discord/types/scheduled_events.py
/home/container/.local/lib/python3.9/site-packages/discord/ui/input_text.py```
Said in console that it was being removed. But it says "Would not remove"

What would it not remove
Oh wait put -y in there iirc
Wdum -y
I never use the os module 💀
I am used to using console linux but this host is diff
pip uninstall -y ...
Oh
I can't use commands
No put that in the os.system cmd
import os
os.system("pip uninstall -y discord.py discord py-cord")
Uhh if that doesn't work then delete the discord folder from site packages yourself
You should consider upgrading via the '/usr/local/bin/python -m pip install --upgrade pip' command.
Found existing installation: discord.py 2.2.2
Uninstalling discord.py-2.2.2:
Successfully uninstalled discord.py-2.2.2
It might reinstall every restart 💀
Maybe I can keep that at the top of the code if that is the case
import importlib
# Replace 'module_name' with the name of the module you want to check
module_name = 'numpy'
try:
importlib.import_module(module_name)
print("True")
except ImportError:
print("False")```
Let me try this
That will slow down your startup time by a lot
trying stuff now let me check if it reinstalls
#import os
#os.system("pip uninstall discord.py discord py-cord")
import importlib
# Replace 'module_name' with the name of the module you want to check
module_name = 'discord.py'
try:
importlib.import_module(module_name)
print("True")
except ImportError:
print("False")```
Is discord.py listed like this in module?
Cause this is printing false which is good..
Yup still installed
Let me try manually deleting every time with the code
discord.py py-cord has been uninstalled
/home/container/syst.py:11: RuntimeWarning: coroutine 'BotBase.load_extension' was never awaited
client.load_extension((f"{path[2:]}/{filename[:-3]}").replace("/", "."))
RuntimeWarning: Enable tracemalloc to get the object allocation traceback```
💀
hi, how can i get the name of a Member in one guild? if i use member.name it returns, for example, Snakeice#7702, my global name, non maybe "Superpippo", my name in that server. Thanks!
I think you should. I've been looking for a few days and I'm having a hard time understanding them.
.rtfm member.nick
Hmm alr ig
Thanks!
@proud mason
If the user is on the channel at the beginning of the recording and then leaves the channel and reconnects after a while, the time difference in the recording disappears. Can you detect and equalize the time difference?
Oh it disappears? Like no silence between leaving and joining?
yeah
I feel this happens because data.timestamp gets paused when the user leaves
It is like discord really doesn't like us to receive audio 💀
Ironically the worst created part of discord
Separate timestamps for all users. No way to coordinate between timestamps of different users
Now i really wonder whether audio should be timed based on data.timestamp or actual packet receiving time
Join and speak 10 second and leave. 10 seconds After, join and speak 10 seconds. The recording 20 seconds. WTF
Where is my 10 seconds .d
I really didn't want to do this, but ig a solution which primarily uses data.timestamp and actual packet receiving time as backup is needed
I'm not skilled enough to understand your solution. Only in the classical recording method, I do not feel the time difference when the user leaves and then reconnects to the channel. Isn't this solved by your method?
Even if there are 10 seconds in between, the sound is combined instantly.
For example;
I connect and said hello. And then I left the channel and waited 5-6 seconds. Then I connected and said hello again.
But the recording is 2 seconds.
My solution solves the cases where new users join or start speaking a while later than when the recording started
Although i can think of a way 
What if i remove the user from the internal dict when he leaves
Will this make the user have two different records?
oh my god, my brain is exploding when I think about this and the possible solutions and the problems that may arise due to the solutions. I think I'll give up
I created a paginator and wanted to have the paginator accutalize the pages at a certain interval. For this I created an update function that loads the new pages and then the view should be updated. Unfortunately this does not work the way I did it. Does anyone have an idea and can help me how to do this?
class PaginatorInfoView(Paginator):
async def __new__(cls, *args, **kwargs):
obj = super().__new__(cls)
await obj.__init__(*args, **kwargs)
return obj
async def __init__(self, bot: discord.Bot):
self.bot = bot
self.pages = await self.update_pages()
view = await self.generate_view()
custom_buttons =[#Code for Buttons]
super().__init__(pages=self.pages, use_default_buttons=False, custom_buttons=custom_buttons, custom_view=view, timeout=None, author_check=False)
asyncio.ensure_future(self.update_loop())
async def update_pages(self):
data = await dab.get_all_spots()
pages = []
spots_per_page = 6
# Erstelle eine neue Seite
embed = discord.Embed(title="Spotübersicht")
.
.
#embed.set_footer(text=spot_text)
pages.append(embed)
# Entferne NULL-Elemente
return [p for p in pages if p is not None]
async def update_loop(self):
while True:
self.pages = await self.update_pages()
self.update()
print("Pages updated")
await asyncio.sleep(30)
async def generate_view(self):
view = SpotDetails(self.bot)
return view```
Yes possible
Oh wait
Hmm
Nope
.rtfm rtfm
Target not found, try again and make sure to check your spelling.
.rtfm deez
Target not found, try again and make sure to check your spelling.
pass help_command = None to the bot constructor
in main py?
yes
if i say nothing change? what to do?
bot = discord.Bot(intents=discord.Intents.all(), help_command=None)```
how remove?(
mport discord
from discord.ext import commands
class general(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.help_command = None
@discord.slash_command(name="help", description="Displays a list of available commands.")
async def help(self, ctx):
embed = discord.Embed(title="Help", description="Here's a list of my commands.", color=0x00ff00)
await ctx.respond(embed=embed)
def setup(bot):
bot.add_cog(general(bot))```
🙃
Well you have a help command. You could remove that.
self.help_command = None is just setting a instance varible. It will not change anything.
Is that your full cog. Can you also show where you create bot.
import discord
import os # default module
from dotenv import load_dotenv
from config import *
import mysql.connector
load_dotenv() # load all the variables from the env file
bot = discord.Bot(intents=discord.Intents.all())
conn = mysql.connector.connect(
host=DB_HOST,
port=DB_PORT,
database=DB_NAME,
user=DB_USER,
password=DB_PASSWORD
)
@bot.event
async def on_ready():
print(f"{bot.user} is ready and online!")
#bot.load_extension('cmd.utility.welcome')
bot.load_extension('cmd.mod.report')
#bot.load_extension('cmd.mod.timeout')
bot.load_extension('cmd.utility.welcome')
bot.load_extension('cmd.utility.general')
bot.load_extension('cmd.main.check')
#bot.load_extension('cmd.utility.test')
bot.run(TOKEN)```
And you do not have multiple bots running on the same token?
no
genaral cog
You are on the latest version of pycord?
checking
||that embed itself shows you have 5 help cmds somewhere||
@novel yacht did you already learn the basic´s of Python?
yea but in code only one msg
learing
But they cant all be slash commands becouse that would through errors.
Hi, how can I trace the button's custom_id parameter? For example, like: if view.custom_id = "for example":, is it workable? I'm subclassing the view.
Can you find all embeds with that green color? And see if any of them look like the second embed that is sent
You would have to get the custom_id of a item like button not the view.
Also generally custom ids are random and unique
I'm not sure how to do that
you already did it
really
button.custom_id when accessing in the callback
view.children
Returns a list of buttons.
So like view.children[0].custom_id
view should be an object btw
I mean if the user clicks the button Test, the value I will get is going to be test
As a way to see which button the user clicked
you just use button.label too ?
Is there anything such as view.action?
What do you want to do when the user clicks the button?
So I want to simply know which button the user clicked
And feed that information to another function outside the view class
interaction.message will give the message the button is attached to. Would that be enough?
Is that to be used inside the callback function?
can I do this instead, using self.action
If you're subclassing the view why not just also add the buttons there with their callbacks?
I'm going to need to load the the user's data from the database and use buttons to interact with these data. I'm at a loss about how to access data between callback functions without using global
So I think I'm should just see which button the user clicked and create an external function that handle the callback
So do you have a command that gets the data and sends the buttons?
Yes, all left is to find a way to know which button the user's clicked
That is what the callback is for. When the button is clicked the callback function is called.
So you can send the message with the data in the callback or similar.
I'm trying to interact with the same data between callbacks tho
Like this, but when I run the code it says 'int' object has no attribute 'value'
Can you show the full error
Is there a way to pull my "snowflake" then embed the photo within a command as a picture varible. Because right now I just have it hard coded in under author command. That has been interesting and reminded me I need to figure out a stop/shut command for the bot because I accidentally made mine into what is best described as a Daemon/zombie process but on windows. when I didn't have error handling. It used another completely unrelated comand though lol.
here it is
I have dyslexia and I know I chose like the worst thing to do for a career (programmer) so if it's in the docs is there anywhere that it would happen to be in a video series or someone would recommend? I get read the docs but I am the same guy who missed a .01 and could not figure out why it would work so feel free to call me dumb as you link/ dm a good playlist please?
Your style needs to be of this type not an int
https://docs.pycord.dev/en/master/api/enums.html#discord.ButtonStyle
The API provides some enumerations for certain types of strings to avoid the API from being stringly typed in case the strings change in the future. All enumerations are subclasses of an internal c...
I think what you want is
.rtfm discord.Bot.get_user
So I should fix style=primary in __init__ perhaps?
Style=discord.ButtonStyle.primary
So I have been getting this error for the past couple of days, and seems to be having it constantly. The error does not seem to reference any of my code, so I'm not sure how I could fix it in on my end, but regardless, I don't recall using webhooks in my bot
But sometimes, I get interaction never responded, even though I have ctx.defer() in the application command
Do you use ext.tasks? If so please post the code for the task and the after task code if any.
Well the error means you're trying to do something on something that doesn't exist. Like deleting a message that has already been deleted.
if you make a role using the bot, can you define the role position? in the hierarchy?
How do I get the users roles?
@team.command(description="Send a team invite via DM")
async def invite(ctx, member: discord.Member):
"""Team Member Invite Handler"""
requestedMember = await bot.fetch_user(member)
userRoles = discord.Member.roles(requestedMember)
await ctx.respond(f"{userRoles}") # Testing purposes
do you know basic python?
.rtfm create_role
Is there a way to get a user's server/display banner like with display_name and display_avatar?
display_avatar is already the guild avatar
banner isn't available on api
yo its ronny
is there a way to get all threads of a specific channel ? please ping when you reply
Hey, is there a way how to "Force Stop" select menu? My code is working just every time getting interaction failed even tho im getting selected option.
Are you not sending a response?
I am. Into another function
hey there quick, really basic question, how can I reply to a slash command with nothing? I have this slash command that sends a webhook, can't figure out how to close the slash command thing without it erroring out
You can't respond with nothing to a slash command, the best thing you can do is an ephemeral message saying "Webhook sent!" or something.
alright, thanks
Can someone help me how to make my paginator update every 10 minutes?
Unfortunately, my approach doesn't work that way.
class PaginatorInfoView(Paginator):
async def __new__(cls, *args, **kwargs):
obj = super().__new__(cls)
await obj.__init__(*args, **kwargs)
return obj
async def __init__(self, bot: discord.Bot):
self.bot = bot
self.pages = await self.update_pages()
view = await self.generate_view()
custom_buttons =[#Code for Buttons]
super().__init__(pages=self.pages, use_default_buttons=False, custom_buttons=custom_buttons, custom_view=view, timeout=None, author_check=False)
asyncio.ensure_future(self.update_loop())
async def update_pages(self):
data = await dab.get_all_spots()
pages = []
spots_per_page = 6
# Erstelle eine neue Seite
embed = discord.Embed(title="Spotübersicht")
.
.
#embed.set_footer(text=spot_text)
pages.append(embed)
# Entferne NULL-Elemente
return [p for p in pages if p is not None]
async def update_loop(self):
while True:
self.pages = await self.update_pages()
self.update()
print("Pages updated")
await asyncio.sleep(600)
async def generate_view(self):
view = SpotDetails(self.bot)
return view```
Hey! I'm trying to define a slash command with SlashCommandGroup and change its name. I wrote this still I'm getting the attached Slash Command. My code is working in a Cog
@reactionGroup.command(name='create')
async def reaction_add(self, interaction: discord.Interaction) -> None:
logging.info('hello world!')
pass
I've looked into some examples but couldn't find the solution. How can I achieve /reaction create command?
You can use await interaction.response.defer() so that there is no error. It's not the cleanest way but it works to avoid the "Interaction failed" error 🙂
It's still going to fail after 30 minutes
Ah okay I did not know yet 🙂
Do you know a solution to my Paginator problem?
You didn't explain your problem, all you said is that it doesn't work
My Paginator is not updated. I get the print that the pages have been updated but the Paginator still shows the old data.
I think that my async def update_loop(self): is not quite correct but I don't know how to do it right.
You need to edit the message with the updated view
I fixed it by removing the interaction parameter and adding a ctx variable.
So I'm only missing this line?
await self.message.edit(view=self)
yes
how do you remove specific buttons in a view from another message?
i made the view = discord.ui.View.from_message(message) work but how do i remove an item using their custom id from this point?
Okay thanks I will give it a try
Hello, i have a question, how to fetch kick
I know that guild have guild.fetch_ban, but have no guild.fetch_kick
So, how to fetch it?
Why would you need to fetch a kick?
audit logs is the only way i can think of
is the message sent by you? if yes then dont rely on from_message you lose out on custom ids and callbacks
The reason fetch_ban exists is to be able to fetch a BanEntry to then unban the user, there is no such thing as a KickEntry and you can't "unkick" a user so there's no reason for a fetch_kick to exist.
Audit logs are your best bet, unless you store a log of the kicks yourself
i'm doing it from the modal's callback so i could access the interaction.message but not the view so i used from_message
now i did
view.clear_items()
view.add_item() #to add the item i want to remain
it now works as intended but is there a better way? like using custom_id?
and what do you mean by lose out on custom_id and callbacks?
the View.from_message method uses message.components to create a view. message.components is sent by discord with message objects. these do not have custom ids or callbacks (not sure about custom ids)
this is why passing the view object around is much more preferable
you could pass the view to the modal init
so it's fine if i do clear_items then edit the message and add the views right?
yes but why not just create a new view object instead of view.clear_items
making another view will add a new view class and i just want to retain a single button
ohhhh wait i just understand what you meant 🤣
same problem though since my button is in a separate button class so clear item is the best way for me unless i want to make a new view with only a single button
anyone pls
discord.TextChannel
discord.TextChannel.archived_threads
discord.TextChannel.available_tags
discord.TextChannel.can_send
discord.TextChannel.category
discord.TextChannel.category_id
discord.TextChannel.changed_roles
discord.TextChannel.clone
discord.TextChannel.create_invite
discord.TextChannel.create_thread
discord.TextChannel.create_webhook
discord.TextChannel.created_at
discord.TextChannel.default_auto_archive_duration
discord.TextChannel.default_sort_order
discord.TextChannel.default_thread_slowmode_delay
discord.TextChannel.delete
discord.TextChannel.delete_messages
discord.TextChannel.edit
discord.TextChannel.fetch_message
discord.TextChannel.flags
yes i have
TextChannel does have a property threads
but does it also gives threads which the bot is not part of ?
like, the bot has administrator permissions (its for my own server)
but if someone creates a thread then bot is not actually a part of it, you cannot see it in members tab
so i am asking whether with TextChannel.threads, will the bot be able to access to all those threads ?
thanks
i believe you would need to use the thread events
.rtfm on_thread
ah, well i will use it now for future threads.
For older threads i have figured out a way by directly calling discord api with proper authorization, because i saw one or two endpoints of getting all threads whether public or private , archived or active. But ig there isnt any way to do so via pycord right ?
anyways much thanks
thanks i got it!
Oh wait if the bot has admin perms then it should be able to see those threads even it isn't a member of the thread
class WarnSystem(commands.Cog):
def __init__(self, bot):
self.bot = bot
@slash_command(name="warn", description="warn command", guild_ids=[guild_id])
async def warn(self, ctx : discord.ApplicationContext):
await ctx.respond(content="Yo ok", ephemeral=True)```
help :C
.tag idw
Saying it doesn't work or asking what's wrong with this code is not helpful for yourself or others.
Describe what you expect and/or tried (with your code), and what isn't going right.
Please provide any errors you get for optimal assistance.
@bot.event
async def on_ready():
bot.load_extension('cogs.warn_system')
print("Bot is now online!")
error:
discord.errors.ExtensionFailed: Extension 'cogs.warn_system' raised an error: ClientException: Callback for warn command is missing "context" parameter.
aiofiles 23.1.0
aiohttp 3.8.4
aiosignal 1.2.0
aiosqlite 0.18.0
anyio 3.6.2
async-generator 1.10
Async-OAuthlib 0.0.9
async-timeout 4.0.2
attrs 22.1.0
autopep8 2.0.0
blinker 1.5
cachetools 5.3.0
certifi 2022.12.7
cffi 1.15.1
chardet 4.0.0
charset-normalizer 2.1.1
chat-exporter 2.5.3
click 8.1.3
colorama 0.4.6
dnspython 2.3.0
emoji 2.2.0
ffmpeg-python 0.2.0
Flask 2.2.3
frozenlist 1.3.1
future 0.18.2
grapheme 0.6.0
h11 0.14.0
h2 4.1.0
hpack 4.0.0
httpcore 0.16.3
httpx 0.23.3
hypercorn 0.14.3
hyperframe 6.0.1
idna 3.4
imageio-ffmpeg 0.4.7
itsdangerous 2.1.2
Jinja2 3.1.2
MarkupSafe 2.1.2
motor 3.1.1
multidict 6.0.2
numpy 1.23.4
oauthlib 3.2.2
openai 0.26.5
outcome 1.2.0
Pillow 9.4.0
pip 22.3.1
priority 2.0.0
py-cord 2.4.0
pycodestyle 2.9.1
pycparser 2.21
PyJWT 2.6.0
pymongo 4.3.3
PySocks 1.7.1
python-dateutil 2.8.2
python-dotenv 1.0.0
pytz 2022.7.1
Quart-Discord-any 2.2.2b1
requests 2.28.2
rfc3986 1.5.0
roblox 2.0.0
setuptools 65.5.0
six 1.16.0
sniffio 1.3.0
sortedcontainers 2.4.0
toml 0.10.2
tomli 2.0.1
tqdm 4.64.1
trio 0.22.0
trio-websocket 0.9.2
typing_extensions 4.5.0
urllib3 1.26.14
websockets 10.4
Werkzeug 2.2.3
wsproto 1.2.0
yarl 1.8.1```
then
Anywhere before bot.run
Like
bot = ...
...
bot.load_extension(...)
bot.run(...)
Rip lol
||you have it here tho||
oh thanks works now
that is why i got this error
removed it after sending that message
me dumb
I have been coding in python for over a year or two
The time you've been coding doesn't matter at all, it's about your skill level
Im asking because you fetch the user again but you already got the user
So then how would I get the users roles?
Why are you fetching the user in the first place? You already have a member object
Or does this do it? (to get users roles)
@team.command(description="Send a team invite via DM")
async def invite(ctx, member: discord.Member):
"""Team Member Invite Handler"""
userRoles = discord.Member.roles(member)
await ctx.respond(f"{userRoles}") # testing
member.roles where member is an object of the class discord.Member
You need to know OOP before using pycord
what are debug_guilds? in slash commands
Sorry to ask, but whats OOP
Exactly
._.
object oriented programming
ah ok
can someone help me with this?
i am using guild_ids for now but what are debug_guilds?
You don't specify debug_guilds in a slash command, you pass it to your bot's init to automatically pass guild_ids to all your slash commands
.rtfm debug_guilds
Target not found, try again and make sure to check your spelling.
.rtfm Bot.debug_guilds
Target not found, try again and make sure to check your spelling.
k
it's under slash commands i guess
alright, but what does it do? do i need to use it if i am using this command to test
kk
I've got a bot that's near to the point where I will be forced to shard. According to https://guide.pycord.dev/popular-topics/sharding/#what-is-sharding, all I need to do is change my bot class to AutoShardedBot, which sounds great!
However, I'm seeing another dev (d.js in this case) saying he had to completely rewrite his bot to account for sharding, which has me a little worried.
Are there any special caveats/pitfalls I need to beware when sharding?
Why take into account what someone that uses d.js said when you're using py-cord?
And the guide, just like you said, tells you to just change the instance
in the case you mentioned, at a very large scale you would inevitably have to rewrite code for sharding/clustering regardless of the library
but using the built in sharding tools you shouldn't need to
Can someone explain to me how to get my Paginator persistens?
Unfortunately it does not work with the on_ready method. I don't get an error message, the print is also printed but the paginator still doesn't work after a bot restart.
Can someone explain me what I do wrong or how I get my Paginator persistent?
class Base(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.persistent_views_added = False
@commands.Cog.listener()
async def on_ready(self):
if not self.persistent_views_added:
self.bot.add_view(await PaginatorInfoView(self.bot))
self.bot.add_view(SpotDetails(self.bot))
print("Views added")
self.persistent_views_added = True
@commands.command(name="showspot", help="Zeigt alle Spots an")
async def page(self, ctx):
paginator = await PaginatorInfoView(self.bot)
await paginator.send(ctx)
Can you give an example of something that might have to be rewritten at that scale, even at just a high level concept? The guide suggests you don't have to rewrite anything at all
well you'd mainly have to reduce api calls and structure other stuff to work around multiple connections, or even multiple servers/machines if you're at that large a scale
but you wouldn't need this until you hit like, 10s of thousands of guilds or so
sharding alone should be fine for a few thousand
Cool, thanks
I wasn't sure if I'd need to rewrite my database cache, for instance. It doesn't seem like I would, since it's keyed off of guilds and guilds are isolated to shards, but that's why I asked if there are any obvious pitfalls
heck, clustering is only possible at 150k guilds probably way less, but point being you shouldn't need to worry
Unlikely I'll ever get that big. The community I'm serving is small
I know that discord implemented a thing where you can send timedate that is displayed in local time zone. Does pycord implement that and if so what is it named or where in docs can I find it?
<t:1664318247:t>
<t:1664318247:T>
<t:1664318247:d>
<t:1664318247:D>
<t:1664318247:f>
<t:1664318247:F>
<t:1664318247:R>
<t:1664318247:t>
<t:1664318247:T>
<t:1664318247:d>
<t:1664318247:D>
<t:1664318247:f>
<t:1664318247:F>
<t:1664318247:R>
API Reference: https://github.com/discord/discord-api-docs/blob/ff4d9d8ea6493405a8823492338880c47fb02996/docs/Reference.md#timestamp-styles
See discord.utils.format_dt for the discord.py implementation.
https://docs.pycord.dev/en/stable/api.html#discord.utils.format_dt
@iron mesa 
Thank you!
Is there any method to call when a user is in the server for X days?
or any other ways technically
can you elaborate? do you want to do something when lets say 5 days have passed since the user has joined?
There are a few ways, the way I'd probably do it is to set up an event handler for member joins and add the member to a database table along with the current datetime. Then set up a task that runs every 24 hours and compares the join date with the current date.
That way you can only store the members you actually want to track. As opposed to iterating through all members of all servers.
Hey guys, i would like to ask what is the best format for make a config file in python, i tried yaml but it doesnt really convince me
Json?
I dont really like the syntax of it as some people that doesnt know anything about coding would probably have some problems using it
mhm, what is with InI or XML
I will try .ini ty
yaml, json/hocon and ini are probably your best options. Otherwise you'll have to move onto making some sort of graphical configuration interface like a website or another python program that asks the user for values. Depends on how "non-coder" friendly you want to make it.
Can I not use a local image as a thumbnail in the embed?
The thumbnail is not set but the image is sent large above the embed 🤔
file = discord.File(f"./Fische/{fisch}.png", filename=f"{fisch}.png")
embed.set_thumbnail(url=f'attachment://{fisch}.png')
interaction.response.send_message(embed=embed, File=file)
first the file and then the embed
The image is still packed large above the embed instead of as a thumbnail 😬
Use \:Emoji Name: in a channel and copy it to your code
Thank you, it works !
f small in the kwarg name
file=file
Also the local file only works for the main image iirc
Okay then I can't set the locale file as thumbnail?
i believe no
.tias
If I send it as a normal embed then it goes into the thumbnail but in my paginator somehow not 🤔
Do I need to pass the embeds and files as a list with my Paginator?
pages.append(page)```
.rtfm edit_role_positions
You can use it in your Bot's class too, instead of having to add it to every single command... Just thought you'd wanna know :P
bot = discord.Bot(intents = intents, debug_guilds = """This is basically where you put the ID or multiple ID's""")
Hey there, im trying to use an emoji in a button but it throws Invalid emoji error. This is my code
button = Button(label=f"{ticketpanelconf['button_text']}", style=discord.ButtonStyle.green, emoji=f":{ticketpanelconf['button_emoji']}:")
and this is the data of button_emoji:
button_emoji: incoming_envelope
Anybody knows how to fix it? The format of the emoji looks good to me
where are the <>?
The format for the discord emoji isnt :emoji_name:?
is it a discord or custom one?
discord
📨 this one
really struggling with this thing i dont know why it doesnt work
\📨
Copy and paste this.
If you type out the emoji and put a \ in front of it. This will give you the raw unicode so that it will work in a python string instead of discords overlay. Than when sent, discord will overlay with there again.
Hey guys how would I read the contents of a message? like I basically want to do
@bot.slash_command(name = "read", description = "read message back to user")
async def info(message):
await ctx.respond(message.content)
why so you send a empty message?
No
also where is the ctx?
I have a private bot testing server and want to try parsing my own address then passing it to an api and returning the date and time the ISS can be seen from my house
I could not get ctx to return the content of my message
Do you know basic python?
I'm asking because you have "ctx.respond" without the ctx in the function
async def info(ctx, message):
await ctx.respond(message)
It didn't work
Error?
@bot.slash_command(name = "info", description = "for debugging")
async def info(ctx, message):
await ctx.respond(message)
None
do you have anything else installed than py-cord?
no
do you use discord.Bot?
before or after you installed py-cord?
I forget, it was a while ago
what is the py-cord version?
2.4.1
anything else than discord.py?
does work? ```py
@bot.slash_command(name = "info", description = "for debugging")
async def info(ctx):
await ctx.respond("test")
can you uninstall and reinstall py-cord?
does the bot has the permissions to send messages?
Yes
it has full admin permissions on my server and all intents enabled
Wait, I got it to work. I had a hello command that did basically the same thing so I copied it and replaced the name, description, and response fields and now it works?
Like the uninstall reinstall did not work but this did
mhm
^^
you may be looking for Message Commands
Here's the context menus example.
Learn all about Context Menus (User Commands & Message Commands) and how to implement them into your Discord Bot with Pycord!
I'll take a look, ultimately the response chain should be deleting the message if it's not a DM and then DM'ing the info back to the user for the ISS flyby
then you may be looking for the on_message event.
.rtfm on_message
can I combine this with the slash commands?
what do you mean?
@bot.slash_command(name = "info", description = "for debugging")
async def on_message(ctx, message):
await ctx.respond(message)
how do you restrict visibility of slash commands to a certain role?
i had the code earlier but i deleted it
?tag xq
No tag xq found.
?tag xy
An XY problem is when you're trying to ask about your attempted solution, rather than your actual problem.
You are trying to solve problem X, using solution Y. Instead of asking for help with X, you ask about Y. This only results in frustration as whoever is trying to help you needs to ask several questions before even beginning to help you with your actual issue, wasting both their own, and your time. Always include as much information as you can about your problem, including attempted solutions. If there are solutions you've ruled out, include them along with an explanation as to why you've ruled them out.
.rtfm default_permission
No
What do you want to happen?
I am asking if I can have the on message function nested under the slash command decorator so that I don't have to parse out manually the beginning of a command by doing something like `startswith("!flyover")
Basically I want to be able to type
/Flyover address
So that the message content only contains the address
I'm not sure if you understand what a message is and the difference between that of a slash command argument
that doesnt do role though?
you cannot restrict the visibility of a slash command by role through a bot
oh
i can prevent people from using it tho?
however, you can add internal checks, but other users without the role can still see it
.rtfm commands.has_role
ok thanks
Hello!
With this channel: discord.Option(discord.TextChannel, required=True) channels of type Announcement are not displayed. Any idea how to list only these channels?
.rtfm option.channel_types
Target not found, try again and make sure to check your spelling.
Something like this?
channel: discord.Option(discord.ChannelType.news, required=True)
No I have an error. :/
channel: discord.Option(input_type=discord.ChannelType.news, required=True)
no, something like
discord.Option(discord.TextChannel, channel_types = [discord.ChannelType....], ...)
Ok thanks!
Learn all about implementing Select Menus or Dropdowns in your Discord Bot with Pycord.
so is this where i put my code
im making a subscription plan dropdown
Yes, and I also recommend reading for more info
if i just leave this in a channel, will it expire or something? or will users be able to keep using it
views will no longer be functional after restart.
see
Here's the persistent example.
for how to make views persist through restarts
oh ok thanks
do u happen to have an example that doesnt use a class for the bot?
bot = discord.Bot(intents=intents)
im using this instead of a class
you just have to adapt it.
bot = ...
bot.persistent_views_added = False
@bot.event
async def on_ready():
if not bot.persistent_views_added:
# add the view
# set to true
...
i was getting this when i tried to adapt it thts why i asked
yeah because the Pythonic way would be to inherit/extend it
ValueError: View is not persistent. Items need to have a custom_id set and View must have no timeout
is this bc i didnt do the perisitent views added?
no because the reason for the error is given in the error itself.
send code for the view you are trying to make persistent
class PlanView(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
@discord.ui.select(
row=1,
options=plan_options,
placeholder="Choose a plan",
)
async def select_callback(self, select, interaction):
chosen_plan = next((plan for plan in plans if plan["stripe_price_id"] == select.values[0]), None)
if chosen_plan:
await interaction.response.send_message(f"You've chosen the {chosen_plan['name']} plan.")
else:
await interaction.response.send_message("Something went wrong. Please try again.")```
this?
plan_options = [
discord.SelectOption(label=plan["name"], value=plan["stripe_price_id"])
for plan in plans
]```
yeah your select menu doesn't have a custom_id
sry where do i add that?
is it per option or for the whole thing?
@discord.ui.select(
row=1,
options=plan_options,
placeholder="Choose a plan",
+ custom_id = ...
)
some string with a 30 (I think) character limit
ty it worked
ugh i decided to do a form instead based on member feedback so thats gonna be fun now
.rtfm modal
discord.ui.Modal
discord.ui.Modal.add_item
discord.ui.Modal.callback
discord.ui.Modal.children
discord.ui.Modal.custom_id
discord.ui.Modal.on_error
discord.ui.Modal.on_timeout
discord.ui.Modal.remove_item
discord.ui.Modal.stop
discord.ui.Modal.title
discord.ui.Modal.to_components
discord.ui.Modal.to_dict
discord.ui.Modal.wait
discord.InteractionType.modal_submit
discord.ApplicationContext.send_modal
discord.InteractionResponse.send_modal
discord.InteractionResponseType.modal
discord.ext.bridge.BridgeApplicationContext.send_modal
no
Hey, when doing options with slash command, integer-only ones don't accept server IDs like 996922553266360360. Any thoughts why?
Is it viable to just make them integers in the code?
Because discord doesn't support numbers that large, you need to take a string and parse it in your code
Okey, thanks
is there a way to count how many messages one user sent in a server? or do i need to recursively search in every channel for the last 9 million messages and see how many match the user?
Is it possible to write such a code that the button turns off at a certain time.
i believe you are interested in timeouts
.rtfm view.on_timeout
subclass and override that
disable the button you want in the view, and edit the msg
nope. no easy way. gotta go through the entire history of all the channels in the server
there is not recursion in this tbh...
simple plain looping
yeah that's what i was talking about, iterate i think is the word i was looking for
weird how that's not possible, since a normal user can just search messages from x and it spits out the whole history
Hi
It this possible? I want to make sure before I try making it
a persistent view with a drop down of 3 items
If user chooses item it’ll show two buttons
If user chose a button it will run my code
However when you press the button I need the value of the item they chose in the dropdown
yes
Okay and I can do it ephemeral?
yes
discord doesnt offer that to bots unfortunately
boowomp
So libraries implemented their own version of it
.rtfm view.timeout
Target not found, try again and make sure to check your spelling.
history is available to bot api iirc. search isnt
It is a valid argument: https://docs.pycord.dev/en/master/api/ui_kit.html#discord.ui.View.timeout
The library has helpers to help create component-based UIs. Shortcut decorators: Objects: Attributes children, disable_on_timeout, message, timeout. Methods cls View.from_message, def add_item, def...
oh yeah just set disable_on_timeout to True and set timeout as the number of seconds after which the buttons should be disabled
Guys i have a view in a subclass and then a slash commands that should use the view of that class, but when i try to define the view with view=PanelView() it says its undefined. Any idea?
is the class in the same file as the slash cmd?
also full traceback please
also are you using the correct version of the file? ||and did you save the file 💀 ||
Yes they're in the same file and also i saved the file.
Ignoring exception in command ticketpanel:
Traceback (most recent call last):
File "C:\Users\Federico\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\commands\core.py", line 113, in wrapped
ret = await coro(arg)
File "C:\Users\Federico\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\commands\core.py", line 766, in _invoke
await self.callback(ctx, **kwargs)
File "c:\Users\Federico\Desktop\TicketBot\bot.py", line 152, in ticketpanel
await channel.send(embed=embed, view=PanelView())
NameError: name 'PanelView' is not defined
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Federico\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\bot.py", line 755, in process_application_commands
await ctx.command.invoke(ctx)
File "C:\Users\Federico\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\commands\core.py", line 312, in invoke
await injected(ctx)
File "C:\Users\Federico\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\commands\core.py", line 119, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.commands.errors.ApplicationCommandInvokeError: Application Command raised an exception: NameError: name 'PanelView' is not defined
You want the code?
Idk
yes was gonna say just that 😂
you dont use ctx.respond in a slash command?
also view = Menu()?
The indentation is off. In order to use the view, the class has to be in the global scope.
Oh im dumb didnt notice it, sorry
just another view class
Thanks to all of you, i fixed it.
Hey, you can make SlashCommandGroups. If I now create a group with e.g. "test", is there a possibility to use only the /test? And then /test 1, 2 etc. as well.?
Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - pycord/slash_cog_groups.py at master · Pycord-Development/pycord
Sure, but there is only /greetings (hello, aloha), and I would like to be able to do only /greetings if possible.
not possible. discord limitation
it is because of the fact that subgroups are technically just option choices of the parent command
discord clients just render them differently
Ah okay, all right. thx 😄
bot.get_channel(123) also works for categories, right?
Yes
thx
If an embed raw has the "contents" value, will it also be added as a message while using from_dict or will be ignored?
embeds don't have content. Messages have content
The function input bot on __init__ in a commands.Cog cog is the type of commands.Bot yes?
it can be whatever you want it to be
when loading from bot.load_extension("cogs/cog")?
yes
iirc it is only there for you to access the bot object
yeah
I am genuinely confused,
file = discord.File(f"assets/gifs/no.gif", filename=f"no.gif")
em = discord.Embed(title="Error!", description="Why would I do that?.", color=em_red)
em.set_image(url="attachment://no.gif")
await ctx.respond(file = file, embed=em)
So for some reason, I cannot add images (gifs) to my embed, otherwise it will give me the error code :
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction
code for the command?
# Mute
@commands.has_permissions(moderate_members = True)
@discord.slash_command(name = "mute", description = "Mutes a member.")
@option("user", discord.Member, description="Choose a member.",)
@option("reason", description="Reason for the user to be muted.", default="No reason provided", required=False)
@option("days", description="Time for the user to be muted in days (optional).", required=False, default=0)
@option("hours", description="Time for the user to be muted in hours (optional).", required=False, default=0)
@option("minutes", description="Time for the user to be muted in minutes (optional).", required=False, default=0)
@option("seconds", description="Time for the user to be muted in seconds (optional).", required=False, default=0)
async def mute(self, ctx, user: discord.Member, reason: str, days: int, hours: int, minutes: int, seconds: int):
unix_time = int(time.time())
try:
duration = timedelta(days = days, hours = hours, minutes = minutes, seconds = seconds)
except OverflowError:
file = discord.File(f"assets/gifs/no.gif", filename=f"no.gif")
em = discord.Embed(title="Error!", description="Why would I do that?.", color=em_red)
em.set_image(url="attachment://no.gif")
await ctx.respond(file = file, embed=em)
return
user_role = discord.utils.get(user.roles, name='Muted')
mute_role = discord.utils.get(ctx.guild.roles, name="Muted")
if user.id == ctx.author.id:
em = discord.Embed(title = "Error!", description = "You can't mute yourself, " + random.choice(insult), color = em_red)
await ctx.respond(embed = em, ephemeral = True)
return
...
its a mute command, but yeah the rest should be pretty irrelevant
just ping me if you have a solution ig
It's taking longer than 3 seconds to respond. Consider using ctx.defer.
oh- that'd make sense lol didn't think of it. thanks
plan_options = [
discord.SelectOption(label=plan["name"], value=plan["stripe_price_id"])
for plan in plans
]
# create a view for a dropdown for each plan in plans.yml
class PlanViewTest(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
@discord.ui.select(
row=1,
options=plan_options,
placeholder="Choose a plan",
)
async def select_callback(self, select, interaction):
chosen_plan = next((plan for plan in plans if plan["stripe_price_id"] == select.values[0]), None)
if chosen_plan:
await interaction.response.send_message(f"You've chosen the {chosen_plan['name']} plan.")
else:
await interaction.response.send_message("Something went wrong. Please try again.")
im super confused with this, how do i make it so i can send code for each of the different options?
basically i need to have a changeable amount of options (plans that the user configures) so i have to use a for loop?
Here's the dropdown example.
i get that, but i need to have it scale for however many plans the user configures @silver moat
the example defines a set amount of plans
maybe i should say the end goal
a dropdown which spawns two buttons (one for one time payment and another for subscription), that button will open a modal asking for the users email, then it replies with a invoice link
but the invoice needs to know what plan to charge the user for
imo this seems very insecure over a discord bot. Consider using a website with stripe instead.
hows it insecure?
i currently use a paid solution which uses a website but i want my own via a bot
payments are processed via a stripe invoice
api key is restricted in permissions
well, I think it looks suspicious. Mostly because Discord Bots have been known to be involved with scams and such
i have a good reputation in the community i sell in, hundreds of reviews
but ye i get what you're saying
i dont believe its against discord tos as other popular payment bots exist
well, you have the selected option(s) what else do you need?
well i need to create a two buttons after the user choses (which i can do)
then make a modal
i get that part
however i dont know how to then fetch what plan they chose after they submit email via modal
without manually setting up each option in the dropdown, which i cant do because i need to loop through all the user's plans
just pass it as an argument through?
how do i do that?
plan_options = [
discord.SelectOption(label=plan["name"], value=plan["stripe_price_id"])
for plan in plans
]
# create a view for a dropdown for each plan in plans.yml
class PlanViewTest(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
@discord.ui.select(
row=1,
options=plan_options,
placeholder="Choose a plan",
)
async def select_callback(self, select, interaction):
chosen_plan = next((plan for plan in plans if plan["stripe_price_id"] == select.values[0]), None)
if chosen_plan:
await interaction.response.send_message(f"You've chosen the {chosen_plan['name']} plan.")
else:
await interaction.response.send_message("Something went wrong. Please try again.")
#make a slash command to spawn the PlanViewTest```
i dont see where i could put the arguement in the for loop
sry im not that good with python
this took me like 8 hours to make
Do you know basic Python OOP?
Extending a class is a basic OOP concept.
Pycord is an advanced python library. You should have a solid understanding of fundamentals before starting to integrate with pycord.
ok
.rtfm modal
discord.ui.Modal
discord.ui.Modal.add_item
discord.ui.Modal.callback
discord.ui.Modal.children
discord.ui.Modal.custom_id
discord.ui.Modal.on_error
discord.ui.Modal.on_timeout
discord.ui.Modal.remove_item
discord.ui.Modal.stop
discord.ui.Modal.title
discord.ui.Modal.to_components
discord.ui.Modal.to_dict
discord.ui.Modal.wait
discord.InteractionType.modal_submit
discord.ApplicationContext.send_modal
discord.InteractionResponse.send_modal
discord.InteractionResponseType.modal
discord.ext.bridge.BridgeApplicationContext.send_modal
I'm having an issue when trying to host my bot that I actually ran into a few weeks ago.
I am getting:
"ImportError: cannot import name 'option' from 'discord' (/usr/local/lib/python3.10/dist-packages/discord/init.py)"
I have py-cord 2.4.0 installed, and my code is working just fine on my windows system, but it is getting hung up in my ubuntu system. I did a normal pip freeze, ported reqs, and now have encountered this issue.
Any clue what might cause this? Before, the problem was that my py-cord lib needed an update, but that's not the case here
Hello!
I have a small question.
From a list of ID I get a list of channels.
I then try to do an auto completion but impossible to propose a custom channel list, any idea?
I am forced to give a list of channel names and retrieve the channel a second time, with the risk that the name is duplicated.
do you have any other discord related library like dpy etc? uninstall that
also uninstall py-cord and reinstall it
see if that helps
you can return OptionChoice in the autocomplete
set the name as channel name and value as the id
.rtfm optionchoice
I hadn't thought of that, it's a good idea! Thanks
Yep yep! Looks like I discord.py crept into my req doc somehow...thank you for always helping, NomNom
sorry, why does the footer is not mentioned? I did set the footer's text to
"By: {ctx.author.mention}"
how can i make slash commands limited to certain roles
.rtfm has_role
doesn't seem to work
@warn_class.command(name="view", description="Shows all the warns for a specified user", guild_ids=[guild_id])
@commands.has_role(1088420607877730314)
@discord.option(name="member", type=discord.SlashCommandOptionType.user, description="The member to view warns for", required=False)
async def view(self, ctx : discord.ApplicationContext, member):```
@proud mason
no error
i want it so it only shows up for certain people
i could do it in js but not in py.. why?
That is not possible for roles
Only for permissions
discord.default_permissions
Ik, but what if I pass this raw?
{
"content": "Hello!",
"embeds": [
{
"title": "hi",
"description": "dasda",
"color": null
}
],
"attachments": []
}```
should i use bot.dispatch? is it good to use it?
Why would you?
i can assure you there are better way to implement your features than using bot.dispatch 98% of the times
I am trying to make an on_warn event
to make it organized
instead going on each command and doing stuff there
so what would you suggest?
Can't you just call the on_warn method in those places?
has somebody a list of discord code block colors?
what?
there is not a list of code block colors
google it ;3
Those are markdown syntax colors
Has nothing to do with Discord, and you can't control them
And there isn't a "list" of colors, the colors are decided by the syntax highlighting of the language you're writing in
hey i was wondering, is there a way to mock and an interaction, like for example button press interaction, lets say i have a button and if the user does not press it in 20 seconds the bot can press it as it was the user who pressed it
em = discord.Embed(title = 'Test Embed!', description = 'Hell yeah', color = em_green) # em_green is a variable to hex color and works fine.
em.set_author(name=self.bot.user.name, # The Bot's Name (works fine, self because this embed is in a cog.)
url='https://google.com', # Here this is my issue, the Author name above, should become clickable in the embed, but for some reason it just doesn't
icon_url=self.bot.user.display_avatar.url) # The Bot's Avatar (works fine too, self because this embed is in a cog.)
What am I doing wrong with my url='https://google.com'
I mean https://google.com is a valid Url... so I am really confused here, docs say I can include url too soo... Yeah. I have no idea what I am doing wrong.
Search the world's information, including webpages, images, videos and more. Google has many special features to help you find exactly what you're looking for.
Oh my god I am an idiot. I made 2 embeds and it took the first one 
No more help needed 
Well i can think of a way. Although how will you determine which user was going to press it?
Unless the callback is user indifferent
well as of the moment let's say that i know 100% who is supposed to press it
it's some sort of turn based "game"
i just want to add a time for the turn, so the player doesnt intentionally make others wait
If what you want to do it do stuff when button is pressed or 20s have passed and button not pressed, then what i was thinking is
For normal button press, call another function from the button and pass interaction.
For timeout,
Set view timeout to 20s. In the on_timeout method of the view, create any object (even object()) that has the parameters you would use from Interaction and then pass that to the function you would call from normal button press
Since python uses duck typing, the actual class won't matter
Oh if you want to do different actions when button is pressed or timeout, just use on_timeout
No need for this then
oh, didnt know that was a thing, thanks 😄 i guess i shouldve looked more into the docs 😄
slash commands doesnt load. it loads in the first cog the main.py file loads but not the others
cogs = [
"cogs.moderation_settings", #this cog has one command (and it works)
"cogs.warn_system"]# this cog has 4 commands (doesnt load)
for filename in cogs:
bot.load_extension(filename)```
.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)?
nothing works 
and what do you mean by on_connect overriden
its not like all my commands are not loading its just that one cog
class ModSettings(commands.Cog):
def __init__(self, bot : discord.Bot):
self.bot = bot
modsettings_class = discord.SlashCommandGroup(name="modsettings", description="Everything related to moderation settings. Can only be set up by admins.", guild_ids=[guild_id])
@modsettings_class.command(name="mod", description="Edit moderator roles", guild_ids=[guild_id])
@discord.option(name="action", description="Choose actions to do moderator roles" ,autocomplete=["add", "view", "remove"])
@discord.option(name="role", description="Role to do actions for. There is no need of this field if using the action \"view\"." ,autocomplete=modactions)
async def mod(self, ctx, role):
#code
def setup(bot):
bot.add_cog(ModSettings(bot))```
cog 2
do you have an on_connect ?
nope on _ready
import discord
from discord.ext import commands
import os
from dotenv import load_dotenv
import time
import aiosqlite
from discord.ext import tasks
load_dotenv()
TOKEN = os.getenv("DISCORD_BOT_TOKEN")
guild_id = os.getenv("GUILD_ID")
intents = discord.Intents.all()
bot = commands.Bot(command_prefix="!", intents=intents, case_insensitive=True, debug_guild=guild_id)
bot.remove_command('help')
cogs = ["cogs.auto_actions",
"cogs.moderation_settings",
"cogs.warn_system"]
@bot.event
async def on_ready():
print("Bot is now online!")
for filename in cogs:
bot.load_extension(filename)```
I’m assuming modactions is defined
are you on the newest pycord version
class WarnSystem(commands.Cog):
def __init__(self, bot):
self.bot = bot
warn_class = discord.SlashCommandGroup(name="warn", description="Everything related to... warns.", guild_ids=[guild_id])
@warn_class.command(name="add", description="Warns a specified user", guild_ids=[guild_id])
@discord.option(name="member", type=discord.SlashCommandOptionType.user, description="The member to warn")
@discord.option(name="reason", type=str, description="Reason to warn the user", required=False, min_length=1, max_length=300)
async def add(self, ctx : discord.ApplicationContext, member, reason : str=None):
pass
@warn_class.command(name="remove", description="Removes a warn for the specified user", guild_ids=[guild_id])
@discord.option(name="member", type=discord.SlashCommandOptionType.user, description="The member to remove a warn for")
@discord.option(name="warn id", type=discord.SlashCommandOptionType.integer, description="The warn to remove")
@commands.has_permissions(administrator=True)
async def remove(self, ctx : discord.ApplicationContext, member, warnid):
pass
@warn_class.command(name="view", description="Shows all the warns for a specified user", guild_ids=[guild_id])
@discord.option(name="member", type=discord.SlashCommandOptionType.user, description="The member to view warns for", required=False)
async def view(self, ctx : discord.ApplicationContext, member):
pass
@warn_class.command(name="clear", description="Clear all the warns for a specified user", guild_ids=[guild_id])
@discord.option(name="member", type=discord.SlashCommandOptionType.user, description="The member to clear warns for", required=False)
async def clear(self, ctx : discord.ApplicationContext, member):
pass
def setup(bot):
bot.add_cog(WarnSystem(bot))```
because debug_guild was removed way before alpha 1
I’m not sure what autocomplete = [“add”, “view”, “remove”] does
oh hum
autocomplete takes a coroutine with an argument of AutocompleteContext
Here's the buttons example.
bruh
Here's the confirm example.
