#General Help
1 messages · Page 24 of 1
hmm
still offline
u have free dyno hours ?
i said hours
Um what?
how to see
In ur account billing
Show me ur files
Check logs
Hm this might be because messages can only have one view at a time
But I don't see why that would affect anything
Use heroku --tail
How buttons interactions and so on works in pycord including method override
Oh okay
So you have any other way to add multiple button in a message? For button because when i restart my bot it automatically work
All buttons
Ok alr don't worry I'll find it
Um alright
Also BTW the indentation for the statements under the for loop is invalid
I just trying the for loop it's unnecessary
And I'm on mobile so it discord glitch
Don't worry
I'll manage
Alrighty then
@drifting spindle
I already said use heroku --tail to view the logs
i type heroku --tail
Hello everyone
How can i fix it?
File "/Volumes/Danya disk/Windows Hall/Programer/Py-cord/KeyBot/bot.py", line 104, in <module>
async def addm(ctx, user: Option(str, discord.Member, name="участник", description="Участник сервера", required=True),
TypeError: Option.__init__() got multiple values for argument 'description'```
Is there a way to see how many boosts a user currently has?
No, I don't think so
You can check if they have boosted the server, but not how many times
You can't provide name and desc in Option
Name is already set by user:
So you can remove the name arg
Then it work
Thanks
Now give me 100$ for helping
i need to give you 5 365 rubles
Why but ?
100$ = 5365₽
Yeah you're not getting paid for helping someone here
There are difference between serious & joke
Read to know
Yes pay me
🙂 i need to go to bank
i'm lazy
Am I able to further tighten rules for slash commands. For example use regex or start with.
I am talking about:
quert: Option(str, 'Pass your query', required=True)
And lets say only accept max 20 chars
ш вщтэн тщц
Wdym ?
i don't now
I mean that I for example set the query to be max 20 chars. or starts with a or use of regex
I know I can filter it after the query but I am wondering if I can do it before that already
Can someone help me with this error, all I am trying to do is upload a local file into the embed
You can use @option
Don't do like this just specify the path directly on embed image component which supports image
Alright
Yes
I still can't figure how to put in a local image in the embed
in the thumbnail field
How ? Show me how you doing
Yes please wait
Ok
do you mind showing me an example? looked into it but was not able to find a solution.
😊
Here's the slash options example.
@zinc saffron

remove c:
didn;t work
Yes I am
it is for url argument, i tried putting that
and it shows the sceme has to be an https or http
and it still doesn't work
that's why I was trying the file method earlier
So concert it with a url
Simple
can someone help? i cant play music on my bot
@drifting spindle can you help me again?
this is from heroku log
or i need database for music bot?
Stick to english! #rules
i wrote in english, but russian keyboard was turned on
Then edit the message? We all make mistakes
oh lol 🤣
local variable 'voice_client' referenced before assignment
can someone help?
async def play (ctx):
try:
voice_client = await ctx.author.voice.channel.connect()
voice_clients[voice_client.guild.id] = voice_client
except:
print("error")
try:
url = ctx.message.content.split()[1]
loop = asyncio.get_event_loop()
data = await loop.run_in_executor(None, lambda: ytdl.extract_info(url, download=False))
song = data['url']
player = discord.FFmpegPCMAudio(song, **ffmpeg_options)
voice_client.play(player)
await ctx.reply(f"Playing {url}", mention_author=True)
except Exception as err:
print(err)```
this is the code
Error is kinda self explanatory
"Voice_client" referenced before assignment
i am trying to add a embed to a message, but this does not seem to work for some reason
await interaction.message.edit(embeds=[interaction.message.embeds[0], embed], view=self)
only the old embed is showing up, the new one is not added
How to show slash commands only to certatin roles
You cant really do that yet
You can use has_role or some logic (check if user has X role) to limit the cmd running when the command has been invoked
Could be wrong but you cant rly do the embeds=[] thing. maybe try setting it as embed=embed or just change view
ok so if i wanted to do something like update to db before the bot goes down, would i have to use on_disconnect event?
Whenever u help just ping me I'm not like others who will be rude on ping
didnt i asked that?
i wonder will this event called when the bot explicitly closed
sori i cant test rn
Did i asked?
No one asked you why you saying anything which never make any sense
Really non sense peoples are their
uhh ?
May I ask what the structure of a complete bot file will be like?
Umm there are so many type of structure like
If you make a very normal bot then it will be only main.py
If you make a bot which do some particular stuff ex. only economy then it will have one main.py 1 cogs folder and in the cogs folder 1 economy folder then 1 utils folder for views, modals, select menu subclasses
And i guess you got a idea
If not
It depends on you, You have freedom to make any files structure
It won't effect on your production
It's just a way to initialise your backend work
.
Is subclassing an embed to reuse a good idea, or would it be better to make a function for it?
just use discord.Embed
i dont see any big reason for subclassing other that default values
so a function that returns just that? I have a dict that it reads from and returns the info in the respective fields
then why not just
discord.Embed(**your_dict)
the dict doesn't have keys that match with the embed args
like its not
description: '',
color: '',
fields: []
its
palette: '',
character: '',
creation_date: ''
thank you very much
Wlcm
Pycord is not even installing after following quickstart guide.
py-cord package is installed.
import discord
import os
client = discord.Bot()
@client.event
async def on_ready():
print(f'We have logged in as {client.user}')
@client.slash_command(guild_ids=[860169374278352906])
async def hello(ctx):
await ctx.respond("Hello!")
token = os.environ['token']
client.run(token)
?tag install
-
Uninstall
discord.pyor any other forks of discord.py you might have with the namespacediscord.
python -m pip uninstall discord.py discord -y -
Install
py-cord
python -m pip install py-cord
Installing other builds:
Note: You need to have git installed. Use !git to find out how to install git.
Updating the module to Alpha (unstable):
pip install -U git+https://github.com/Pycord-Development/pycord
Updating to release candidate:
pip install py-cord==2.0.0rc1
if you are using slash commands you have to use a version that is 2.0.0
It still doesn't work.
Just returns:
Traceback (most recent call last):
22.06 13:06:08 [Bot] File "/bot.py", line 1, in <module>
22.06 13:06:08 [Bot] import discord
22.06 13:06:08 [Bot] ModuleNotFoundError: No module named 'discord'
hm do you have the "-"?
some peope forget the - in py-cord sometimes which is a differnet library name
For installing py-cord, yes.
['cogs.moderation', 'cogs.events']
Traceback (most recent call last):
File "C:\Users\maksi\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\cog.py", line 727, in _load_from_module_spec
setup(self)
File "d:\Desktop\peer\cogs\events.py", line 19, in setup
client.add_cog(events(client))
File "C:\Users\maksi\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\cog.py", line 597, in add_cog
raise discord.ClientException(f"Cog named {cog_name!r} already loaded")
discord.errors.ClientException: Cog named 'events' already loaded
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "d:\Desktop\peer\bot.py", line 34, in <module>
client.load_extension(cog)
File "C:\Users\maksi\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\cog.py", line 787, in load_extension
self._load_from_module_spec(spec, name)
File "C:\Users\maksi\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\cog.py", line 732, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.errors.ExtensionFailed: Extension 'cogs.events' raised an error: ClientException: Cog named 'events' already loaded
Code:
cogs = []
for filename in os.listdir("./cogs"):
if filename.endswith(".py"):
cogs.append("cogs." + filename[:-3])
print(cogs)
if __name__ == "__main__":
for cog in cogs:
client.load_extension(cog)
You loading cogs multiple time
cogs = []
print(cogs)
if __name__ == "__main__":
for filename in os.listdir("./cogs"):
if filename.endswith(".py"):
cogs.append("cogs." + filename[:-3])
Do like this
How can I create slash command groups?
name="say_something",
description="say something!",
default_member_permissions=interactions.Permissions.ADMINISTRATOR, # admin-only
scope=931114842021044275,
options = [
interactions.Option(
name="text",
description="What you want to say",
type=interactions.OptionType.STRING,
required=True,
),
],
)
async def my_first_command(ctx: interactions.CommandContext, text: str):
await ctx.send(f"You said '{text}'!")```
What
variable = SlashCommandGroup("name", description="")
@variable.command()
Thx!
np
elaborate? this is just sending plain unformatted code
that doesnt even look like pycord lol
It says SlashCommandGroup is not defined.
import it
from discord import SlashCommandGroup``` i think or
```py
from discord.commands import SlashCommandGroup``` @azure quest
Ok but how can I use the SlashCommandGroup with a slash command?
its the same as normal
It doesn't work.
show code
test = discord.SlashCommandGroup("testname", description="testdesc")
@test.command(guild_ids=[860169374278352906])
async def hello(ctx):
await ctx.respond("Hello!")
is there an error?
No, but the only slash command in the list is /hello
The main command should be /test
no the command would be
/testname hello
thats weird maybe the commands didnt sync right?
🤷♂️
I think maybe it takes a bit to update?
Using the on_message and on_reaction_add events works fine for me for messages in normal channels, but doesn't seem to trigger on messages in threads
Are there different events for threads specifically or?
how to increase waaiting time slash command
my bot need some time to communicate with database
Defer the context
whole code on bot
await ctx.defer() at the start of your command function
Can you do pip list and send the output here
with hidden=True?
No
got it thanks 🙂
👍
absl-py 1.1.0 aiohttp 3.7.4.post0 aiosignal 1.2.0 astunparse 1.6.3 async-timeout 3.0.1 attrs 21.4.0 cachetools 5.2.0 certifi 2022.6.15 cffi 1.15.0 chardet 4.0.0 charset-normalizer 2.0.12 click 8.1.3 coc 0.2 coc.py 2.0.0 colorama 0.4.4 discord-py-interactions 4.2.1 discord-py-slash-command 4.2.1 flatbuffers 1.12 frozenlist 1.3.0 gast 0.4.0 google-auth 2.8.0 google-auth-oauthlib 0.4.6 google-pasta 0.2.0 grpcio 1.46.3 h5py 3.7.0 idna 3.3 joblib 1.1.0 keras 2.9.0 Keras-Preprocessing 1.1.2 libclang 14.0.1 Markdown 3.3.7 multidict 6.0.2 nltk 3.7 numpy 1.22.4 oauthlib 3.2.0 opt-einsum 3.3.0 packaging 21.3 pip 22.1.2 protobuf 3.19.4 py-cord 1.7.3 pyasn1 0.4.8 pyasn1-modules 0.2.8 pycparser 2.21 PyNaCl 1.4.0 pyparsing 3.0.9 python-dotenv 0.20.0 regex 2022.6.2 requests 2.28.0 requests-oauthlib 1.3.1 rsa 4.8 six 1.16.0
Uninstall discordpy related libraries
discord-py-interactions 4.2.1
discord-py-slash-command 4.2.1
should probably upgrade pycord too
!install
Install pycord:
pip uninstall discord.py
pip install py-cord
Install pycord beta:
pip uninstall discord.py
pip install py-cord==2.0.0b7
Install pycord alpha from git:
pip uninstall discord.py
pip install git+https://github.com/Pycord-Development/pycord
need to install 3
its not working
@client.command()
async def order(ctx):
await ctx.send("hello", components=[
[Button(label="Yes", style=3, custom_id="button1"),
Button(label="No", style=4, custom_id="button2")]
])
while True:
interaction = await client.wait_for("button_click")
await interaction.send("Select", components = Select(placeholder= "yeyeymemambawe", options=[SelectOption(label = "A", value= "B"), SelectOption(label= "E", value="C")]))
select_interaction = await client.wait_for("select_option")
await select_interaction.send(content=f"{select_interaction.values} selected!", ephemeral=False)
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: object of type 'Select' has no len()
could you elaborate?
No tag idw found.
whats the full stack tracE?
showing same error
wdym
the full error
hmm
Does someone have an answer to this question?
Ignoring exception in command None:
discord.ext.commands.errors.CommandNotFound: Command "oordeer" is not found
Ignoring exception in command order:
Traceback (most recent call last):
File "C:\Users\Abdulazeez\PycharmProjects\yupthing\venv\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\Abdulazeez\PycharmProjects\yupthing\main.py", line 23, in order
await interaction.send("Select", components = Select(placeholder= "yeyeymemambawe", options=[SelectOption(label = "A", value= "B"), SelectOption(label= "E", value="C")]))
File "C:\Users\Abdulazeez\PycharmProjects\yupthing\venv\lib\site-packages\discord_components\interaction.py", line 214, in send
res = await self.respond(
File "C:\Users\Abdulazeez\PycharmProjects\yupthing\venv\lib\site-packages\discord_components\interaction.py", line 153, in respond
data["components"] = _get_components_json(components)
File "C:\Users\Abdulazeez\PycharmProjects\yupthing\venv\lib\site-packages\discord_components\utils.py", line 20, in _get_components_json
for i in range(len(components)):
TypeError: object of type 'Select' has no len()
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Abdulazeez\PycharmProjects\yupthing\venv\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Abdulazeez\PycharmProjects\yupthing\venv\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\Abdulazeez\PycharmProjects\yupthing\venv\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: object of type 'Select' has no len()
can you show an example code
can you run pip list?
and send the output here
example code can be found on the github repo
thats now getting error
aiohttp 3.7.4.post0
async-timeout 3.0.1
attrs 21.4.0
chardet 4.0.0
discord 1.7.3
discord-components 2.1.2
discord.py 1.7.3
idna 3.3
multidict 6.0.2
pip 21.3.1
setuptools 60.2.0
typing_extensions 4.2.0
wheel 0.37.1
yarl 1.7.2
you dont even have pycord installed..
i have installed
that wasn't directed at you
recommend installing pycord before you complain about no one helping you
!install
Install pycord:
pip uninstall discord.py
pip install py-cord
Install pycord beta:
pip uninstall discord.py
pip install py-cord==2.0.0b7
Install pycord alpha from git:
pip uninstall discord.py
pip install git+https://github.com/Pycord-Development/pycord
make sure to uninstall all discordpy libs
this was showing
aka these two libs
i uninstalled them also
yes
can you show pip list again so I can double check?
absl-py 1.1.0 aiohttp 3.7.4.post0 aiosignal 1.2.0 astunparse 1.6.3 async-timeout 3.0.1 attrs 21.4.0 cachetools 5.2.0 certifi 2022.6.15 cffi 1.15.0 chardet 4.0.0 charset-normalizer 2.0.12 click 8.1.3 coc 0.2 coc.py 2.0.0 colorama 0.4.4 flatbuffers 1.12 frozenlist 1.3.0 gast 0.4.0 google-auth 2.8.0 google-auth-oauthlib 0.4.6 google-pasta 0.2.0 grpcio 1.46.3 h5py 3.7.0 idna 3.3 joblib 1.1.0 keras 2.9.0 Keras-Preprocessing 1.1.2 libclang 14.0.1 Markdown 3.3.7 multidict 6.0.2 nltk 3.7 numpy 1.22.4 oauthlib 3.2.0 opt-einsum 3.3.0 packaging 21.3 pip 22.1.2 protobuf 3.19.4 py-cord 2.0.0b7 pyasn1 0.4.8 pyasn1-modules 0.2.8 pycparser 2.21 PyNaCl 1.4.0 pyparsing 3.0.9 python-dotenv 0.20.0 regex 2022.6.2 requests 2.28.0 requests-oauthlib 1.3.1 rsa 4.8 six 1.16.0 tensorboard 2.9.1 tensorboard-data-server 0.6.1
Exception has occurred: AttributeError module 'discord' has no attribute 'Bot'
try discord.ext.commands.Bot()
just try changing it to bot = discord.Client()
was getting the same error
changed it and it started working
or better
import discord
from discord.ext import commands
bot = commands.Bot()
or this ^
not worked
Can you show the file?
BotBase.__init__() missing 1 required positional argument: 'command_prefix'
can anyone share bot code which is working
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix=".", intents=discord.Intents.all())
@bot.event
async def on_ready():
print(f"{bot.user} is ready!")
bot.run("TOKEN")
it's worked let me check adding new commands
don't forget about intents
ok
Hey guys, one question, was browsing around the examples in pycord github and the example in slash_option.py have a example for attach a file to slash command but i can't seem to attach anything when im trying the command, anyone knows why?
@bot.slash_command(name="attach_file")
@option(
"attachment",
discord.Attachment,
description="A file to attach to the message",
required=False # The default value will be None if the user doesn't provide a file.
)
async def say(
ctx: discord.ApplicationContext,
attachment: discord.Attachment,
):
"""This demonstrates how to attach a file with a slash command."""
if attachment:
file = await attachment.to_file()
await ctx.respond("Here's your file!", file=file)
else:
await ctx.respond("You didn't give me a file to reply with! :sob:")
i also trying but not worked
Traceback (most recent call last):
File "/home/pi/Desktop/Python/Minecraft Link/venv/lib/python3.9/site-packages/discord/client.py", line 382, in _run_event
await coro(*args, **kwargs)
File "/home/pi/Desktop/Python/Minecraft Link/venv/lib/python3.9/site-packages/discord/bot.py", line 1042, in on_connect
await self.sync_commands()
File "/home/pi/Desktop/Python/Minecraft Link/venv/lib/python3.9/site-packages/discord/bot.py", line 644, in sync_commands
registered_guild_commands[guild_id] = await self.register_commands(
File "/home/pi/Desktop/Python/Minecraft Link/venv/lib/python3.9/site-packages/discord/bot.py", line 473, in register_commands
prefetched_commands = await self.http.get_guild_commands(self.user.id, guild_id)
File "/home/pi/Desktop/Python/Minecraft Link/venv/lib/python3.9/site-packages/discord/http.py", line 357, in request
raise DiscordServerError(response, data)
discord.errors.DiscordServerError: 503 Service Unavailable (error code: 0): 503: Service Unavailable
why is it giving this error
['cogs.moderation', 'cogs.events']
Traceback (most recent call last):
File "C:\Users\maksi\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\cog.py", line 727, in _load_from_module_spec
setup(self)
File "d:\Desktop\peer\cogs\events.py", line 19, in setup
client.add_cog(events(client))
File "C:\Users\maksi\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\cog.py", line 597, in add_cog
raise discord.ClientException(f"Cog named {cog_name!r} already loaded")
discord.errors.ClientException: Cog named 'events' already loaded
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "d:\Desktop\peer\bot.py", line 34, in <module>
client.load_extension(cog)
File "C:\Users\maksi\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\cog.py", line 787, in load_extension
self._load_from_module_spec(spec, name)
File "C:\Users\maksi\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\cog.py", line 732, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.errors.ExtensionFailed: Extension 'cogs.events' raised an error: ClientException: Cog named 'events' already loaded
Code:
cogs = []
for filename in os.listdir("./cogs"):
if filename.endswith(".py"):
cogs.append("cogs." + filename[:-3])
print(cogs)
if __name__ == "__main__":
for cog in cogs:
client.load_extension(cog)
please help
Read the Error
I did -_-
Read the code
@past gate hi) I have something the command does not appear for a long time
@discord.slash_command(guild_ids=guild_id)
@commands.slash_command(guild_ids=guild_id)
I tried to put these two
Does someone have an answer to this question?
Can the role be pinged?
I had similar issue, and for me was that the role in options couldn't be pinged besides ppl with same role or Admins
The bot has administrator permissions, so yes it can ping
Did you try instead, discord.AllowedMentions.all()?
I tried without allowed_mentions, since it should also work without and I just added it to make sure
Ye, i had similar issues, but after add allowedmentions.all and check if roles can be pinged, it worked for me
alright let me try
Why do you have to list a cog 1st?
what do you mean
I mean why dont you just direct load extension within your for loop
i mean good point
Instead of appending them into a list 1st
Cogs, often known as modules or extensions, are used to organize commands into groups. This is useful
if __name__ == "__main__":
for filename in os.listdir("./cogs"):
if filename.endswith(".py"):
client.load_extension("cogs." + filename[:-3])
it still doesnt work tho
Try renaming event (or the conflicting cogs) to somethin else?
there may be conflicts with the cog class name
?
i changed the name to mod and
Extension 'cogs.mod' raised an error: ClientException: Cog named 'events' already loaded
OH WAIT
class name
YES
why is the slash command not being registered?
@commands.slash_command(guild_ids=guild_id)```
so and so I try.
application.commands is enabled
it works thank you omg!
You might want to take a look at some of the application command examples:
- https://github.com/Pycord-Development/pycord/blob/master/examples/app_commands/slash_basic.py
- https://github.com/Pycord-Development/pycord/blob/master/examples/app_commands/info.py
and anything really inside ofexamples/app_commands/
I can't really answer your question because its pretty vague
@bot.command()
async def estimate_prune(ctx,days:int):
a = await estimate(ctx,days)
for nik in a:
nick_name = discord.Guild.get_member(ctx.guild,nik)
await ctx.send(f'@{nick_name}')
async def estimate(ctx,days:int):
date = datetime.utcnow()- timedelta(days=days)
for i in channels:
if type(i) == discord.channel.TextChannel:
async for message in i.history(limit=None,after=date,oldest_first=True):
if message.author.id not in active_members:
active_members.append(message.author.id)
afk_members = [value for value in all_members if value not in active_members] # it doesn't update the afk_members list
return afk_members```
it doesn't update the afk_members list
is it bcz i am not using the @bot.command when calling the estimate function
is there any way to get a dictionary containing an object's data? Im cycling through a list of discord objects and i need to return their dictionary values, but .__dict__ doesnt work
i think it's because a bot command is not supposed to return a value
you could try and make it separate
cant you use dict(obj)
do you have the members intent enabled for your bot and provided to the bot?
yep i do
So im testing this on just one member object right now, and it's oddly giving me a type error--that discord.Member is not iterable
it started working now somehow
yeah i was thinking the same thing
the command isnt returning a value though
ohh yeah my bad i didn't see it well
Hi, so I started looking into this time feature in DC like <t:1655920645:R> and that would work really well for a giveaway feature but the only thing that my bot now needs is to check if the timer is already up. How can I do that?
what is DC?
discord
well, you can try time.time()
and that returns a unix timestamp
or something like 12342353
and you can compare that to <t:12342353>
the larger the number, the later it is
so you can compare the two ints and see if time.time() is larger or equal to, or not at all
hey anyone have idea about band
Thats my code and the errors. I dont get what im doing wrong? I wanna do and error handler for member, so if anyone types e.g. /removerole d and thats not a real member on the server it will send a message
how do you check if a channel is in a certain category?
Check the parent of the channel via channel.parent
kk
any ideas why it wont work?
Why are you comparing a Category Channel to a string
You should extract the name of the parent of the channel, or even better, compare via ids
does pycord support these type of embeds? with no border
what is it called in the docs?
Embed.Empty
nvm all they do is set the color to "#36393F"
components.3.components.0.options.3—is this 0-indexed or 1-indexed?
lists/arrays in programming languages are 0 indexed
also the correct syntax is components[3].components[0].options[3]
Not all of them
IIRC Lua starts from 1
Is it possible to set up an automated test framework to test slash commands and views?
is there any way to make a slash command only appear to the bot owners?
how can you verify if a user is a administrator ?
from a discord.ApplicationContext
ctx.author.guild_permissions.administrator
thanks you !
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embeds.0.url: Scheme "<response [200]>" is not supported. Scheme must be one of ('http', 'https').```
From a user account, you can make API calls and test them, but this is against ToS.
Using a Bot account will fail because method not allowed
only in a specific server that the owners have permissions in
send code for embed
skylink = requests.get(f'https://sky.shiiyu.moe/stats/{ign}/{profile_name}')
response = requests.get(f'https://sky.shiiyu.moe/api/v2/coins/{ign}/{profile_name}')
player_api = requests.get(f'https://api.slothpixel.me/api/players/{ign}')
slayers_api = requests.get(f"https://sky.shiiyu.moe/api/v2/slayers/{ign}/{profile_name}")
true_api = requests.get(f"https://api.slothpixel.me/api/skyblock/profile/{ign}/{profile_name}")
player = requests.get(f"https://api.slothpixel.me/api/skyblock/profile/{ign}/{profile_name}")
dungeons_api = requests.get(f"https://sky.shiiyu.moe/api/v2/dungeons/{ign}/{profile_name}")
profile = response.json()
mcuid = MojangAPI.get_uuid(ign)
mcuid = mcuid.replace('-', ' ')
hotmxp = true_api.json()["members"][mcuid]["mining_core"]["experience"]
dungeons_level = dungeons_api.json()["dungeons"]["catacombs"]["level"]["level"]
level = player_api.json()["level"]
rank = player_api.json()["rank"]
purse = profile["purse"]
bank = profile["bank"]
purse = int(purse)
bank = int(bank)
purse = f"{purse:,}"
bank = f"{bank:,}"
hotm_level = str(hotm_level)
embed = discord.Embed(title='Account To Be Sold', url=skylink)
embed.add_field(name='IGN', value=ign)
embed.add_field(name='RANK', value=rank)
embed.add_field(name='Hypixel lvl', value=level)
embed.add_field(name='Purse', value=str(purse))
embed.add_field(name='Bank', value=str(bank))
embed.add_field(name='HOTM', value=hotm_level)
embed.add_field(name='CATA', value=dungeons_level)
await channel.send(embed=embed)
skylink is a Response 200
that explains a lot
wait how, if i replace the ign and profile_name with real values it works
works just fine
I’m assuming you just want the url of the skyblock profile. try just
skylink = “url”
you might wanna swap out those http requests using requests to use aiohttp instead. using requests library blocks your code
If it’s a private bot, don’t worry about it, but it’s still good practice
its still gonna affect things if the server is unable to respond fast
That could be a cool pycord feature
automated testing of commands
how to fix this
import discord
import json
from discord.ext import commands
with open('./config.json') as config:
data = json.load(config)
token = data["token"]
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
@bot.event
async def on_ready():
print(f"{bot.user.name} is online")
@bot.command()
async def ping(ctx):
await ctx.send("pong")
bot.run(token)
bot event work
but bot command not work
uhm, maybe remove that whitespace between your async def and @bot.command()
work with select this in discord develop
How i can use aiohttp to make my bot fast
Aiohttp has documentation that you can read here: https://docs.aiohttp.org/en/stable/
The documentation also includes some examples
how would i override a command cooldown for a specific role?
Where is the source code for message caching located?
https://pycord.dev/github, I believe it's in a file named state.py
Stop being rude!
Sry for his behavior
Projects exist which emulates discord backend
Hey, When i help him he said did i asked then i deleted all my msg and i being rude why you saying sorry to him ? He really don't know how to behave i just help him and after help he said did i asked it.? And second thing you don't know the matter and you warning me what's the behaviour?
And you are now lecturing me?
If you delete your messages, we can’t see what the situation was.
This is your fault now.
Im sorry i think you were misunderstanding,
From what i remember,
1st. I asked on how on_disconnect event work
2nd. I saw you replied to the guy who asked about voice stuff, then replied to me is there such disconnect event
3rd. I show you on_disconnect, then you replied its an event from bot to discord not voice
4th. didnt i asked that?
So why the logs are made ?
I know the situation now.
You should really learn to calm down and clearly read a whole conversation instead of just mixing thoughts together.
@half marsh is right in this situation and you were misunderstanding it and being rude.
This is what i asked
Yo what, im fine with him
Ah well ok then
🔨 Banned 942683245106065448 indefinitely
Thing is he already came to my attention a few days before. His kinda seeking drama
Aahh... Up to you then 💯
If all bots created in the same account share a global rate limit ?
quick question, discord only allows slash commands now or prefixes command still work?
prefix command still work
mine doesn't it, it's not showing any errors
It's hard to figure out what was happened, show your code bro
import os
from discord.ext import commands
from dotenv import load_dotenv
bot = commands.Bot(command_prefix= ['-'], help_command=None)
@bot.event
async def on_ready():
act = discord.Activity(type=discord.ActivityType.listening, name='-help')
await bot.change_presence(status=discord.Status.dnd, activity=act)
print("it's working good job")
@bot.command()
async def load(ctx, extension):
bot.load_extension(f'data.{extension}')
@bot.command()
async def unload(ctx, extension):
bot.unload_extension(f'data.{extension}')
@bot.command()
async def reload(ctx, extension):
bot.unload_extension(f'data.{extension}')
bot.load_extension(f'data.{extension}')
for filename in os.listdir('./src/data'):
if filename.endswith('.py'):
bot.load_extension(f'data.{filename[:-3]}')
load_dotenv()
TOKEN = os.getenv("TOKEN")
bot.run(TOKEN)```
enable message_content intent
?tag intents
import discord
from discord.ext import commands
# Get specific intents for fine control
intents = discord.Intents()
intents.emojis = True
intents.guilds = True
intents.messages = True # Required for prefix commands!
...
# Get all non-priveliged intents; this excludes presences, members and message_content
intents = discord.Intents.default()
# Set priveliged intents: these must be enabled on dev portal
intents.members = True
intents.presences = True
intents.message_content = True # Required for prefix commands >= 2.0.0b5
# Get all intents; all intents must be enabled on dev portal.
intents = discord.Intents.all()
# Apply intents when creating your bot
bot = commands.bot(prefix="?", intents=intents)
Hello guys is there any tutorial for which guides us through pycord and how to develop bots from scratch from it?
tysm
Not officially from us. Just search 
I don't think i would need that, this guide is so good
Guys anyone have pagination examples , where reacting to the emoji will edit the existing message
Hey guys, i was looking into the pycord examples and saw a example that slash commands we can attach a file to them now, i tried the example but couldn't attach a file using, dunno if i was using it wrong anyone have a idea how it works?
@bot.slash_command(name="attach_file")
@option(
"attachment",
discord.Attachment,
description="A file to attach to the message",
required=False # The default value will be None if the user doesn't provide a file.
)
async def say(
ctx: discord.ApplicationContext,
attachment: discord.Attachment,
):
"""This demonstrates how to attach a file with a slash command."""
if attachment:
file = await attachment.to_file()
await ctx.respond("Here's your file!", file=file)
else:
await ctx.respond("You didn't give me a file to reply with! :sob:")```
That example looks wrong
You already have a post #discord.Option 'required' parameter not working?
Please don’t ask here too if you already have a thread.
Was recently updated in the pycord GitHub, that's why I'm asking if i was doing something wrong
with open('extensions.txt','r') as f:
for line in f:
for word in line.split():
print(word)
initial_extensions = [word]
the text contains 'hello.command' , 'hello.test'
but it returns a error with cant find hello
how do i return 'hello.command' , 'hello.test'
its ordend like
'hello.command' ,
'hello.test'
in the file
i do have that i have BBMoon.commands.mod.warn basicly Xd
but it returns No module named "'BBMoon"
in the folder BBMoon i have a few cogs and more folders
but it stops reading the text file after the BBMoon. so the . and most likely the , will cause problems
Instead of using a txt file, did you try with simple list and put the values int here?
initialExtensions = [
"cogs.Fun.helloBot",
"cogs.Fun.pokeBot",
]
And then run for loop to load the extensions
i had that but what my goal is is to be able to do !reload cogs and that the cogs that i added will load too withou having to restart the whole bot Xd
And you can still do that
I can reload a specific cog
yeah can you also load in a new one ?
thats my goal Xd
Just make a command that simple adds the new cog to the initial_extension list
And then run the load function
Never tried
i could try
it says that the cogs are allready loaded
so i have to unload them first i think
it doesnt work
there should be a way for it to work
I tried too, and it doesn't it seems you need to restart the bot everytime
Even if i can add the new cog and load
The command won't show
breh okey thanks for the help tho !
What are guilds?
the technical name for discord servers
My bot won't register any commands I put inside main.py but it registers commands in all the cogs.
I have no clue what to say.
I'm using @discord.commands.core.slash_command(guild_ids=[4564564564245])
Anyways here's a spongebob episode
Try using @bot.slash_command
I was trying the following to make a slash command with a required user option
@bot.command(guilds_ids=[server], description="Funnify a member.")
async def funny(ctx, user: discord.Option(user)):
guild = bot.get_guild(server)
role = guild.get_role(985086725938356244)
if role in ctx.author.roles or ctx.author.id == 675316333780533268:
await ctx.respond(f"Successfully funified {user}")
but I am getting the error undefined name 'user'
discord.Member
you use a command and not a slash command
And slash commands use @bot.slash_command
ok
Is it just me that's having trouble getting select menus to work correctly?
I wrote this to create a slash command
view = View()
select = Select(placeholder="Make a move!", min_values=1, max_values=1, options=options) #options is a list from earlier in the code
async def selected(interaction):
await interaction.response.send_message(content="Move made!", ephemeral=True)
print(select.values[0])
await msg.edit(content=formresponse(text), view=view)
select.callback = selected #set callback
view.add_item(select)
await ctx.send(content=formresponse(text), view=view)
Sometimes it responds
sometimes it doesn't
I don't understand why, select menus just aren't working for me often
it's only part of a bigger function
Unsure if its just discord mobile but your code doesn't make any sense to me, you've defined the same function twice?
wait hold on
I edited it
Also it's much better to inherit from View or Select rather than setting the callback property yourself
I feel like I say this a lot...
Your code makes no sense to me
Sorry the indentation on discord is hard to figure out
This
I'd subclass discord.ui.View. it's way easier
https://easy-pil.readthedocs.io/en/latest/easy_pil/easy_pil.editor.html?highlight=bar#easy_pil.editor.Editor.bar easy pil has a function to build them
No i not mean this..
Probably?
I got it anyway thanks
so i wanna check on member update if there display name changed but i dont want it to run if a bot chnaged it is there a way i can do that
actualyy i dont want it to change if anyone but the user himself changed it
basicly how do i get who changed nickname lol
does it take time for it to be registered since i made and it doesn't reflect on discord yet.
Deny manage nicknames lol
Every other approach is just overload
I have been sing 0b5 version here and would like to install the same. Could someone help me out with this error please?
if you dont supply any guild ids to the guild_ids parameter then yes
up to an hour
otherwise should be instant
Ty
update pip
It is working just fine now ty
but i am reiceiving this when it sends the output just fine
use await ctx.respond instead of send
Also, all the commands which used ! prefix in my bot have now been not working with the initial prefix 💀
seems like it converted all the commands to use slash
I'm searching for the same thing so if you have a answer i would be happy to know it
For some reason my callback is never being answered in my dropdown menus
#text and options variables set up earlier
msg = None #Initiate variable to be used in callback
class Dropdown(discord.ui.Select):
def __init__(self, bot_: discord.Bot):
super().__init__(
placeholder="Make a move",
min_values=1,
max_values=1,
options=options,
)
async def callback(interaction):
await interaction.response.send_message(content="Move made!", ephemeral=True)
print(select.values[0])
await msg.edit(content=text, view=view)
class DropdownView(discord.ui.View):
def __init__(self, bot_: discord.Bot):
self.bot = bot_
super().__init__()
self.add_item(Dropdown(self.bot))
view = DropdownView(client)
msg = await ctx.send(content=formresponse(text), view=view)
My print statements don't run, so I feel like the callback function just isn't being triggered
you dont
its only await ctx.defer()
ok ok...
view = discord.ui.View(timeout=None)
view.add_item(discord.ui.button(label="Red", style=discord.ButtonStyle.red, custom_id="1"))
await message.edit(view=view)
how can you just create buttons in this way?
Try it
And see what happend
view.add_item(discord.ui.button(label="Red", style=discord.ButtonStyle.red, custom_id="1"))
File "C:\Users\merka\Desktop\pythonProject33213\civpyMain\venv\lib\site-packages\discord\ui\view.py", line 279, in add_item
raise TypeError(f"expected Item not {item.__class__!r}")
TypeError: expected Item not <class 'function'>```
ui.button is decorator
ui.Button is class
how can a button click be handled?
If you mean is callback, you can set the button callback attribute to a coro function
async def cb(inter):
....
ui.Button(...).callback = cb
async def add_button_in_lobby(self, lobby):
""" . """
view = discord.ui.View()
view.add_item(discord.ui.Button(label="test", style=discord.ButtonStyle.primary, custom_id="join"))
discord.ui.Button("join").callback = self.cb
return view
async def cb(inter)
pass
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: __init__() takes 1 positional argument but 2 were given
and
async def add_button_in_lobby(self, lobby):
""" . """
view = discord.ui.View()
view.add_item(discord.ui.Button(label="test", style=discord.ButtonStyle.primary, custom_id="join")).callback = self.cb
return view
async def cb(inter)
pass
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'NoneType' object has no attribute 'callback'
I don't understand how
We have logged in as KIYU#1751
Ignoring exception in on_message
Traceback (most recent call last):
File "/home/firminou/.local/lib/python3.8/site-packages/discord/client.py", line 382, in _run_event
await coro(*args, **kwargs)
File "main.py", line 22, in on_message
await msg.channel.send(msg.content)
File "/home/firminou/.local/lib/python3.8/site-packages/discord/abc.py", line 1521, in send
data = await state.http.send_message(
File "/home/firminou/.local/lib/python3.8/site-packages/discord/http.py", line 359, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50006): Cannot send an empty message
hey guys so I don't quite understand why is my bot trying to send an empty message while its not an empty message
here is the code of the bot
import discord
intents = discord.Intents.default()
intents.message_content = True
bot = discord.Bot()
@bot.event
async def on_ready():
print(f'We have logged in as {bot.user}')
@bot.event
async def on_message(msg):
if msg.author == bot.user:
print("lol")
return
if msg.content == 'oui':
print('yo')
await msg.channel.send('ok!')
else:
await msg.channel.send(msg.content)```
You have to pass the intents to discord.Bot via the intents keyword argument
It doesn't actually have the message content intent enabled
oh okay thank you !
-
Try not to set the callback like this, if you want to add a button ad hoc then you can subclass
ui.Buttonand override the callback function there e.g.py class MyCustomButton(ui.Button): async def callback(self, interaction): await interaction.response.send_message("Hello, world!")and then add it withpy view.add_item(MyCustomButton(label="Text", style=discord.ButtonStyle.primary)2. In your first example, you are not actually setting the callback of your specific button toself.cb, you've just made another button instance passing only"join"into its constructor, which obviously won't work, what you probably wanted here is something like this ```py
async def add_button_in_lobby(self, lobby):
view = discord.ui.View()
button = discord.ui.Button(label="test", style=discord.ButtonStyle.primary)
button.callback = self.cb
view.add_item(button)return view``` However, like I said earlier, this is not a very good way of doing it. -
In your second example, you are trying to set the property
callbackon the result of youradd_itemcall, which returnsNoneresulting in your error. -
self.cbshould be takingselfas an argument or just mark it with@staticmethodto make it a static method (https://realpython.com/instance-class-and-static-methods-demystified/)
there is then some on_button_click. So that when we click on the button, we catch the event?
on_interaction
Try to avoid catching button events with on_interaction
You are just introducing more complexity into your code
In general, I would like something like
@on_click("join")
async def join(inter):
pass
is there something similar?
Hey guys how can I check if someone is in a voice channel ?
voice seems to be if the guy is muted or not
Idk exactly but you could loop threw the voice channels
hmm guess it'll work thx !
didnt feel like this needs a new thread, so ill just ask it here...
when you have a user option in a slash command, is it restricted at all? from what i remember, you can specify any user id into the field and pycord auto-converts it into a user object - do we have to manually check whether the user has access to the channel where the slash command is used?
Not really, you could take a look at the view examples
?tag slash_commands
No tag slash_commands found.
?tag
Description: Edit a tag
Cooldown: 5 seconds
Usage:
?tag edit (optional category) [tag name] [content]
Example:
?tag edit how2invite Invite Dyno to your server at https://dyno.gg/invite
No tag slash found.
If voice is None they they are not connected to a voice channel
- #app-commands 2. https://github.com/Pycord-Development/pycord/tree/master/examples
Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - pycord/examples at master · Pycord-Development/pycord
- Sorry didnt see that chat 💀 2. Thanks
can anyone explain what a public vs private thread is? ive seen very little about it, and this sparked my curiosity:
is a private thread similar to a private channel? cause it doesnt have a link to a message...
and how do permissions work for that?
cause from what i remember its a thread where mods have to invite you in
but dont all threads need a message?
how can I kick someone out of a voicechannel ?
Views are hard...... I am trying to create a button according to a value inside a view but i have no idea how to do that properly. Any examples?
i guess impossible via decorators
cannot find a kick method
and a huge if wrapping the entire thing wont work because weird python class issue
lets say if something is true i add a button called Yes but if not i add a button called No
does the something ever change? and if so, how?
and what is the something? a value in a select?
doesnt really change, just a parameter in init that affects the button text
you are correct - but remember, you can always subclass ui.Button and use view.add_item
you could literally just do
view.add_item(Button(style=ButtonStyle.green, label="Yes", ...))
in your constructor
and that lets you use ifs
the option decorator, if the name used for the argument is different than the function's parameter name
discord shows the parameter name not the decorator's name
dunno if thats intended or not
How can i connect my mongosrv url thing into my env?
cos i have github, dont want it expose
d
do it like how you normally do it
What’s the best to use to store data? Json files? A database?
Database
It could be overloaded very easily though.
So
bot.mongoConnect = motor.motor_asyncio.AsyncIOMotorClient(os.getenv("MONGO"))```would something like this work
yes
ook
.. with
Little stuck, is there a way you can see when a user joined a server?
I've tried member.joined_at but ....no luck.
wdym
How do i fix
WARNING:discord.http:We are being rate limited. Retrying in 17.71 seconds. Handled under the bucket "None:965533467557371944:/applications/{application_id}/guilds/{guild_id}/commands"
From what i see, They want to send to a channel or print to console when a member joined a server
you can't
I think it may have been cause i had another terminal open with my bot.. ima try the fix now
Yeah it was that, May i ask why that occurs if the 2x terminal wasnt the reason?
I asked about this a few days ago but didnt get far,
@slash_command(name="suggest", description="suggestions")
@commands.cooldown(1,7200, commands.BucketType.user)
async def modal_slash(self,ctx: discord.ApplicationContext):
await ctx.send_modal(Suggestions(self.bot, title="Suggestion"))
db = self.bot.mongoConnect["FelBot"]
collection = db["FelBott"]
await collection.find_one({'_id':m.id},m.id)
await collection.insert_one(m.id)``` m isnt defined, but where can i define it again and what should i define it as
@slow dome
probably ctx.author
I defined it as m = ctx.author
I got this error
TypeError: projection must be a mapping or list of key names
bruh I don't even know what you are trying to do
Tryna store message id
into mongo
ok then make m a discord.Message object
How would i do this?
docs are your friend
class Suggestions(discord.ui.Modal):
def __init__(self,bot,*args, **kwargs) -> None:
self.bot = bot
super().__init__(*args, **kwargs)
self.add_item(discord.ui.InputText(label="Your Suggestion: ", style=discord.InputTextStyle.long))
async def callback(self, interaction: discord.Interaction):
m = await interaction.response.send_message("Suggestion send!", ephemeral=True)
suggest = discord.Embed(title=f"Suggestion by {interaction.user} Under Review ",color=discord.Color.blue())
suggest.add_field(name="Your Suggestion: ", value=self.children[0].value)
suggest.set_footer(text=f"Message id: {m.id} ")
channel = self.bot.get_channel(987396375069224960)
embed = await channel.send(embed=suggest)
await embed.add_reaction('☑')
await embed.add_reaction('❌')
class Suggest(commands.Cog):
def __init__(self,bot):
self.bot = bot
@slash_command(name="suggest", description="suggestions")
@commands.cooldown(1,7200, commands.BucketType.user)
async def modal_slash(self,ctx: discord.ApplicationContext):
await ctx.send_modal(Suggestions(self.bot, title="Suggestion"))
m = ctx.author
db = self.bot.mongoConnect["FelBot"]
collection = db["FelBott"]
await collection.find_one({'_id':m.id},m.id)
await collection.insert_one(m.id)
full code
ook
you are capable of doing this yourself
Thats true lol
Im confused tho lol, What am i supposed to do? m = discord.Message or like self, ctx, m: discord.Message
I don't even know what message is
The message id im trying to store is an embed of a suggestion
what embed
Its /suggest, brings a modal u type ur suggestion then it sends an embed of that suggestion to a channel (check thefull code i sent itll make sense)
do your database thing in the modal callback and set embed equal to m
m = await interaction.response.send_message("Suggestion send!", ephemeral=True)```
Already is, Where im having the issue is on this line
await collection.find_one({'_id':m.id},m.id)
I defined m as m = ctx.author but i got this error after trying suggest
TypeError: projection must be a mapping or list of key names
if you want the message id, just set it as the m as the message
Wym
I asked you to set it as the author because I thought you wanted the author id
Oh, So id set it as m.id
@slash_command(name="suggest", description="suggestions")
@commands.cooldown(1,7200, commands.BucketType.user)
async def modal_slash(self,ctx: discord.ApplicationContext):
await ctx.send_modal(Suggestions(self.bot, title="Suggestion"))
m = m.id
db = self.bot.mongoConnect["FelBot"]
collection = db["FelBott"]
await collection.find_one({'_id':m.id},m.id)
await collection.insert_one(m.id)``` says its assigned before assignmnent, how tho
UnboundLocalError because where in the world is m.id defined
I said do the database things in the modal callback
async def callback(self, interaction: discord.Interaction):
m = await interaction.response.send_message("Suggestion send!", ephemeral=True)
suggest = discord.Embed(title=f"Suggestion by {interaction.user} Under Review ",color=discord.Color.blue())
suggest.add_field(name="Your Suggestion: ", value=self.children[0].value)
suggest.set_footer(text=f"Message id: {m.id} ")
channel = self.bot.get_channel(987396375069224960)
embed = await channel.send(embed=suggest)
await embed.add_reaction('☑')
await embed.add_reaction('❌')
class Suggest(commands.Cog):
def __init__(self,bot):
self.bot = bot
@slash_command(name="suggest", description="suggestions")
@commands.cooldown(1,7200, commands.BucketType.user)
async def modal_slash(self,ctx: discord.ApplicationContext):
await ctx.send_modal(Suggestions(self.bot, title="Suggestion"))
m = m.id
db = self.bot.mongoConnect["FelBot"]
collection = db["FelBott"]
await collection.find_one({'_id':m.id},m.id)
await collection.insert_one(m.id)
not in the slash command callback
so move the db stuff above the class cog
Traceback (most recent call last):
File "C:\Users\jackd\Documents\Felbcord Py.venv\lib\site-packages\discord\ui\modal.py", line 260, in dispatch
await value.callback(interaction)
File "C:\Users\jackd\Documents\Felbcord Py\Modals\Suggestions.py", line 24, in callback
await collection.find_one({'_id':m.id},m.id)
File "C:\Users\jackd\AppData\Local\Programs\Python\Python310\lib\concurrent\futures\thread.py", line 58, in run
result = self.fn(*self.args, **self.kwargs)
File "C:\Users\jackd\Documents\Felbcord Py.venv\lib\site-packages\pymongo\collection.py", line 1418, in find_one
cursor = self.find(filter, *args, **kwargs)
File "C:\Users\jackd\Documents\Felbcord Py.venv\lib\site-packages\pymongo\collection.py", line 1610, in find
return Cursor(self, *args, **kwargs)
File "C:\Users\jackd\Documents\Felbcord Py.venv\lib\site-packages\pymongo\cursor.py", line 250, in init
projection = helpers._fields_list_to_dict(projection, "projection")
File "C:\Users\jackd\Documents\Felbcord Py.venv\lib\site-packages\pymongo\helpers.py", line 242, in _fields_list_to_dict
raise TypeError("%s must be a mapping or list of key names" % (option_name,))
TypeError: projection must be a mapping or list of key names
this error now
ping me if u reply
@slow dome
how many items can i add in a modal?
5
well
you can add 5 rows
a row can have up to 5 buttons, or up to 1 select dropdown
so technically you can add up to 25 items
@lusty dragon
i mean how many input texts
in a modal
?
like what?
is there a way to use commands.Bot without entering a prefix?
e.g.
bot = commands.Bot()
as of right now this errors "missing 1 required positional argument: 'command_prefix'"
wait am i even using the updated version
i am
1.7.3
That is discord.py but fine for starter stuff
For buttons and other stuff you a another version
do you have something else installed?
for the command_prefix?
no
i havent installed any packages before this
ok im using the guide code and its not working either
which one?
Excited to create your first bot? Once you install Pycord, you can start right
without the os and enviroment variables
it just says that bot isnt part of discord
ill try to troubleshoot this on my own and ill ask questions in here
they really need to fix this....
uninstall the old version with
pip uninstall py-cord
i tried uninstalling and reinstalling
wait
the newest version is 1.7.3 right?
or is that really old
nope
dang
its the old one
uninstall it and install the newest version with
pip install py-cord==2.0.0rc1
ok
which editor to you use?
vscode
you have to restart the editor after the installation
\o
whats really weird is on github the latest release is still 1.7.3
https://pypi.org/project/py-cord/1.7.3
Full Changelog: v1.7.2...v1.7.3
hmmm
does someone know why after printing data the bot goes offline?
NH().get is not async code...
so i to_thread it
am i dumb?
no error in logs too
how do I get a class with a button from another cogs?
pass an empty string if you don't want any prefix
can someone help?
I would recommend using a class from where you import the kind of buttons you want (customised one)
When a variable/object is not defined, that's the error that shows up
you haven't defined bot anywhere
i just import it
now i got this:
TypeError: remove_command() missing 1 required positional argument: 'name'
depends on what you imported. Could you show me the bot definition?
from discord.ext.commands.bot import Bot i import this
Do you get the same issue without it?
yes
Normally, if you print anything, it shouldn't go offline.
If you're running the bot, then there will be an error thrown by default.
what?
no i mean if i dont used the print to it shut down
Which version of Pycord are you using?
You can pip freeze and you'll see py-cord==version
i use 1.7.3
Do
Pip install py-cord==2.0.0rc1
^ That's Beta version, btw
2.0.0b7 might be good
It's the release version isn't it
It's the best one to be on
1.7.3 is basically discord.py
what perms i need to timout ppl?
the same you need as user 
huh? elaborate
what perms i need as user 
"Timeout member" 💀
Have you ever read the discord permissions list lol
Hi, how do I get the author of button interaction?
try moderate membes
interaction.user
k lemme try#
await inter.response.edit_messsage(content="deleted!", view=None) and i am getting this error: 'InteractionResponse' object has no attribute 'edit_messsage'
ah yes edit_messsage
oh oops
await collection.find_one({'_id' : m.id},m.id)```
TypeError: projection must be a mapping or list of key names
What here is giving me the error?
How do i make multiple options in a menu using a loop 
@commands.command()
async def shutdown(self, ctx):
await ctx.send("hjskld")
await self.bot.logout()
why that command dowsn't works
are you providing your bot with messages and message_content intents?
How can I check if someone is currently boosting the guild?
@commands.command()
@commands.has_permissions(manage_roles=True)
async def removerole(self, ctx, member: discord.Member, role: discord.Role = None):
if member is None:
embed = discord.Embed(title='Role Manager ▼', description='You must specify a Member!', color=0xff3344)
await ctx.send(embed=embed)
if role is None:
embed = discord.Embed(title='Role Manager ▼', description='You must specify a Role!', color=0xff3344)
await ctx.send(embed=embed)
if member in ctx.guild.members:
embed = discord.Embed(title='Role Manager ▼',
description=f'Succesfully removed the Role {role.mention} from {member.mention}!',
color=0x8fce00)
await member.remove_roles(role)
await ctx.send(embed=embed)
else:
embed = discord.Embed(title='Role Manager ▼',
description=f'''Couln't find the user {member}''',
color=0xff3344)
await ctx.send(embed=embed)
@removerole.error
async def removerole_error(self, ctx, error, member):
if isinstance(error, MissingPermissions):
embed = discord.Embed(title='Role Manager ▼', description='You dont have permissions to do that!',
color=0xff3344)
await ctx.send(embed=embed)
elif isinstance(error, MemberNotFound):
embed = discord.Embed(title='Role Manager ▼', description=f'''I couldn't find the suer!''',
color=0xff3344)
await ctx.send(embed=embed)
else:
raise error
What am i doing wrong?
I wanna make a removerole command but if someone types /removerole sidufg and thats not a member on the server then send a message!
But it doesnt work!
remove member from your argument in your error handler
you can always get the person who ran the command with the context
ctx.author
like this?
yes
yes
How do I check if someone is currently boosting a server?
the Members premium_since attribute will be a datetime object of when they boosted the server
or None if not boosting
so if they have boosted previously, but aren't actively boosting it will show None?
yep
can an ephemeral message be changed to a non-ephemeral message when you have a response?
what do you mean?
So say i do
ctx.defer(ephemeral=True)```
if the defer is ephemeral yes
Oh handy to know
any follow ups after the initial follow up to a defer may be whichever because theyre not tied to the defer
Ohhh, now that is how someone helps thanks so much
?
py-cord==2.0.0rc1
thank you
So, I have been trying to get the user id's but the bot always keeps on saying the application is responding, just like in the image.
it doesn't let me start a game
oof, ill just say that this is bad practice to rely on the global keyword
you should containerize everything in a class so that multiple instances of tic tac toe may exist
whats even better is that you can put all that in a View subclass to incorporate button input as well
I tried, it still required an argument.
Turns out I was using an old Pycord
@crimson gale Hey would you mind helping me here?
i will try to do that but can you help me identify the current problem?
show me the full callback please
what is line?
btw you can get a mention string out of a Member or User by using the mention attribute so you dont have to make the mention formatting yourself
also this should really be a function that returns a list instead of setting a variable
i seee
or just returning stuff in general
it makes more sense, is readable and more generalized
#989902108880949269 anyone (just so ppl see it easier)
the thing is everything was working fine with prefixed commands,i tried slash and all of my commands were converted to slash
i can always revert back to prefix
but i thought to learn about slash
how can I get errors like this, do I have to download any packages?
i think the function not returning anything is the main cause of your issue
are any errors raised when you use it btw?
yeah but it is handled
it doesn't cause the bot to stop
ohh alr
im aware
but updating makes that error go away
because thats caused by the old permissions v1 having been deprecated without notice
i will do so tysm
In components.0.components.1: The specified component exceeds the maximum width
What's going on here?
code
one sec
Full traceback is
Ignoring exception in view <TicketQuestionManagerView timeout=180.0 children=2> for item <Button style=<ButtonStyle.secondary: 2> url=None disabled=False label='Edit existing question' emoji=<PartialEmoji animated=False name='✏️' id=None> row=None>:
Traceback (most recent call last):
File "C:\Users\Nexus\PycharmProjects\trident-bot\venv\lib\site-packages\discord\ui\view.py", line 371, in _scheduled_task
await item.callback(interaction)
File "C:\Users\Nexus\PycharmProjects\trident-bot\views.py", line 424, in edit_existing_question
await interaction.edit_original_message(view=self)
File "C:\Users\Nexus\PycharmProjects\trident-bot\venv\lib\site-packages\discord\interactions.py", line 379, in edit_original_message
data = await adapter.edit_original_interaction_response(
File "C:\Users\Nexus\PycharmProjects\trident-bot\venv\lib\site-packages\discord\webhook\async_.py", line 213, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In components.0.components.1: The specified component exceeds the maximum width
It sends okay though oddly enough. I'll try removing that one sec
fe0f is variation selector so I didn't think it'd matter lol
Could someone check #989902108880949269
its worth a shot to see if its causing issues
i fix that with this:
command_prefix=";",
intents=discord.Intents.all(),
help_command=None
)```
Nope, same problem
I’m saying how you have an error saying "bot" is not defined and your code being underlined, how do i do that?
so the same error?
i think u can import some module
Let me see if I can still repro
do u know which one?
its too large for discord one sec
this is the flow I've got
As soon as that modal is submitted, that view is stopped, which then means view.wait() on line 69 is released, updating the message back to the original view on line 70
Let me see if clearing the view before updating it again changes anything It does not, same error
Let me turn the view into a Dict when it errors one sec
OH I GOT SOMETHING
You see that Select in that modal at the end? If I change the value, the error doesn't raise.
I know select items aren't officially supported yet so it could be something to do with my patch
(of which I stole from ##1419 but yk)
(if you're interested in the View's component breakdown, you can find it at https://paste.pythondiscord.com/amozeyerul.json)
anyone know any packages / modules I can use for this?
I think this is most likely the reason
is this architecture correct?
cog
import discord
from discord.ext import commands
from config import settings
from cogs.button_handler import JoinButton
class LobbyCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
async def add_button_in_lobby(self, lobby):
""" . """
view = discord.ui.View()
view.add_item(JoinButton())
return view
def setup(bot):
bot.add_cog(LobbyCog(bot))
button_handler
import discord
from discord.ext import commands
class JoinButton(discord.ui.Button):
def __init__(self):
""" . """
super().__init__(
label="test",
style=discord.ButtonStyle.primary,
custom_id="join",
)
async def callback(self, interaction: discord.Interaction):
print("pressed")
# and then more buttons
why do that when you can just subclass View and make the callbacks directly in there
can I have an example?
?tag ex
Bot examples: https://github.com/Pycord-Development/pycord/tree/master/examples
Slash command/context menu examples: https://github.com/Pycord-Development/pycord/tree/master/examples/app_commands
Buttons, dropdowns example: https://github.com/Pycord-Development/pycord/tree/master/examples/views
Whats this error i get with a select component:
"Dropdown" object has no attribute "to_components". i think its pycord thingie because i never wrote "to_components" anywhere in my code.
show code
hold on logging in to pc
by the way, you can somehow increase the processing time of the command in slash. And then often "The application does not respond" appears
await ctx.defer()
class ServicesDropdown(discord.ui.Select):
def __init__(self):
options=\
[
discord.SelectOption(label="Google", description="Descriptive texts."),
discord.SelectOption(label="Yandex", description="High quality & large images.")
]
super().__init__(
placeholder="Choose a service...",
min_values=1,
max_values=1,
options=options,
row=0
)
def fix_selection(self):
service_name = self.view.service_name
for option in self.options:
if option.label == service_name:
option.default = True
else:
option.default = False
async def callback(self, interaction):
old_service = SERVICES.get(self.view.service_name)
new_service = SERVICES.get(self.values[0])
self.view.on_service_change(old_service, new_service)
self.view.search_btn.style = discord.ButtonStyle.green
self.view.search_btn.disabled = False
self.fix_selection()
await self.view.response_interaction.edit_original_message(view=self)
this is something you could wrap up into a View subclass along with your other components to keep everything clean and readable
its actually inside another view so
so its used in two views?
you didnt have to wrap them in a class though
iirc i did that because of this fix_selection thing
when i edited the message it would reset select's value
you could just have that as part of the view class as a private method
await a.edit(embed=embed)```
how to do it correctly?
anyway so my issue is actually something to do with insides of pycord i guess because as i said there isnt any "to_components" in that example
drop the variable assignment and dont even try to edit it and youre good to go
await ctx.defer() and await ctx.followup.send()
or just await ctx.respond()
the followup part isnt necessary as respond handles that
he literally just wanted to increase the processing time
ok, cool
how do I make the callback work even after restarting the bot?
class JoinButton(discord.ui.Button):
def __init__(self):
"""."""
super().__init__(
label="test",
style=discord.ButtonStyle.primary,
custom_id="join",
)
async def callback(self, interaction: discord.Interaction):
pass
?tag ex
Bot examples: https://github.com/Pycord-Development/pycord/tree/master/examples
Slash command/context menu examples: https://github.com/Pycord-Development/pycord/tree/master/examples/app_commands
Buttons, dropdowns example: https://github.com/Pycord-Development/pycord/tree/master/examples/views
example of persistent view is provided
@commands.Cog.listener()
async def on_ready(self):
"""
This method is called every time the bot restarts.
If a view was already created before (with the same custom IDs for buttons),
it will be loaded and the bot will start watching for button clicks again.
"""
# We recreate the view as we did in the /post command.
view = discord.ui.View(timeout=None)
# Make sure to set the guild ID here to whatever server you want the buttons in!
guild = self.bot.get_guild(...)
for role_id in role_ids:
role = guild.get_role(role_id)
view.add_item(RoleButton(role))
# Add the view to the bot so that it will watch for button interactions.
self.bot.add_view(view)
I found this
sure that works
view = discord.ui.View(timeout=None)
buttons = [Button1, Button2, Button3, Button4, Button5, Button6, Button7, Button8, Button9]
for i in buttons:
view.add_item(i())
self.bot.add_view(view)
I somehow need to go through all the buttons every time?
upd; does not work.
I need all the buttons to work again after restarting
Is there any way to convert all slash cmds to only for a specific guild and update instantly
Like in one place
For development
But then on the production bot, it will be global
debug_guild kwarg
@crimson gale and for my question? how can I put a callback back on all the buttons? I never figured it out
raise TypeError(f"Expected TextChannel, VoiceChannel, DMChannel or Thread not {type(channel)!r}")
TypeError: Expected TextChannel, VoiceChannel, DMChannel or Thread not <class 'discord.channel.VoiceChannel'>
hmm what this ?
its a VoiceChannel but not a VC at the same time ?
im trying to get a message in a VC chat bu msg id
Alright thanks
But I cannot seem to find it in the commands.bot docs
By the way, if it is set to an empty list, will the slash cmds still be global?
omit the kwarg to make them global
set it to None
then global
or that
this though any idea
it actually never checks for VC
Alright thanks
#989929962410754098 anyone
How can i start listening to an on_message event after issuing a slash command ?
I am trying to make a command so that it initiates the session with a chatbot
oh and its a cog
class Cleverbot(commands.Cog):
def __init__(self, bot):
self.bot = bot
chat = discord.SlashCommandGroup(name="chat", description="Chat with Cleverbot")
@chat.command(name="start", description="Start a chat session with Cleverbot")
async def _start(self, ctx: discord.ApplicationContext):
await ctx.respond("Chat session has **started**. Send a message to start chatting...")
@chat.command(name="stop", description="Stop the chat session with Cleverbot")
async def _stop(self, ctx: discord.ApplicationContext):
await ctx.respond("Chat session with Cleverbot has **stopped**. Goodbye 👋")
# @commands.Cog.listener()
# async def on_message(self, message: discord.Message):
# if message.author.bot:
# return
# await message.channel.send("Yo this message from the listener")
```Its with cleverbot api
how to make slash and prefix on one command
TypeError: document must be an instance of dict, bson.son.SON, bson.raw_bson.RawBSONDocument, or a type that inherits
from collections.MutableMapping
What does this mean?
import discord
from pymongo import MongoClient
from discord.ext.commands import slash_command
from discord.ext import commands
from discord.ext.commands import Cog
class Suggestions(discord.ui.Modal):
def __init__(self,bot,*args, **kwargs) -> None:
self.bot = bot
super().__init__(*args, **kwargs)
self.add_item(discord.ui.InputText(label="Your Suggestion: ", style=discord.InputTextStyle.long))
async def callback(self, interaction: discord.Interaction):
m = await interaction.response.send_message("Suggestion send!", ephemeral=True)
suggest = discord.Embed(title=f"Suggestion by {interaction.user} Under Review ",color=discord.Color.blue())
suggest.add_field(name="Your Suggestion: ", value=self.children[0].value)
suggest.set_footer(text=f"Message id: {m.id} ")
channel = self.bot.get_channel(987396375069224960)
embed = await channel.send(embed=suggest)
await embed.add_reaction('☑')
await embed.add_reaction('❌')
db = self.bot.mongoConnect["FelBot"]
collection = db["FelBot"]
await collection.find_one({'_id' : m.id})
await collection.insert_one(m.id)
class Suggest(commands.Cog):
def __init__(self,bot):
self.bot = bot
@slash_command(name="suggest", description="suggestions")
@commands.cooldown(1,7200, commands.BucketType.user)
async def modal_slash(self,ctx: discord.ApplicationContext):
await ctx.send_modal(Suggestions(self.bot, title="Suggestion"))
def setup(bot):
bot.add_cog(Suggest(bot))```
This is my code
I am hosting mongodb localy
PLEASE KEEP THIS CHAT SANE
Ah I don't know much about mongo but that looks like it'll probably be something to do with this
monogo is likely expecting a dictionary or json of some sort
What line is the error on?
I think its on the await insert line
Again idk how mongo works so take what im saying here with a grain of salt
have you tried inserting {"_id": m.id} like you did to find one?
wym
instead of await collection.insert_one(m.id) try await collection.insert_one({'_id': m.id})? I have no idea though I'm just spitballing
I already have that the line above
No you have find_one.
can I see the full traceback?
sure
getting traceback now
Traceback (most recent call last):
File "C:\Users\jackd\Documents\Felbcord Py.venv\lib\site-packages\discord\ui\modal.py", line 260, in dispatch
await value.callback(interaction)
File "C:\Users\jackd\Documents\Felbcord Py\Modals\Suggestions.py", line 25, in callback
await collection.insert_one(m.id)
File "C:\Users\jackd\AppData\Local\Programs\Python\Python310\lib\concurrent\futures\thread.py", line 58, in run
result = self.fn(*self.args, **self.kwargs)
File "C:\Users\jackd\Documents\Felbcord Py.venv\lib\site-packages\pymongo\collection.py", line 600, in insert_one
common.validate_is_document_type("document", document)
File "C:\Users\jackd\Documents\Felbcord Py.venv\lib\site-packages\pymongo\common.py", line 512, in validate_is_document_type
raise TypeError(
TypeError: document must be an instance of dict, bson.son.SON, bson.raw_bson.RawBSONDocument, or a type that inherits
from collections.MutableMapping
@tropic fractal
omg
after 3 fricking days
of trying
to fix it
ITS FIXXED, TYSM!
np
okay now i need to do the thing i was actualy storing the message ID for.. (I need help.. sorry)
Yeah idk mongo so you're on your own there, unless someone else helps you out here
Most of this part isnt about mongoDB, I just want to create a suggestion accept slash command so
/suggestionaccept (MessageID) (Rename Embed Title)
Please keep politics out of help i beg you
this is the only sane place in thsi entire server
please keep it sane
just keep this chat normal for support bru
A lot of libraries now have their own individual diversities. Just try some out and see which ones throw the least errors with your existing code I guess 🤷
dpy is really similar to pycord since pycord is a fork
this is helpful too
I mean dpy is cool and all but eh I wouldn't personally use it
its the reason why I use pycord
I've used them all and NAFF is actually superior to them all.
emretech's one
and it's not a fork.
to be frankly honest
I'd just use the raw discord api
no wrapper
because im a rebel

I heard disnake is great
dpy is fine if you have an existing dpy bot, but personally i hate the tree commands structure it uses
I was going to switch back to discord.py when it started being worked on again but I quite like how pycord handles slash commands so I decided against it
now pycord did the same lol
same 👍
what are the actual advantes of pycord over dpy?
different ways of doing very similar things - solely preference
i mean besides being alive, that's why i started using it

