#Basic Pycord Help (Quick Questions Only)
1 messages · Page 49 of 1
using ctx.edit ofc
But not quite sure if you can edit a message to remove the file?
if you can do it on client, it's probably possible
user = ctx.bot.get_user(1059358812051603576)
embed.set_image(url=user.avatar)
await ctx.edit(file=None, embed=embed)
what is the issue?
file=None returns the error
what is the error
Ignoring exception in command summon:
Traceback (most recent call last):
File "C:\Users\DolyPC\PycharmProjects\DiscordIconsBot\venv\lib\site-packages\discord\commands\core.py", line 124, in wrapped
ret = await coro(arg)
File "C:\Users\DolyPC\PycharmProjects\DiscordIconsBot\venv\lib\site-packages\discord\commands\core.py", line 980, in _invoke
await self.callback(ctx, **kwargs)
File "C:\Users\DolyPC\PycharmProjects\DiscordIconsBot\main.py", line 88, in summon
await ctx.edit(file=None, embed=embed)
File "C:\Users\DolyPC\PycharmProjects\DiscordIconsBot\venv\lib\site-packages\discord\interactions.py", line 415, in edit_original_response
params = handle_message_parameters(
File "C:\Users\DolyPC\PycharmProjects\DiscordIconsBot\venv\lib\site-packages\discord\webhook\async_.py", line 672, in handle_message_parameters
"value": file.fp,
AttributeError: 'NoneType' object has no attribute 'fp'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\DolyPC\PycharmProjects\DiscordIconsBot\venv\lib\site-packages\discord\bot.py", line 1114, in invoke_application_command
await ctx.command.invoke(ctx)
File "C:\Users\DolyPC\PycharmProjects\DiscordIconsBot\venv\lib\site-packages\discord\commands\core.py", line 375, in invoke
await injected(ctx)
File "C:\Users\DolyPC\PycharmProjects\DiscordIconsBot\venv\lib\site-packages\discord\commands\core.py", line 132, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'NoneType' object has no attribute 'fp'
hmm try files=[]
instead of file=None
Cool
nope no change
I’m sorry, I do not know.
what if you pass attachments=[], try that
this actually worked. no idea why files dont work
It's explained in the docs
I have another question. What determines the order in which users are in ctx.guild.members
No specific order
If I call a modal in a button callback, how would I wait for the modal to be finished? Especially using Modal.wait().
send the modal, in the button callback, use await modal.wait() and the you will get the input from modal.children[0].value
dont forget to send a response in the modal callback
It's in a cog, and using await modal.wait() resulted in this error: TypeError: Modal.wait() missing 1 required positional argument: 'self'
how are you defining modal?
also are you doing Modal.wait ?
you have to use wait on the modal object, not the class
You mean this part?
def __init__(self3, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)```
I used await start_modal.wait() in the button callback.
there is a few things wrong with that code 
1st- dont name classes in snake case
2nd- why self3 
3rd- i have a fear you are naming the object same as the class
no i meant how do you create the modal object
in the button callback
I'm unfamiliar with the term snake case. I used self3 because in earlier experiments I tried to access a function through the cog's self, which clashes with the Modal's self if you name them the same.
snake case is snake_case. Class names should be camel case: CamelCase
Ah, that makes sense.
this_is_snake_case
ThisIsCamelCase
I tried to access a function through the cog's self, which clashes with the Modal's self if you name them the same.
wat 
everything else in Python should be snake case. Constants however should be SCREAMING_SNAKE_CASE
What is the precise definition of constants?
like MAXIMUM_PLAYER_COUNT which is not going to change throughout the program
a value which should not change during runtime
python doesnt have a constant
its you as a dev who has to remember to not assign smth to it while coding
Like if you'd need the bot's user, I'd use self.bot for that in a cog. But if that's in a button's class, and you use self instead of self2 there, it'll result in an error, because the button's class doesn't have a user attribute.
how does pycord change image size in embeds?
discord does
are you defining ui models inside the cog?
you can get bot instance from interaction.client btw
self3 indicates a button thingy in a modal in a cog.
why do soo many people keep doing this 
a lot of unccessary nesting
so no easy way to get a consistent user icon size with displaying an image?
i think you can set height and width right
embed.set_image(url=iconuser.avatar, width=256, height=256)
height and width are not recognized as arguments
i could not find other ways
I put the class inside a function, because it uses a list that's passed to the function from another function.
maybe ill try to use a thumbnail instead
use the class init
nesting classes gives you fucked up bugs and errors
nesting classes might be useful sometimes, but not usually.
only if yk what you are doing. which you rarely do 💀
I admit I barely know what I'm doing with Modal Dialogs and all that stuff, so I'll gladly take any tips that'll make the process easier. 👀
I'm trying to see everything that's possible with them for now.
nesting a subclass is rarely ever done.
Then would I place the Modal's class between the imports and the cog's class?
it should be in the same scope as the cog
i think yes
if i understood what you meant correctly
Honestly what I said doesn't even make sense to me. 🤔
If the class is not inside the function, how will I pass lists to the modal and buttons and back?
pass it through init
I suggest learning more about oop in python
Then you yourself would understand what to do
How can a user command take input, can i pop up a modal and handle it that way?
and re: that, if so, is there some pre-made facility to do that or do I have to write a modal view/callback for each command
What's the reason behind that a music 24/7 bot stops playing after a while?
That is literally impossible to know without seeing any code or error messages
That's like asking "why does my car not work?" without explaining what's wrong or showing your car.
Is it possible to have a task always run on a specific date? For example always on the first day of a month?
I know you can specify a list of times to run it, unsure if it works for days of the month
@tasks.loop(time=[datetime.strptime('12:00AM', '%H:%M%p').time(), datetime.strptime('12:00PM', '%H:%M%p').time()])
...
This example would run at 12AM and 12PM every day
That's kinda what I'm using currently.
Having it run daily to a specific time and then checking manually if it is the first of a month, so it just works for debugging purposes.
Was wondering if there is a nicer way to do it cause it kinda looks weird 😅 😂
.rtfm audio
discord.PCMAudio
discord.PCMAudio.cleanup
discord.PCMAudio.is_opus
discord.PCMAudio.read
discord.AudioSource
discord.AudioSource.cleanup
discord.AudioSource.is_opus
discord.AudioSource.read
discord.FFmpegAudio
discord.FFmpegAudio.cleanup
discord.FFmpegAudio.is_opus
discord.FFmpegAudio.read
discord.FFmpegPCMAudio
discord.FFmpegPCMAudio.cleanup
discord.FFmpegPCMAudio.is_opus
discord.FFmpegPCMAudio.read
discord.sinks.AudioData
discord.sinks.AudioData.cleanup
discord.sinks.AudioData.on_format
discord.sinks.AudioData.write
Hello all, I am trying to send a zip file I have created to a discord channel. I've made it a discord file however getting this: discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: expected str, bytes or os.PathLike object, not ZipFile
how are you sending the file
and how did you get my_zip ?
Using the zip functions in python but if you give me 10 minutes I'll send the code. Just need to leave quick
import zipfile
with zipfile.ZipFile("test.zip", mode="w") as archive:
for file in glob.glob('sent/*.ytd'):
discord_prep = discord.File(file)
uniforms.append(discord_prep)
archive.write(discord_prep)
print("-- File to Send --")
print(file)
print("- File to Send Array -")
print(uniforms)
# Used to be sleep for 10
await discord.asyncio.sleep(2)
print(uniforms[0])
await ctx.send(
file="test.zip"
)
Error: Application Command raised an exception: TypeError: stat: path should be string, bytes, os.PathLike or integer, not File
trying to stream music from youtube to the voice channel using a Lavalink node, but when I satrt the bot I get this error "Connection Failure: 500, message='Invalid response status', url=URL('https://lavalinkinc.ml:443')" . Where can I find other lavalink nodes?
Streaming from YouTube is against ToS
mhh so no music bots at all anymore?
You can make a music bot, but you can't stream from a service that doesn't allow you to
and you obviously can't stream music you don't have rights to
Any advice on how to connect Bot with MongoDB database? IIRC you just have to pip install motor since pymongo and pymongo[srv] are included?
And for import in my .py file i have
from motor.motor_asyncio import AsyncIOMotorClient but it say that following marked area "mongodb+srv" isnt defined and throw an error.
async_client = AsyncIOMotorClient(**mongodb+srv**://xNiKERAGEx...)
so I can only stream my own music from local files, isn't it?
Basically, unless you find some royalty-free online service that lets you legally stream from it
ok, perfect, but how?

Do I need the lavalink thing?
What is with Spotify?
same
This would also apply to online services
I think you can use SoundCloud
But tbf pycord doesn't enforce tos. Its upto the bot devs to use what they want
in plain text
?? What about Unbel. And Mee they're using it too?
What 403 forbidden mean and how can i error handle it
If you see a bot using it, you can report it to Discord. Mee6 is known to slither around Discord's ToS anyways so it's not surprising.
But it doesn't change the fact that it's against ToS. A lot of developers lost their bot's verified status because they had music streaming on them
In codeblock or pastebin
at this point anything
What 403 forbidden mean and how can i error handle it
Hah
Posting the same question twice doesn't increase response time
should be something like
except Forbidden:
# do smth
@everyone this is not @everyone ping but i need help 😎
code
await user.send(embed=senimase)
review_channel = bot.get_channel(c.review_channel)
if str(ratings) == "1":
print("one")
stars = "⭐"
elif str(ratings) == "2":
print("two")
stars = "⭐⭐"
elif str(ratings) == "3":
print("three")
stars = "⭐⭐⭐"
elif str(ratings) == "4":
print("four")
stars = "⭐⭐⭐⭐"
elif str(ratings) == "5":
print("five")
stars = "⭐⭐⭐⭐⭐"
messagess = discord.Embed(
title="Review",
description=f"**Services Provided:** {role_ping}\n\n**__Freelancer__**\n{ctx.author.mention}\n\n **Review by**{user.mention}\n {stars} \n{user_review.content}",
color= discord.Color.green(),
timestamp=datetime.datetime.utcnow()
)
messagess.set_footer(text="• Xlereaon Services")
await review_channel.send("stop reading this and solve my error")
Error
Command raised an exception: UnboundLocalError: cannot access local variable 'stars' where it is not associated with a value
So did any of you guys connected a MongoDB to your bot? I guess sqlite is better?
What do you mean by "better"?
he is taking opinion
The error explains itself
I like mongodb just learn the basics
i dumb to understand it im new to python
You should use whatever suits your use case the best. There is no "better" option, only more suitable.
Read rule 1 in #help-rules
More user friendly, better overview, at least IDK whats crucial for a "good" database. I just heard sqlite is most commonly used so i thought of that its better
Tbh SQL is better for discord bots as discord data is relationally structured
ok....
it's funny because discord uses non-sql things
Yeah, it depends on what you want to store and what you're more comfortable with. If you prefer mongoDB, then use mongoDB.
they used to use mongodb then switched to casandra
You should pick whichever one you like using the best. If you find sqlite easier than mongodb, then use sqlite.
Cassandra is only really necessary if you're experiencing the amount of traffic Discord has imo
aka millions of messages every week
*Minute
I already choose mongodb but i can really understand why people are just storing data in .json files
Yeah but json sucks as a db
😄
?tag nojson
Why not to use json files for data storage
JSON files are commonly used to store data that is read by a program, however, they are unsuitable for storing dynamic data due to a number of reasons.
It is recommended to use a DBMS (Database Management System) as they come with optimized technologies for storing and retrieving information.
Advantages of using a database:
- Database tables can be related, making it easy to separate your information into multiple tables and only fetch what you need
- Databases allow you to use a query/data processing language to make complex data operations easier with less code
- One misplaced character will corrupt an entire file. A database very rarely experiences corruptions due to their automatic handling of data integrity
- Transactions in SQL databases allow you to revert unwanted changes and prevent data corruption in the case of an error
- Databases have support for indexes, allowing retrieval of some data to be extremely fast
- It is very easy to update existing data in a database, as opposed to re-writing a file
- Databases are reliable
Popular database management systems:
- SQLite3 (File based, no need for a server setup, SQLite is the most used database engine in the world)
- MongoDB (Stores data in documents a similar manner to JSON format, easy for beginners)
- PostgreSQL (Very popular and robust SQL based database management system)
- MySQL (Another popular SQL based system, good start for learning SQL)
What issues are you having with using mongo?
Command raised an exception: UnboundLocalError: cannot access local variable 'stars' where it is not associated with a value
what does this error even mean?
Read rule 1 in #help-rules
scopes tbh
omg bruh ;-; i just quick help
No issues at all. I guess its just a bit harsh for setup. I watch the third video now the other ones were not very helpful.
I know its better to store things in DB thats why im changing to it, but yk its like being clinging to your habits.
Doesn't matter if it's "quick help". You still need to know Python to use PyCord
Your question is easily solved by learning the basics of Python
:/ uhhh .... your "helper" so can i get help? for my query
Yeah, setup part I can resonate with you, but I find that it gives considerable benefits in the long run. Looking back I'd prefer dealing with database setup at the beginning, rather than headaches with errors and other issues in the later stages, e.g, explained in the dyno tag.
PyCord
that's a new one
we are helpers and we would have to follow certain guidelines too
I "help" people who follow the rules
If you want a helper which doesn’t contradict ask chatgpt lol but doesn’t expect learning anything from it
it useless
Yes I’m sure it’s worth it
did you install mongo[srv]
Not useless but you’re just not learning coding from it. The code which is supplied is good (most likely)
or something like that
or something a failure just like me
the provided code given by chatgpt doesnt works 90% of the time
Can’t relate
Because when asking a coding question you're expected to understand the answer, not just copy/paste and hope that it works
it's of course not just going to give you a complete answer
i dont copy/paste but still an AI cant replace programmers
that likely will change one day
"Replacing programmers" and "responding to a question" is not the same thing
Right now ChatGPT is a great tool for developers to figure out tedious/difficult obstacles
I do use EnfusionScript for a Game im modding for and i was very surprised about the good code it supplies. Ofc you have to change something here and there but especially for difficult calculations its very good
will you atleast explain me my error 😂
there's something called a local variable and a global variable
It means you're trying to reference a variable that hasn't been assigned a value in the scope you're trying to access it
AI can’t replace humans entirely. For example, sports. It wouldn’t be interesting to watch robots try and tackle into each other and always know where the ball is, since they’re preprogrammed. Humans have discretion, AI will only have preprogrammed things to do and say, while we can make a decision on the circumstances. So I think AI won’t be able to replace humans entirely, and I hope not at all.
I have some magnets ready in case a robot tries to take over my house 
AI will only have preprogrammed things to do and say, while we can make a decision on the circumstances.
I guess it's kind of pre-programmed if trained on current data
Exactly, that’s why robots/AI taking over the world is stupid and won’t happen if the decision is left up to people that are actually smart and not dumb.
We will ultimately be street-smarter than AI.
AI can also learn by itself
can bots log forum channel messages atm
?tag tias
how to add default permission to a slash command group (example please)
on_message doesnt trigger on a forum message
Unless I ping the bot
That means you don't have message content intents
on_thread_create, await thread.join()
Thanks!
.rtfm discord.Thread.
discord.Thread.invitable
discord.Thread.is_news
discord.Thread.is_nsfw
discord.Thread.is_pinned
discord.Thread.is_private
discord.Thread.join
discord.Thread.jump_url
discord.Thread.last_message
discord.Thread.last_message_id
discord.Thread.leave
discord.Thread.locked
discord.Thread.me
discord.Thread.member_count
discord.Thread.members
discord.Thread.mention
discord.Thread.message_count
discord.Thread.name
discord.Thread.owner
discord.Thread.owner_id
discord.Thread.parent
🏓
.rtfm SlashCommandGroup
discord.SlashCommandGroup
discord.SlashCommandGroup.add_command
discord.SlashCommandGroup.after_invoke
discord.SlashCommandGroup.before_invoke
discord.SlashCommandGroup.call_after_hooks
discord.SlashCommandGroup.call_before_hooks
discord.SlashCommandGroup.callback
discord.SlashCommandGroup.can_run
discord.SlashCommandGroup.cog
discord.SlashCommandGroup.command
discord.SlashCommandGroup.cooldown
discord.SlashCommandGroup.copy
discord.SlashCommandGroup.create_subgroup
discord.SlashCommandGroup.dispatch_error
discord.SlashCommandGroup.error
discord.SlashCommandGroup.full_parent_name
discord.SlashCommandGroup.get_cooldown_retry_after
discord.SlashCommandGroup.has_error_handler
discord.SlashCommandGroup.invoke
discord.SlashCommandGroup.invoke_autocomplete_callback
there is a check parameter in SlashCommandGroup but i am confused how to use it...
and i also tried default_member_permissions but it didn't worked ...
what doesn’t work?
condition didn't applied maybe i am writting it wrong...
def check(ctx: discord.ApplicationContext) -> bool:
pass #return a boolean
checks = [check]
can you please give example to check weather a user has manage_guild permission or not??
"example", more like code for you to copy/paste 
if you don't know the answer better not to question the question
.
just for that, I'm definitely not giving you an "example"
;-;
aa i am giving condition in commands now instead of group (i just to explore pycord function by adding permission into group itself)
anyways thanks for the check example
Hm, when I'm setting the thumbnail to a gif, it only shows the first frame
Do you use a url or gif as a file?
Url
Its weird because I have an Embed with a thumbnail gif
It's not just a reduced motion setting on Discord or something? GIFs should definitely work for thumbnails
Any ideas how to display
Username: value
Wert: value
Gutscheincode: value
if its stored in db['Gutscheine] like this:
inputs = {
'User' : str(member.id) ,
'Username' : str(member.name) +"#"+ str(member.discriminator) ,
'Gutscheincode' : Gutschein ,
'Wert' : wert
}
i tried show_all = collection.find_one() and print it but i dont want the User info nor the id.
I saw its possible to check filter but didnt understand the docs
print it manually ?
print(f"Username: {show_all['Username']}")
Or use a for loop to make it dynamic
I would not use Username
Use UserID
If you change your name, it will not find it anymore
Thx I’ll do that. Makes sense
Merci
Yeah I remember same for people who left. My ban conmand is also with id
How do I edit a message reply
This is what I want to edit: https://i.imgur.com/FjD4rLD.png
get the msg and edit it?
msg = await ctx.reply("")
await msg.edit(content="")
Thanks
The problem is that the there is also no error code at the console or something else
this is why you use logging?
If you can't provide any of that then there's no chance that anyone can tell you what's wrong
is there any way to apply this to my bot?
It could be anything from an issue with your code to your host being bad. We don't know
That's done automatically if you have global slash commands. You can't change it
the bot needs to be verified
And verification, yeah
aw man
its a private bot and some people are struggling to use slash commands
If it's a private bot it shouldn't be too hard to tell them how to use it then, no?
yeah but every1 keeps typing it out
use bridge commands?
even with a video tutorial posted
what is that
It's not like this would fix that issue anyways. This just shows the most used commands
Concept
I have that shut off
Is there a way to check if my bot has manage role permissions in a specific guild ?
.rtfm permissions_for
discord.Thread.permissions_for
discord.DMChannel.permissions_for
discord.TextChannel.permissions_for
discord.StageChannel.permissions_for
discord.ForumChannel.permissions_for
discord.VoiceChannel.permissions_for
discord.GroupChannel.permissions_for
discord.CategoryChannel.permissions_for
discord.abc.GuildChannel.permissions_for
.rtfm bot_has_permission
or this
thanks !
how do you know what is the permission number ?
for exemple what would be "manage role" number
read the docs
.tag discord.Permissions
Tag not found.
.rtfm discord.Permissions
discord.Permissions
discord.Permissions.DEFAULT_VALUE
discord.Permissions.VALID_FLAGS
discord.Permissions.add_reactions
discord.Permissions.administrator
discord.Permissions.advanced
discord.Permissions.all
discord.Permissions.all_channel
discord.Permissions.attach_files
discord.Permissions.ban_members
discord.Permissions.change_nickname
discord.Permissions.connect
discord.Permissions.create_instant_invite
discord.Permissions.create_private_threads
discord.Permissions.create_public_threads
discord.Permissions.deafen_members
discord.Permissions.embed_links
discord.Permissions.external_emojis
discord.Permissions.external_stickers
discord.Permissions.general
yes I am on that page already
or use the permissions calculator
guys, is there a way to send ephemeral messages from getting messages in on_message?
You can only send ephemeral messages to interactions
Component custom id cannot be duplicated
When I try to do emb = interaction.message.embeds[0].copy()
Full traceback?
Ah lol
How to make a button on timeout be disabled?
Learn all about implementing buttons in your Discord Bot using Pycord.
tyy
np
Um, what's the model for the member that used the select menu?
nvm i found it
Just fetch the images from the json file and use random.choice to pick one
If you've never coded before, you should not be making a Discord bot
read rule 1 in #help-rules
Hey guys, how can i edit a view in an ephemeral message? (with followup)
view.message.edit ?
thx
Indent it inside the cog
Yeah and call it like self.set_emoji_quiz(...)
No no
Not while defining it
While calling it
Outside the class. Some people like to put it in a separate file of thier own
No worries lol
self.bot
Use that
Inside the cog right
Accept self as the first parameter in the functions
It would be a good idea to revisit some oop tutorials on python
Can anyone copy/paste me an example of a user_command with a check for having a certain role?
?tag codeexamples
I don't think the docs are very clear how the checks parameter should work, doesn't seem like an unreasonable "quick question".
Oh wait. I think you have defined the functions in the cog but are calling them from the View
Am i right?
Is V3 stable enough for a Server with 50.000 Members?
member.send
while True:
def check_ratings(m: discord.Message):
if int(m.content) > 0 and int(m.content) <= 5:
return True
else:
user.send("I'm sorry, Please enter a number between 1 to 5") # getting error here
ratings = await bot.wait_for('message', check=check_ratings, timeout=None)
if (ratings.content).isdigit():
await user.send(embed=review)
break
print(ratings.content)```
userr.send("I'm sorry, Please enter a number between 1 to 5")
RuntimeWarning: Enable tracemalloc to get the object allocation traceback```
this is the error
are you using a def in a while 💀
user.send("I'm sorry, Please enter a number between 1 to 5")
await user.send("I'm sorry, Please enter a number between 1 to 5")
uh so how do i make it work?
def check_ratings(m: discord.Message):
if int(m.content) > 0 and int(m.content) <= 5:
return True
else:
user.send("I'm sorry, Please enter a number between 1 to 5")
while True:
ratings = await bot.wait_for('message', check=check_ratings, timeout=None)
if (ratings.content).isdigit():
await user.send(embed=review)
break
print(ratings.content)```
```RuntimeWarning: coroutine 'Messageable.send' was never awaited
user.send("I'm sorry, Please enter a number between 1 to 5")
RuntimeWarning: Enable tracemalloc to get the object allocation traceback```
can't use await in def
Rename the function to async def check_ratings
And then when you run it, you do await check_ratings(...)
@proud pagoda How do you got Helper Role?
okay
I helped people
Ig you do that actively
Yeah
What is this called again? I forgot the term for it
Embed_Fields: list = [Embed_Field[Data] for Embed_Field in Embed_Dict.get("fields") for Data in Embed_Field if Data != "inline"]
list comprehension
ty!
V3 is not even stable for a server with only itself
Give it about a year
Can you show the full file so i understand what's going on
If you're trying to timeout the server owner, you can't
I'm not
And for how long are you trying to time them out for?
i tried for like 1 minute to like a month and nothing worked
import discord
import aiohttp
import random
from discord.ext import commands
def random_number():
return str(random.randint(0,900))
class GuessThePokemon(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.slash_command(
name="guess_the_pokemon",
description="Begins a game of guess the Pokemon"
)
async def guess_the_pokemon(self, ctx, prize : str, channel : discord.TextChannel = None):
await ctx.defer()
if channel != None:
event_channel = self.bot.get_channel(channel.id)
else:
event_channel = self.bot.get_channel(ctx.channel.id)
async with aiohttp.ClientSession() as session:
pokemon_api = await(await session.get(f"https://pokeapi.co/api/v2/pokemon/{random_number}")).json()
pokemon = pokemon_api["species"]["name"]
embed = discord.Embed(
title = "Guess the Pokemon!", description = f"The first person to guess the Pokemon below receives the prize:\n**{prize}**", color = discord.Color.green()
)
embed.set_image(url=pokemon_api["sprites"]["front_default"])
await event_channel.send(embed = embed)
while True:
msg = await self.bot.wait_for("message")
if msg.content.lower() == pokemon.lower():
await event_channel.send(f"{msg.author} guessed right!")
else:
await event_channel.send(f"{msg.content} is wrong, the answer was: {pokemon}")
def setup(bot):
bot.add_cog(GuessThePokemon(bot))
anyone know why msg.content is always showing up empty?
Do you have message content intents?
yea
Enabled in both the code and the dev portal?
forgot about it in the code, thx
also why the while True? Your guessing game is never going to end?
both message intents?
some of the code was for testing only
Dude stop spamming your question
You've already posted here twice. and made a thread
Stick to the rules or leave
ok i deleted it
Move the functions you want inside the class you want to use them
Ig
You can get bot instance from interaction.client
Chat GTP just told me that "The Wix API is not available for Python, so it is not possible to use Python to create a custom endpoint for your server-side script on a Wix website." so its not possible to request a data from my Wix Website and display it in DC via my .py Bot?
That's not really related to Python or your bot at all, that's an issue with Wix.
You're better off asking their support, as this server has nothing to do with that.
Why not? Could be that there are other ways, like using the Beautiful Soup library.
But im not here to discuss so sorry if its offtopic for you, wont ask for it again.
You can always use Python to make requests to an endpoint, but supposedly "it is not possible to use Python to create a custom endpoint for your server-side script on a Wix website". So that's an issue with Wix, not Python or PyCord.
Do you have message content intents?
nope i didnt
thx, it works now 👍
Anyone have an easy way to send paginated embeds outside of an interaction? It seems like the built in paginator.send requires a ctx and paginator.respond requires a discord.Interaction, which makes sense.
What else is not a ctx or a interaction?
I've built an alert system which sends embeds to channels long after they've been set. So I fetch the channel from the channel id and send the embed using channel.send. It doesn't seem like a ctx is involved in any of that but I could be missing it.
How can I make a slash command that only works on servers not users dm??
.rtfm guild_only
tnx
guild.get_member is returning None these are my intents configuration:
i have both intents enabled on the dev portal too
does anyone know how to tell if a message has already had .delete() called on it
I have multiple conditions in an on_message listener that might lead to message deletion, it doesn't actually affect the bot but getting errors in console is kind of annoying
.rtfm on_message_delete
could you show the bot = ... code as well?
yeah I'm gonna store a list of deleted messages???? cmon.
I'm calling from within an on_message function, just need to be able to tell if the message is already deleted
try-except?
cancer but I guess it would work
works 👍 bit dumb but who cares I guess
aint nobody reviewing this code other than me 
if you still get it, than the bot cannot find the member
is guild.members empty?
How do I add the member intent to discord.Intents.default()
?tag intents
https://docs.pycord.dev/en/master/intents.html
https://discord.com/developers/docs/topics/gateway#gateway-intents
import discord
from discord.ext import commands
# Get specific intents for fine control
intents = discord.Intents()
intents.emojis = True
intents.guilds = True
intents.messages = True # Required for prefix commands!
...
# Get all non-priveliged intents; this excludes presences, members and message_content
intents = discord.Intents.default()
# Set priveliged intents: these must be enabled on dev portal
intents.members = True
intents.presences = True
intents.message_content = True # Required for prefix commands >= 2.0.0b5
# Get all intents; all intents must be enabled on dev portal.
intents = discord.Intents.all()
# Apply intents when creating your bot
bot = commands.bot(prefix="?", intents=intents)
In version 1.5 comes the introduction of Intents. This is a radical change in how bots are written. An intent basically allows a bot to subscribe to specific buckets of events. The events that corr...
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
How can i get the user who made the change on the on_guild_channel_update event? For example I would like to display the user who renamed a channel.
Get the last audit log
Thanks
.embeds
I've been trying to record conversation in a voice channel and I'm using discord.sinks.WaveSink(). When I iterate through sink.audio_data.items() in the callback I'm only seeing the first 5 minutes of audio. Is there something I need to do to get the full conversation?
WAV files are large. Is there a chance you might be running out of memory? try using MP3 sink
I'll try swapping sinks incase its a memory issue, wouldn't ogg be best then or is there a reason to use mp3?
well mp3 is the most widely used format for audio
but its upto you
Is there any problems running two instances of the bot to the same bot account? They both only use slash commands and technically dont have anything overlapping.
well yes. both accounts will get events
Including interactions
if bot instance 1 has f, a, b cmds
and bot instance 2 has f, x, y cmds
then
interactions for f, a, b, x, y will go to both
both instances will try and send a callback for f. the one with slower connection would fail
for a, bot1 will successfully process it, but since it would be missing in bot2, bot2 will try to remove it from discord. this can be averted if you set auto_sync_commands to false
do you mean sending a modal as a response to another modal?
no like after clicking button a modal shows up
to fill
yes
Here's the modal dialogs example.
example or docs
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
np 🙃
await value.callback(interaction)
File "C:\Users\يولين\Downloads\rwg.py", line 40, in callback
user_id = str(interaction.context.author.id)
^^^^^^^^^^^^^^^^^^^
AttributeError: 'Interaction' object has no attribute 'context'
@proud mason
interaction.user.id
kk
read the docs when 
@proud mason discord modals limited to 5 questions??
yes
also, dont ping members for help 
hey can anyone tell me what this error means? discord.ext.commands.errors.CommandInvokeError: Command raised an exception: UnicodeEncodeError: 'charmap' codec can't encode character '\u2665' in position 13749: character maps to <undefined>
full error?
age_group = "Unknown"
if member is not None:
print(role.name for role in member.roles)
if "18-21" in [role.name for role in member.roles]:
age_group = "18-21"
elif "21-51" in [role.name for role in member.roles]:
age_group = "21-51"
elif "100-900" in [role.name for role in member.roles]:
age_group = "100-900"
why doesnt this work. and stayes as "unkown" i have intents. in dashboard
any intents must be added in code?
@proud mason last thing istg
you have guild members intent, right?
in dashboard
https://docs.pycord.dev/en/master/intents.html
https://discord.com/developers/docs/topics/gateway#gateway-intents
import discord
from discord.ext import commands
# Get specific intents for fine control
intents = discord.Intents()
intents.emojis = True
intents.guilds = True
intents.messages = True # Required for prefix commands!
...
# Get all non-priveliged intents; this excludes presences, members and message_content
intents = discord.Intents.default()
# Set priveliged intents: these must be enabled on dev portal
intents.members = True
intents.presences = True
intents.message_content = True # Required for prefix commands >= 2.0.0b5
# Get all intents; all intents must be enabled on dev portal.
intents = discord.Intents.all()
# Apply intents when creating your bot
bot = commands.bot(prefix="?", intents=intents)
In version 1.5 comes the introduction of Intents. This is a radical change in how bots are written. An intent basically allows a bot to subscribe to specific buckets of events. The events that corr...
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
intents = discord.Intents.default()
intents.message_content = True
intents.members = True
that is my intents in cod
and you have those enabled on discord developer portal?
yh
and this aswell, i hope
ofc..\
just to be sure, well
bot = commands.Bot(
command_prefix=commands.when_mentioned_or("!"), intents=intents
)
at least, you can create one single list with all roles you need, instead of creating at everytime
and, you can print it out to check availability of all the roles
i tried but my brain glitched like
age = ["3333","33322","32211"] -- ID*S
now i want to check which one on users acc
WTV, just the point is how to check
same as you did before, but i suggest you making an variable with your id list
if ID in list
blah blah blah
kk
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: SSLError: HTTPSConnectionPool(host='steamcommunity.com', port=443): Max retries exceeded with url: /inventory/76561198055800013/730/2?l=english&count=5000 (Caused by SSLError(SSLError(1, '[SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:992)')))
how do i fix this?
@simple canopy yo
#help-rules
where is the docs for this
Pycord is a modern, easy to use, feature-rich, and async ready API wrapper for Discord. Features: Modern Pythonic API using async/ await syntax, Sane rate limit handling that prevents 429s, Command...
if you have an member object, you don't need it
but in general, yes, it's one of the ways to get it
it's not cached then
do you have intents?
either it's not on guild anymore, or it fails to cache it
im the user running the cmd in the guild , so not that, how to fix the failure tho
ya\
code and website?
give full code
import discord
from discord.ext import commands
import json
intents = discord.Intents.default()
intents.message_content = True
intents.members = True
bot = commands.Bot(
command_prefix=commands.when_mentioned_or("!"), intents=intents
)
@bot.slash_command()
async def information(ctx, user_id: str):
try:
member = ctx.guild.get_member(user_id)
age_group = "Unknown"
if member is None:
print("Member object is None")
if member is not None:
print([role.name for role in member.roles])
if "18-21" in [role.name for role in member.roles]:
age_group = "18-21"
elif "21-51" in [role.name for role in member.roles]:
age_group = "21-51"
elif "100-900" in [role.name for role in member.roles]:
age_group = "100-900"
the rest is not valuable.
yup
not it shouldn't
cuz i got the error 'enter right int
well, tbf
you can replace it with discord.Member
instead of str and id at all
this will do
there is an Member option type, so you can basically select members ifp
if it doesn't work, try following documentation on discord.Option and examples from github repo
I have the same
see what i said above
i hope it'll work
How can I make a prefix for a bot that will respond to both a large and a small letter
make 2 prefixes
case_insensitive=True
the docs are too complicatedd
no?
like fr everything is mixed together
you don't need an source code
Models are classes that are received from Discord and are not meant to be created by the user of the library. Attributes key, url. Methods def is_animated, async read, def replace, async save, def ...
can u say how to get the ID 💀 cuz wtf isReturns the length of the CDN asset’s URL.
dady gigabite
or gigachad
yk the way i be learning from you is the same from docs, i just not comfortable with the docs pycord, is giving. i came accross alot of docs. but the better i saw was easy. this one is complicated, not straight to point, and just ....
you would actually be saving my time, and doing your job, your not even spoonfeeding
and ill be happy
and kiss u
Pycord is a modern, easy to use, feature-rich, and async ready API wrapper for Discord. Features: Modern Pythonic API using async/ await syntax, Sane rate limit handling that prevents 429s, Command...
Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - GitHub - Pycord-Development/pycord: Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API
Rtfd 💀
we are just trying to say
that you gotta learn stuff yourself
to do stuff
we can't just spoonfeed everything to you
can u just answer this thing for me and ill never ask again.
try to, at least, try to read
i thought thats what "BASIC PYCORD HELP" CHANNEL MADE FOR,
NOT spoonfeeding, is im asking how to call the userid from discord.member
a aint asking you to code a bot
i did
..
Wtf did you do 💀
member = ctx.guild.get_member(discord.Member.id)
age_group = "Unknown"
if member is None:
print("Member object is None")
if member is not None:
print("roles", [role.name for role in member.roles])
if "18-21" in [role.name for role in member.roles]:
age_group = "18-21"
elif "21-51" in [role.name for role in member.roles]:
age_group = "21-51"
elif "100-900" in [role.name for role in member.roles]:
age_group = "100-900"
with open("users.json", "r") as f:
users = json.load(f)
.^.
am i really that dumb
💀
Here's the slash options example.
I'm trying to get my user id and write it into mysql db.
The problem occurs at the moment when I try to write this data (31-34). It writes random id into db (2147483647), but i need to write my user id (1003694956919148625). Any ideas?
class MyModal(discord.ui.Modal):
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.add_item(discord.ui.InputText(label="Name"))
self.add_item(discord.ui.InputText(label="Gender"))
self.add_item(discord.ui.InputText(label="City"))
self.add_item(discord.ui.InputText(label="Description", style=discord.InputTextStyle.long))
async def callback(self, interaction: discord.Interaction):
id = interaction.user.id
print(id)
cursor = connection.cursor()
cursor.execute(
"INSERT INTO users (id, name, gender, city, description) VALUES (%s, %s, %s, %s, %s)",
(id, self.children[0].value, self.children[1].value, self.children[2].value, self.children[3].value)
)
connection.commit()```
In console print id is correct
But in db - it isn't

SAME SHIT IM DOING BUT WITH JSON
use json its lifesaver
JSON is a convenient and easy-to-read data storage protocol that's widely accepted by most programming languages. However, we caution against its use for storing and retrieving data in an asynchronous environment like a Discord bot. Don’t use json!
- It's a file-based data storage, which makes it vulnerable to race conditions
- You'll need to implement your own synchronization primitives to avoid corrupting data
- If you're not careful, you could accidentally wipe your entire JSON file.
Solution? Use a database. Recommended schema are SQLite, PostgreSQL, and MongoDB.
- Async libraries exist on pypi for each of these
sqlite --aiosqlite(or Danny's wrapper,?tag asqlite)
postgresql --asyncpg
mongodb --motor - Databases organize your data into tables, and are fast at inserting, retrieving, and removing records
- You can impose uniqueness constraints to ensure against duplication
- The Python libraries enforce synchronization for you
- The query language is intuitive, you can get running with simple queries in just a few hours!
if u have a good hosting, encryption, you dont have to worry.
Well does it matter then 
SQL is not that hard
yeah man, just use sqlite
mehalready coded json
well, when that blows up, remember sqlite
nver blowin up
Also, don't assign values to id in python
It is a built in function that can give you fucked up bugs down the road. Call it user_id or smth
Also, use an async driver
oh, so don't use sqlite3?
💀
using sqlite 3
complicated stufffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
i meant to reply stanislav
He is using MySQL
Also yes, do not use sqlite3
Use asqlite or aiosqlite
Or straight up use an ORM
huh
hmm, well I know what I'm doing this morning then
if our economy.db blew up everyone would kill me
Daily backups? 👀
uh.. yes... of course..
lie detect
u should be a helper
Om is very helpful
Ty 🙃
Tell that to lala and Bob
How does the checks parameter work on a user_command? I'm not entirely sure what to do with it.
GUYS
I FIXED THIS SHIT
ALTER TABLE users MODIFY COLUMN id VARCHAR(255);
ALTER TABLE users MODIFY COLUMN name VARCHAR(255);
ALTER TABLE users MODIFY COLUMN gender VARCHAR(255);
ALTER TABLE users MODIFY COLUMN city VARCHAR(255);
ALTER TABLE users MODIFY COLUMN description VARCHAR(255);
And all is fine now
LOOOOOL
I spent all day on this
why VARCHAR 💀
especially id
should be BIGINT tbh
How can check if a option of a slash command has been used?
Wdym? Do you want to check if a non-required option has any value?
do you guys know how do i edit the response i tried await ctx.edit("Test 2") but i got this error: TypeError: edit_original_response() takes 1 positional argument but 2 were given
content = “Test 2”
thx
How can I read a .env file in the .gitignore folder to pass a token?
I still get security warnings though for sharing my token 💀
what does your gitignore file look like?
uhh I've only seen a .gitignore file
not a folder.
ok, I tried to create a .gitignore.env file now, but I still get security warnings
what?
Is there a way to have a list of roles as input in discord.Option? Or do I have to have the user manually mention roles in a str input field?
discord.Role
You can not select multiple roles in one option if that's what you're asking
at that point just use a role select menu
True
yeah, but then it would be limited to 25 roles (select menu only can show 25 elements afaik)
nope, a role-select menu shows all roles in the server
interesting
you are thinking of a string-select menu
.rtfm role_select
1st one
ok, so, github ignores that now, and it works, but it gives me the error; "token must be of type str, not NoneType"
Here's the code;
load_dotenv()
TOKEN = os.getenv("DISCORD_TOKEN")
yes
but, well, with my actualy token
so what am I doing wrong? :/
Is your env file in the root folder of your project?
none of my files are in a folder even
here's the project on github; https://github.com/llamaair/FetchBotMain
Can you screenshot your env file, and blur out the token?
Also don't use json as a database
ok
are you using replit?
Switched over to what?
where are you getting the error, local machine, or host?
host
.^
Did you add your .env file to the host as well?
yeah
Your host probably handles environment variables in some weird way then. Not much we can do to help, contact their support
Try passing the location of the .env file to load_dotenv
Pass a relative location
And not an absolute location
how to add a cooldown to a interaction?
what does client's internal cache mean?
It means the internal cache managed by the library
just how you would to a prefix cmd?
Here's the cooldown example.
thanks for clarifying :)
no i mean to a view like a select menu
ah. i think you have to implement that yourself
okay
wait i think you can use pycord internal stuff to make things slightly easier
ok no it would be more difficult to use that lmao
What do persisent views do
A persistent view stays when you restart your bot
Here's the persistent example.
So it carry on working
Yes
embed = discord.Embed(
title="New Suggestion!",
fields=[
discord.EmbedField(
name="By", value=f"<@{user_id}>"
),
discord.EmbedField(
name="Suggestion", value=f"{self.children[0].value}"
),
discord.EmbedField(
name="Benifits!", value=f"{self.children[1].value}"
),
],
color=discord.Color.random(),
)
test = await interaction.response.send_message(embeds=[embed])
await test.add_reaction('👍')
await test.add_reaction('👎')
NO REACTIONS GETTING ADDED? <- error
using the slash_command decorator, the slash command just inherits the name of the function immediately afterwards, right? no way to do name=<whatever> like with @bot.command?
you can, like so (from discord.ext.commands)
@commands.slash_command(name="command_name")
async def function_name(self, ctx):
...
Interaction.response.send returns a InteractionMessage
.rtfm interaction.response
You need the message
oh sweet
i pull the command names from a list of vars at the top of the file (so I can change em easy), so nice that it works the same
Do you need the self? I thought it would just be def funcname(ctx)
no, sorry. self is if it's in a cog
it doesn’t have to be from discord.ext.commands all slash command decorators can
ah cool, kk
this is possible
since I use @bot.command already it seems like I probably should just be able to switch that to @bot.slash_command and pass in the allowed server list and have it function.. I think. you can also do ephemeral responses to slash_commands too, right
I havent messed w/ ephemeral messages yet
how are you planning to “pass in the server list”
I have a dict of serverids:channelids right now since I was using the old response method to do my commands. so I should just be able to pass in the keys to that dict
You can use ephemeral responses in slash commands in addition to other forms on interaction.
allowed_channels.keys() or whatever method
are you handling that in the command callback or in the decorator. If in the decorator, how?
I mean in theory I could just do something like..
if I have a dict = {serverid:[channelids]}
the decorator could just be
@bot.slash_command(guild_ids = dict.keys())
def stuff here
at least thats what I would think
ah ok.
I'm not sure on the channel thing - I'm just doing a check if msg.channel.id is in dict[msg.guild_id], but maybe there's some prettier way to make a command only in one channel on a given server?
Like I said I did a partial rewrite of my bot that used the older on_message() way of doing things, eggdrop style lol
so some of the stuff on that bot carried over
.rtfm on_interaction
may be useful
yeah, I was just looking at some of the kwargs that can go with slash_command. checks keyword might be what I need there
But I'm not super worried about that until I get the new version up and going with the slash commands anyways
it mostly works now, but I have to find all the places that ints are getting turned into strings and recast them. it's been a fun little minefield :D
Yup. Honestly most of the issues I've had were with the game logic I wrote for the bot, and not the bot library itself. seems pretty intuitive
That’s the point :)
it's nice!
how can i make a button never expires, clickable by everyone
Here's the persistent example.
Here's the persistent example.
Do we have any example/showcase bots here? Digging through the api I"m kinda curious on how dialogs that accept input work on the discord user's end. dont remember ever seeing one of those
hmm cant understand can u explain
just a s a form
there should be one in #883236900171816970
I think the command is +modal test
?
persistent views would have no timeout and work after the bot restarts. This requires the view to have timeout=None and the view added to the bot's cache.
yeah I found it, /modaltest - not exactly what I was looking for tho :( What I'd love is for there to be a way to put a text box into an embed, where people could type a guess into the box and click a button to have it submitted for the round
Currently that is not a possibility.
Dunno if there's any functionality for an embedded one like that
Gotcha. That's okay, /guess 123 should work just fine, i just was thinkin that would be a kinda slick way to do it lol
My suggestion is to add a button that sends the modal.
that is not possible at all
Having a popup box is a little much for what I'm using it for, so i"ll just stick with a /guess command. I WAS using !guess 123 and having the bot delete the message (since I want the guesses to be private), but that's a little janky lol
alright
Is it possible to have a command group and use the groups name as a command (if that makes sense)?
For example, have both of these be a command?
/rank
/rank top
No
Okay thought so, wanted to double check. Ty!
./rank rank should work
My problem is people are used to !rank and I want to separate it out for its slash command by doing a /rank and /rank search, but I'm gonna have to do it as /rank top & /rank search instead I guess aha
print(f"We have logged in as ")
is there a way to add like a mention user to the bots would say we have logged in as bot#1234?
str(bot.user)
💀 Another one that didn't read them.
How can i use deleted = await ctx.channel.purge(limit=amount+1) to specifically only clear messages by bots?
https://docs.pycord.dev/en/master/api/models.html#discord.TextChannel.purge
You can use the check parameter.
Models are classes that are received from Discord and are not meant to be created by the user of the library. Attributes key, url. Methods def is_animated, async read, def replace, async save, def ...
Thank you
tysm just a squid
does anyone know how to make it in a command were u chose from the users on the server so like /idk user: then u put a name like that is that possible?
@fervent cradle how are u using ctx bc it won't work for me like are u using a different library or just a older python version?
what is your Python version?
how do i chnage it?
Do you have a runtime.txt file?
i don't think so
Create one in your bot folder, and type in either 3.8 or 3.10 in there
ok then how do i get ctx in there bc pip install ctx does not work
do i just type that?
Bruh
Are you trying to install ctx 🤣
yes
Please do learn python
i know it but i don't do stuff like this
i have been doing python for 3 years
ctx is provided by discord which is the namespace of pycord v2
You don't need to install it
oh ok
$ pip install py-cord
i used to code python on a web based ide but trying to do python on local host now
ty sorry i am acting like a idiot with this i know a good bit but installing libraries is new bc i just switched running it on my pc not the cloud
ty for helping me
ModuleNotFoundError: No module named 'discord.enums' what does this mean getting a error with not changing the code and the error is within the library bc i don't have 3k lines of code
discord.Option?
Sometimes stuff you do in your code can cause errors in the library
It doesn't necessarily mean the library is at fault
so should i restore it to the last save to see if that is the problem?
what is the best way to get a bool value from modal or a url (i mean restrict user from typing else)
Full error?
from ..enums import AppCommandOptionType, AppCommandType, ChannelType, Locale
ModuleNotFoundError: No module named 'discord.enums'
that is the error
Is it possible to extract the view from a message if you have the message ID? I know you can overwrite the view when editing a message, but can you pull the view out of a message, to add or remove things from the view?
What are you doing?
Or is that not your code but the library?
Show pip list
can you test a file with just
import discord
this line ^
It think there is View.from_message
.rtfm View.from
Yes ^
Sweet. Thanks so much
No worries 🙃
I had been looking in the docs under the message, didn't think to look under view
this is not normal something is wrong bc i installed this
what happens when you run it?
In embeds.0.url: Scheme "a" is not supported. Scheme must be one of ('http', 'https').
i am getting url from modal is there any way to stop user from typing something that is not url
error message
from ..enums import AppCommandOptionType, AppCommandType, ChannelType, Locale
ModuleNotFoundError: No module named 'discord.enums'
That could be a good pr tbh.
Message.get_view
That would call View.from_message
As I said, show pip list
wdym?
pip list in terminal
Package Version
aiohttp 3.7.4.post0
aiosignal 1.3.1
async-timeout 3.0.1
asyncio 3.4.3
attrs 22.2.0
certifi 2022.12.7
chardet 4.0.0
charset-normalizer 2.1.1
colorama 0.4.6
coverage 7.0.4
discord 2.1.0
discord.py 2.1.0
exceptiongroup 1.1.0
frozenlist 1.3.3
idna 3.4
iniconfig 2.0.0
multidict 6.0.4
numpy 1.24.1
packaging 22.0
peewee 3.15.4
Pillow 9.4.0
pluggy 1.0.0
pytest 7.2.0
pytest-cov 2.12.1
rand 0.3.0
requests 2.28.1
toml 0.10.2
tomli 2.0.1
typing_extensions 4.4.0
urllib3 1.26.13
yarl 1.8.2
you have discord.py not pycord --_--
You could use regex which should be the easiest. Or implement converters, but it can be complicated. You can use checks too but I'm not sure how
i guess you need to uninstall discord.py
pip uninstall discord discord.py
pip install py-cord
^
did that
I suggest you switch over
ok
ok, i thought there is something easy way 😅, same for numbers?
@proud mason what is the import for pycord?
Prefix cmds? For numbers you can just typehint int and library should handle iirc
import discord
it is white not cyan though
entry in modal
Ah. Regex is the way lol. The other stuff won't work
Restart ide
🥲 ok thanks for helping
What ide do you use? Vscode? Pycharm?
If you are developing python locally for the first time, use only 1 of those 2
vscode
That's fine
i get this error when i run it @bot.tree.command(name="hello", description="say hello to me")
AttributeError: 'Bot' object has no attribute 'tree'
.guide
should i remove the command tree
That's not how pycord implements app cmds
Read this thoroughly
ok i will tmr ty for helping i gtg
👍👍
I am trying to work on some persistent buttons. Basing some of the code off of the button role example, I have the bot on loading the cog find the appropriate message from my database, getting the message, extracting the view from it and then adding the view from the bot, but even though when I print out the view on the console, it tells me there are the correct number of items in the view, when I click on the buttons, they don't function like they did before the restart, And I have confirmed that they do function before restarting the bot.
Here is the code:
@commands.Cog.listener()
async def on_ready(self):
print("4e Cog Loaded")
# We recreate the view as we did in the /post command.
view = discord.ui.View(timeout=None)
engine = get_asyncio_db_engine(user=USERNAME, password=PASSWORD, host=HOSTNAME, port=PORT, db=SERVER_DATA)
async_session = sessionmaker(engine, expire_on_commit=False, class_=AsyncSession)
async with async_session() as session:
result = await session.execute(select(Global).where(
Global.system == "D4e"))
guild_list = result.scalars().all()
for guild in guild_list:
tracker_channel = self.bot.get_channel(guild.tracker_channel)
last_tracker = await tracker_channel.fetch_message(guild.last_tracker)
comp_list = last_tracker.components
print(comp_list)
view = discord.ui.View.from_message(last_tracker, timeout=None)
print(view)
self.bot.add_view(view, message_id=guild.last_tracker)
View.from_message does not give you buttons with callbacks
Well that would expalin it
You should rather subclass and create the view fresh for every guild
The problem I was running into with that is that the callback requires the application context to function, and I am running into the wall that I can't just recreate the buttons without the ctx
Is there a way to get the button with callback from the old message?
Hello again, one quick question: What is the best way to get the id of a slash command for mentioning it? For example I want to create a custom help command, where all the commands are clickable with the /name:cmd_id markdown. I thought about fetching a list of all the commands that are registered by the bot and looping through it to get the right one, but it would be even better if I could fetch just a specific command by name. Is there a function that does that?
what parts of ctx do you need? why not store them in a db
I could. That's definitely an option. It's just this is a side feature on a bot that is somewhere around 10k lines and I need to figure out if making changes to the DB and lots of associated code is actually worth it's for what's essentially a minor thing.
its not a lot tbh.. but whatever you choose
I was hoping there were easier options, but I may need to go down that route
It's not much code lmao
ok well, I made a test file and copied the code from the pycord docs for cogs, so I added this to main; client.add_cog(greetings(bot))
and this to the cog;
def __init__(self, bot):
self.bot = bot
self._last_member = None
@commands.Cog.listener()
async def on_member_join(self, member):
channel = member.guild.system_channel
if channel is not None:
await channel.send(f'Welcome {member.mention}.')
@commands.command()
async def hello(self, ctx, *, member: discord.Member = None):
"""Says hello"""
member = member or ctx.author
if self._last_member is None or self._last_member.id != member.id:
await ctx.send(f'Hello {member.name}~')
else:
await ctx.send(f'Hello {member.name}... This feels familiar.')
self._last_member = member```
I get the error NameError: name 'greetings' is not defined
Try and use extensions
Rather than manually importing it
so, I just add this?
client.add_cog(greetings(bot))
ok, so I tried this
client.add_cog(greetings(bot))
setup(client)
client.run(TOKEN)````and it doesn't work. am I doing something wrong?
I still get the error that NameError: name 'greetings' is not defined
dont think you are supposed to run add_cog during a setup func in the main file
Uhh capital G
And that's not how you make cogs
.guide
Check the cogs section there
ok, well, now I'm getting this error; Extension 'cogs.greetings' raised an error: AttributeError: 'Bot' object has no attribute 'add_command', might that be cause I've defined it as Client instead of Bot?
for discord.ext.commands.Cog,
@commands.command is a prefix cmd
and @commands.slash_command is well, a slash command
since your bot instance is discord.Bot and not commands.Bot, it cant have prefix cmds
ah right
is there a way to do the following:
/checkroleperms [@role]
and have it return the permissions of the role?
results would be something like
has admin: false
has channel edit: true
ect ect
.rtfm Role.permissions
.rtfm discord.ui.channel_select
how can i get the selected channel in variable?
Hey guys,
i have a command which is working like !command #outputchannel url1 url2
"url1" is setting a footer image of an embed and "img2" the thumbnail.
As i sometimes dont wanna use a footer i can remember that i could pass / empty that by just invoke it like this: !command #outputchannel "" url2
Today i used this command since ages and the error tells me that i cant perform it like that.
It would expect a http link instead. So now if i do it like https://"empty".png it work but cant that be done easier?
you can use try and except
it always works for me in this type of situations
Yeah its been a while.. not really the best method to perform what i want ( as it is atm ). Ill probably just rewrite it like you said.
I thought i could maybe pass it other way without rewrite
how can I create a invite link for a certain guild? Here is the code I've got so far;
@commands.has_permissions(administrator=True)
async def servers(ctx):
embed = discord.Embed()
for guild in client.guilds:
embed.add_field(name=":crown:", value=guild)
link = await guild.create_invite(max_age = 300)
embed.add_field(name=":crown:", value=link)
await ctx.respond(embed = embed)```
Target not found, try again and make sure to check your spelling.
oh, ok. Cause I'm trying to do so that the bot can generate invite links from server that it is in and not me only
.rtfm create.invite
Target not found, try again and make sure to check your spelling.
.rtfm create_invite
yeah you can
whats about ctx.channel
But there is no channel at all link = await guild.create_invite(max_age = 300)
invitelink = await ctx.channel.create_invite() smth like that
and then send(invitelink)
Will create an invitelink for the channel the command was invoked
if it is ctx though, it creates a invitelink for the channel you use the command in
Yes, but you dont have to be in that guild. (just the bot) Or am i getting you wrong rn? Thought that you mean other users can use it in channels in other guilds
does modal support option like slash command?
no. it only supports input texts
ok
how to add a reaction emoji after modal?
.rtfm message.add_reaction
what do .rtfm means?
its a command to show you docs link
but the actual full form is ||read the fucking manual||
ok🥲
raise LoginFailure("Improper token has been passed.") from exc
discord.errors.LoginFailure: Improper token has been passed. should i reset my bot tokken bc it is saying this?
Yes
But that means you aren’t using a valid token
bruh the bot keeps restarting ;-; i am running it locally, it might have something to do with how i run it idk
async def main():
await create_db_pool()
await bot.start(config.token)
asyncio.run(main())
i use this to run it with asyncpg
oh ok i will reset the tokken
same error after i reset the token
import dotenv
import os
dotenv.load_dotenv()
token = str(os.getenv("TOKEN"))
bot.run(token)
#this\/ is in the .inv file
TOKEN = 123456
#this is the error: raise LoginFailure("Improper token has been passed.") from exc
discord.errors.LoginFailure: Improper token has been passed.
keep getting the same error after i reset token and paste it in .inv file
Print the token and see if it matches
it literally just says "None"
That’s why







