#discord-bots
1 messages · Page 178 of 1
can u please screenshot it because i dont see it.
thanks man
thanks so much it worked. But the only problem i have left is i have “role: discord.Role” and when i use it the bot doesn’t give the role to the members and it has permission
role: discord.Role just converts the argument to a discord.Role instance
it doesn't give anyone any roles
ohhh
!d discord.Member.add_roles
await add_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s.
You must have [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
you can add roles with this method
you have member which is an instance of discord.Member, so you can use member.add_roles
ok so where would that code go into the coding ```@client.tree.command(name="sign", description="Where athletic directors & head coaches sign players")
async def sign(interaction: discord.Interaction, member: discord.Member, role: discord.Role) -> None:
msg = f"{member.mention} has been signed by {interaction.user.mention}!"
if 854573259030921256 not in [role.id for role in member.roles]:
msg = f"Sorry, but you don't have the head coach role to perform this command."
elif member.bot:
msg = f"You cannot sign bots since they are sentient beings, thus are immortal."
elif interaction.user.id == member.id:
msg = f"Hey {member.mention}! You cannot sign yourself."
await interaction.response.send_message(msg)```
didnt mean to ping robin
so would i do
where you want to add the role
wdym
just call the method wherever you want to add the roles
hmm. So the best place to do that would be after the argument right?
it has to be after the argument otherwise you wouldn't know which role to add
ok so that part is what im stuck on
so would i just do discord.Member.Add_roles?
@vocal snow
^
ohhh
async def sign(interaction: discord.Interaction, member: discord.Member, role: discord.Role, member.add_roles ) -> None:
thats the whole line
@vocal snow
im so confused on where it should be right now
id recommend looking at how to use functions in python
yep
im still stuck but i just noticed it shouldnt be in the same line as the other code
i mean you put it where you want to actually add the roles
do you want to add them as soon as the command is called
or after you do all the checks with the if statements
after all
so then just use an else statement and do it there
so like where these are?
you know how if statements work right
Learning a bit more python before making a discord bot would be good
If he’s saying to use an else statement just put it under those ones.
Im not sure what the context is so I might be wrong
What’s the problem
so this is about a argument in a tree command where the author runs a command to role someone but right now i guess i didnt add a if statement thats why the bot isnt roling the member
@slate swan
Where’s the command code
async def sign(interaction: discord.Interaction, member: discord.Member, role: discord.Role) -> None:
msg = f"{member.mention} has been signed by {interaction.user.mention}!"
if 854573259030921256 not in [role.id for role in interaction.user.roles]:
msg = f"Sorry, but you don't have the head coach role to perform this command."
elif member.bot:
msg = f"You cannot sign bots since they are sentient beings, thus are immortal."
elif interaction.user.id == member.id:
msg = f"Hey {member.mention}! You cannot sign yourself."```
So what do you want to do ?
Okay, what’s it doing now
nothing
Is it not giving them the role
yep
Or sending any messages
its sending messages and doing everything fine just not giving the person the role
There’s no code that would even add any roles or send a message here
im guessing i just need a code to actually make the bot able to make the role
memberobject.add_role(role)
the thing is where in the code tho
So it should be member.add_role(role)
async def sign(interaction: discord.Interaction, member: discord.Member, role: discord.Role) -> None:
msg = f"{member.mention} has been signed by {interaction.user.mention}!"
if 854573259030921256 not in [role.id for role in interaction.user.roles]:
msg = f"Sorry, but you don't have the head coach role to perform this command."
elif member.bot:
msg = f"You cannot sign bots since they are sentient beings, thus are immortal."
elif interaction.user.id == member.id:
msg = f"Hey {member.mention}! You cannot sign yourself."```
Well In what clauses do you want it to add the roles
if its successful so basically after the bot said its been signed
So you need to move that first msg variable into an if statement or else it’ll just be sending that no matter what
well it dont send when i try to sign a bot or when i try to sign myself
What code are you using to send the message
for which one the sucessful one
msg = f"{member.mention} has been signed by {interaction.user.mention}!"
I don’t really get what the problem is here
the bot isnt rolling the person that has been signed
So move the add role and response inside one of the conditions
hmm like where at in ths code because i dont want to mess it up you can edit it if you want im just gonna paste it
That's not how elif should be used
nope, if any of the conditions satisfy the msg variable is overrided
!e ```py
msg = 1
if "a"=="a":
msg = 2
print(msg)
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
2
Yeah I forgot my bad
how do i make a role be able to see the channel aswell
read_messages is "see channel"
use get role method and then put in variable and then do variable.send_messages r y
ty
ok
wdym excellent code, really well written..
I always use ow
Overwatch?
!e
code
Overwrites

yo
Hey , is it possible to code an python bot as selfbot for an user in discord?
That's not allowed.
ETC , I want to code an selfbot to search all of members in all of servers my user is , and then , if example word was in any of members bio , take that member id
Is it prohibited?
Not really but it's against ToS.
,
but it's gonna be complicated af 
Pretty sure "automating" falls under that category.
And besides don't suggest loopholes.
lmao fine
pretty sure reply triggers ping and is visible in notifications so no use editing
ok and
idk just saying
If you get a message on phone but the person removed the message you can still read it even.
pc too if u enabled notifs atleast on my windows idk others
i know
I'm not sure if I should ask this here or in the get help channel, but how do I make it so that I can see which commands a certain user performed in the console?
this is wht i have currently
print(f"> {interaction.user} used the command.") -
is {interaction.command} an actual command tht i can use?
!d discord.on_interaction
discord.on_interaction(interaction)```
Called when an interaction happened.
This currently happens due to slash command invocations or components being used.
Warning
This is a low level function that is not generally meant to be used. If you are working with components, consider using the callbacks associated with the [`View`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View "discord.ui.View") instead as it provides a nicer user experience.
New in version 2.0.
interaction.command is optional remember that. Pushing buttons sending models etc are also valid interactions.
tysm
Imagine
I'd just use the tree's check
tru
hikari 

discord.js 
W crate
How do I send a message in a Pacific channel with a discord bot
yEP
Does anyone have a example for sticky message ? (message stays at the end of the channel and old msg gets deleted)
sticky_msg_mapping: dict[int, discord.Message] = {}
@listen()
async def on_message(message: discord.Message) -> None:
if (msg:=sticky_msg_mapping.get(message.channel.id)):
await msg.delete()
new_msg = await message.channel.send("sticky message")
sticky_msg_mapping[message.channel.id] = new_msg
``` this should be pretty much it but you'll be better off using a database instead of the dictionary
Rip rate limit.
May ratelimit rest in peace.
Cooldowns in discord.py
Cooldowns can be used in discord.py to rate-limit. In this example, we're using it in an on_message.
from discord.ext import commands
message_cooldown = commands.CooldownMapping.from_cooldown(1.0, 60.0, commands.BucketType.user)
@bot.event
async def on_message(message):
bucket = message_cooldown.get_bucket(message)
retry_after = bucket.update_rate_limit()
if retry_after:
await message.channel.send(f"Slow down! Try again in {retry_after} seconds.")
else:
await message.channel.send("Not ratelimited!")
from_cooldown takes the amount of update_rate_limit()s needed to trigger the cooldown, the time in which the cooldown is triggered, and a BucketType.
I was more implying that the bots will remove his message, then it will send a new message triggering it again lol
omg your really the goat
ok so i have this problem my bot isn’t rolling the member after we use the role member argument command
"rolling the member"?
here let me
ok so you see the role part? that part is meant for the head coach to role who the member the picked on “member”
@cloud dawn
So assign roles to users?
yea
Well the role typehint works right?
yep
async def sign(interaction: discord.Interaction, member: discord.Member, team: discord.Role) -> None:
msg = f"{member.mention} has been signed by {interaction.user.mention}!"
if 854573259030921256 not in [role.id for role in interaction.user.roles]:
msg = f"Sorry, but you don't have the head coach role to perform this command."
elif member.bot:
msg = f"You cannot sign bots since they are sentient beings, thus are immortal."
elif interaction.user.id == member.id:
msg = f"Hey {member.mention}! You cannot sign yourself."
await interaction.response.send_message(msg)```
@cloud dawn
What have you tried so far?
!d discord.Member.add_roles
await add_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s.
You must have [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
Assigned to a member.
Yes and you need some checks.
Like a member cannot add a role equal or higher than the highest role he/she has. And same goes for the bot. If the bot's role that it's going to give is equal or higher it cannot be assigned.
yes
thats very smart
wait is it possible to make it so specific roles show up in the argument
You could with choices.
bet could you please help with the code
Erm.
I like to help but I don't want to provide you the code. I know I can do it, but if I will just do it for you; then you won't learn how to do research.

oh ok let me try to get the add roles working first
Besides that the docs also has some small examples. And anyone here is more than willing to explain how to use a certain function in a context.
ok so would it just be "await discord.Member.Add_roles"?
You are using the derived method.
await inter.user.add_roles

also add a guild only command check
by inter you meant interaction for short right
discord.Member.add_roles is the full path of the method you are going to use. But this class needs context, it has to exists. Therefore we look at what interaction passes if we want to give a role to the author, we can also create a Member object by fetching or getting it.
yeah
lmao
hikari-lightbulb 
this is what i have rn
add_roles is a function.
hm so how would i change that
Well you have to call it.
ohhh
"add_roles(role)"
right?
await interaction.user.add_roles(roles=)
but wouldnt the "roles=" need a certain role after that
Is roles an argument or a keyword-argument?
I’m currently using mongodb for my bot & I’m considering changing to asyncpg, are there any benefits to changing?
SQL is nicer than json syntax.
Other than that no I'd say.
is it not faster or anything?
Unless your bot is as big as mee6 you'd likely not notice.
so when (and if) my bot becomes bigger, it would be better to use asyncpg? since I wanna ensure I have a permanent DB, I can’t change later on when my bot has too much data
you haven’t passed any role objects
It really depends on how you structure your database and what you are going to store.
for the starters, asyncpg has much better design that mongodb/pymongo
and when it comes to the database postgres is much more scalable than mongodb, mongo isnt a great database anyways
snowflakes and strings really
Design due to Mongo not needing it.
oh, why isn’t mongo a great db?
SQL has support for dates and strings as well. But like I said it depends on how the person who makes it structures it. Design and normalizing it is very important.
1.it doesnt provide you features like fixing the data types a record should hold, for example if i have a sql table with column1 as BIGINT, if i enter any other type it will error out, mongo will hold the record since there's no setups like that
2. non relational
you can read more complex reasons here: https://medium.com/nerd-for-tech/the-dark-side-of-the-mongodb-f66f198a566b
sad part of the statement is that snowflakes are actually strings 🚶♂️
am i running this right?
well you're telling it to add roles but not telling to add what roles...
other than that it's fine
that was so casual
interesting
add the role param in the ()
Person who wrote that clearly doesn't know how Mongo is used lol
but theres multiple could i add a option in there?
detailed
|| sarth dosent like mongo ||
*untyped dictionaries
Great article.
tru
I kinda agree
use with some dataclasses
i'll pass with an asyncpg.Record subclass
so i basically have to put the roles in there. The ones i want to be used
The roles you want to add. Since you are doing it on the inter.user you will add it to the author.
member isn't an attribute of interaction.
Yes.
get me 512mb and free 24/7 reliable hosting I'll use it any day over mongo ;-;
Just use a matrix lmao
JSON
Does int have a limit in Python? what's the best way to pass an argument in a function like:
@app_commands.command()
async def test(self, interaction: discord.Interaction, message_id: int)```
inter.user doesn't have roles.
!d discord.ext.commands.Range
class discord.ext.commands.Range```
A special converter that can be applied to a parameter to require a numeric or string type to fit within the range provided.
During type checking time this is equivalent to [`typing.Annotated`](https://docs.python.org/3/library/typing.html#typing.Annotated "(in Python v3.11)") so type checkers understand the intent of the code.
Some example ranges...
but discord doesn't take integers of a Message ID length in an integer type argument
I see. In this case, I will just accept a str and convert it from my end.
yessir
as of 3.10.7 there is a default limit of 4300 digits
https://docs.python.org/3.10/library/stdtypes.html#int-max-str-digits
but in terms of slash commands, discord has a maximum boundary on numeric options in the range [-2^53, 2^53]
https://discord.com/developers/docs/interactions/application-commands#application-command-object-application-command-option-type
Apparently the slash command doesn't read integers.
they do, there's a integer option type in the api
they just don't accept BIGINTs as value
Incredibly useful, I’ll remember that
or any value out of the range thegamecracks mentioned
Remembered someone using string int() conversion earlier 😅
for referencing a message, i would probably make a transformer that uses the same mechanism as MessageConverter
discord doesnt have a native option type for messages apparently
one can use an app_commands.Transformer to make a custom one yeah
the data type shouldn't matter if it's a fetch request
oh right there's context menu commands
thats the best choice lol
almost same steps as it would take to copy the msg id
How can I see all the perms my bot has in a server
!d discord.Guild.me gives you the bot's member
property me```
Similar to [`Client.user`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.user "discord.Client.user") except an instance of [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member"). This is essentially used to get the member version of yourself.
!d discord.Member.guild_permissions gives you the server-level permissions
property guild_permissions```
Returns the member’s guild permissions.
This only takes into consideration the guild permissions and not most of the implied permissions or any of the channel permission overwrites. For 100% accurate permission calculation, please use [`abc.GuildChannel.permissions_for()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.GuildChannel.permissions_for "discord.abc.GuildChannel.permissions_for").
This does take into consideration guild ownership, the administrator implication, and whether the member is timed out.
Changed in version 2.0: Member timeouts are taken into consideration.
appreciate it
another question how would I setup the arguments if I wanted a command like this
.a @slate swan
or
.a bot.on_error=lambda *_:sleep(0)
actually instead of name an id
how can i except discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body In embeds.0.image.url: Scheme "hello" is not supported. Scheme must be one of ('http', 'https').
it you typehint it to discord.Member any of these will work ( for me example)
sarth
sarth#0460
@slate swan
bot.on_error=lambda _*:sleep(0)
580034015759826944
its a discord.HTTPException
fixed but ty
how would I go to replicate this?
do I need to store the images locally or? 
nope you create the image in memory get the bytes and send it directly using discord.File
!d discord.File the fp can be any bufferable
class discord.File(fp, filename=None, *, spoiler=..., description=None)```
A parameter object used for [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") for sending file objects.
Note
File objects are single use and are not meant to be reused in multiple [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send")s.
which means you can pass an io.BytesIO in there
I suppose the same if using disnake?
[we switched to it]
Hello, I'm trying to make a discord bot but I have no idea how to start, I would like the discord bot to use the search bar at the top right, how would I use the search bar with a bot?
this
exactly the same
what exactly are you trying to search
I want the user to input what he wants to search into the terminal
Is the search bar function maybe not the right way of doing it ?
Maybe reading message contents or sumn idk
!d discord.abc.Messageable.history
async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.11)") that enables receiving the destination’s message history.
You must have [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") to do this.
Examples
Usage...
you can check history per-channel
Your a life saver thanks man
And does messagebale history work per server?
We don't help with selfbots here so we won't be answering that question, sorry 🙂
Alright no problem I understand
my bad
this is called ephemeral, now try the docs with that word in mind
Try and see
slash commands have a different syntax than "text commands" tho
guys i have a question
Learning from the phone rather than from the computer will make a difference
Meaning, is there a difference in the Python language between the phone and the computer?
no, Python is Python, the OS is irrelevant
learning on a phone is quite a small screen though, you'll have lots of issuesdiscomfort with "scrolling through classes and functions" etc
indentation also ide support in short u will be in for a bumpy ride
question... why it says it is undefined?
that's not how you reference a method, you're missing a self parameter there too
ah self.create_welcome_image(member)?
right
but also, add self as the first argument to the create_welcome_image function
or make it a staticmethod
noted! I just need to thinker the create_welcome_image function then, thank ya ^^
since i changed my bot to use discord slash commands sometimes it don't respond to commands, someone reasons for this happen?
Hi, anyone is familiar with free hosting for bots? I used heroku but they closed the free tier
there's no good free hosts
https://railway.app this one's nice and free but has usage limitations similar to heroku ( 20-25 days/ month )
🚶♂️ thats just another way of saying 20 days
!e print(500/24)
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
20.833333333333332
🤷♂️
my man is working on anya
21 to be precise
When I try to print mutual guilds of a user it gives back [], I want to print the mutual guilds id
print(user.mutual_guilds)
|
I'm pretty sure I need to add something else here
bonus would be printing how many there in aswell as id and name
check the docs there should be some attribute mentioned there
What intents do you have?
I'm making a bot that collects stats for like how used it is
Okay, but what intents do you have?
Good ones?
No.. your gateway intents
Lol. Miscommunication 😅 my apologies
I haven't put any on
That's probably why then
IIRC your bot needs a special intent to be able to see guilds
Give me a sec to find out which one that was for you
appreciate it
To start off you can just use all intents:
intents = discord.Intents.all() # enable all intents
client = commands.Bot(command_prefix="!", intents=intents)
# commands and other logic here
client.run("token here")
Make sure you enable all 3 intents in your developer dashboard or this will spit out an error
it's weird because when I do bot.fetch _user_profile(user_id) it shows me the content inside the [] but when I try so only print the mutual guilds it doesn't
even with intents off
these 3
Yeah. All fetch_* methods do API calls, which doesn't really care what intents you have
If you'll notice this note here:
Ahhh ok, so
wait I know
It only considers the local cache
OH
What if the cache is out of date?
I'm just hecked?
I think I got it lemme test'
Your cache should not be out of date

Have you had a similar issue?
Heh, lol. Thought you had an issue like that before. The cache will always be up to date
Alright np, just prefer not saying it in the server
it is
if you're not breaking any rules nobody will judge 🙂
... and if it does i'm going to get in trouble for helping lol
Alright fair enough
damn where do I go for help on this kinda stuff bruh
Most servers won't help as it breaks discord's terms of service
And they'd be putting themselves at risk of termination
Yes that's fair enough
xx
Can someone give me that link to the stackoverflow question that explains why on_message stops your commands?
why stack overflow? there's one in the docs
https://discordpy.readthedocs.io/en/latest/faq.html#why-does-on-message-make-my-commands-stop-working
Because use @bot.listen() instead of @bot.event
Very simple
hey question, i have a file that uses memberid as a key, how would i search upthat key using ctx, is it like ctx.author.id?
how can i fix this
!tag intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.
There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.
Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.
thanks
"\n" doesn't work
expected output:
..
...
ahem...
test
Hello there!
Welcome to BitWorld, this is the very first ever book in BitWorld, if you reading this, i'm betting that you already encounter at least an enemy
Well, that's all in this book
Have a nice day!
rbbit```
what it actually does:
```.\n..\n...\n\nahem...\ntest\nHello there!\nWelcome to BitWorld, this is the very first ever book in BitWorld, if you reading this, i'm betting that you already encounter at least an enemy\nWell, that's all in this book\n\nHave a nice day!\nrbbit```
code:
```py
bookEmbed = discord.Embed(title=book, description=str(connDB.getBook(book)[0]["content"]))```
```py
def getBook(title):
k = []
for x in b.find({"title": title}, {}):
k.append(x)
return k``` i also use mongoDB btw
write ```..
...
ahem...
test
Hello there!
Welcome to BitWorld, this is the very first ever book in BitWorld, if you reading this, i'm betting that you already encounter at least an enemy
Well, that's all in this book
Have a nice day!
rbbitinstead of.\n..\n...\n\nahem...\ntest\nHello there!\nWelcome to BitWorld, this is the very first ever book in BitWorld, if you reading this, i'm betting that you already encounter at least an enemy\nWell, that's all in this book\n\nHave a nice day!\nrbbit```
it'll work, hopefully 🙂
ok, tysm
if you're using a listener for on_presence_update(self, before, after): to send an embed, what's the format for the user avatar? i'm trying these and it doesn't grab the avatar. any suggestions?
avatar = before.avatar(size=128)
embed.set_thumbnail(url=avatar)
embed.set_author(name=before.name, icon_url=avatar)
avatar = before.display_avatar.url
embed.set_author(name=str(before), url=avatar)
embed.set_thumbnail(url=before.avatar_url)
embed.set_thumbnail(url=before.avatar_url_as(size=128))
I don't think you can get the avatar from before
so prolly after?
I've never seen that word in my life
i'm using it for discord.ActivityType.streaming
if before.activity != after.activity
if after.activity.type == discord.ActivityType.streaming:
then it sends the embed.
Is it necessary for you to do it from code? Just use integration settings if not
trying to make my code as much as dynamic i can 😅
Wut
i mean i am trying to make bot autosetup
Ah
But like all servers are different, how can you automatically detect the channel you need? By checking names?
i am searching docs but not able to find anything 😅
user can use /register_channel
and then in that channel all commands will be executed
What's the point of that command if user can go to server settings and just put a checkmark on
all cant 😅 , only people with perms
got it to work. thank you!
one major issue is when u reload the bot , bot will register command again in global scope
That's why you should sync the commands manually
yes
It only sync the command when you call CommandTree.sync
!d discord.app_commands.CommandTree.sync
await sync(*, guild=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Syncs the application commands to Discord.
This also runs the translator to get the translated strings necessary for feeding back into Discord.
This must be called for the application commands to show up.
@mild token you can't update command permissions using bot https://discord.com/developers/docs/interactions/application-commands#permissions
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
Only if you authorise the user and do that via bearer token
How could I use this https://docs.nekobot.xyz/#image-generation-blurpify
class MyClient(discord.Client):
def __init__(self) -> None:
intents = discord.Intents.default()
super().__init__(intents=intents)
self.tree = app_commands.CommandTree(self)
async def on_ready(self):
print(f'Logged in as {self.user} (ID: {self.user.id})')
print('------')
async def setup_hook(self) -> None:
await self.tree.sync(guild=TEST_GUILD)
self.add_view(PersistentView())
this is how its in my bot
so when i turn on bot self.tree.sync is called everytime
Make a request to this endpoint?
I just said that's why you should sync the command manually
With a prefix command or something
I don't really know does that thing utilize authorization
what would be the needed json
?
Yeah just don't use it in async app
ok : ( is there any lib which have this option of syncing through channel
Just make it
Once you learn requests generally, move to aiohttp to use in async context
alright
It's not any harder than learning + operator
I learned how to use requests a one point
I just don't understand how to read docs
like I don't understand what I'm sending a get to it shows this /imagegen{?type}
Type is an URL param or whatever it's called
Like https://api.cool-site.com/imagegen?type=raw will send raw image bytes in response body
so like
If that's their base API url then yeah
Their base is actually https://nekobot.xyz/api/
Do they not require authorisation wtf
@vale wing still i am able to use command in other channel
bot.command not add_command
Where did you get this code from
and nice slash commands 
What library are you using?
That's for a text command-
I didn't see they were trying to add a slash command with that, not my fault 
Yes it is, read the question and code before answering

ah ok well that's very wrong but I'm not familiar with pycord, you might have better luck asking in their server
no 
it's probably @bot.slash_command() though
it is
sure-
I'm not familiar with pycord
Are you sure you're actually using pycord though?
discord.py 2.0+ slash command info and examples. GitHub Gist: instantly share code, notes, and snippets.
pip list
that's not stack overflow
do you also have discord or discord.py there
yeah use only discord.py or pycord, they'll conflict and make weird shit happen if you have both
sure, also do pip install discord.py --force-reinstall while you're at it
I have a question, I'm getting a error about exceeding rate limits, it's 429 but how do I prevent this from happening next time?
Slow down
Wdym?
A ratelimit means you're doing something too fast, slow down
It's a AI chatbot that I'm letting idle mostly
Do you have logging enabled?
No 
You should see warnings about ratelimits being handled before the 429
Using dpy 2.0 and not getting any errors? This is on purpose, the library now uses logging to send errors but only if you're using Client/Bot.run. More about that in ?tag defaultlogging.
It's recommended to setup logging yourself if you aren't using .run or use the utils.setup_logging helper function: just put discord.utils.setup_logging() anywhere in your running file. Docs: https://discordpy.readthedocs.io/en/stable/api.html#discord.utils.setup_logging
but I can't use Client/Bot.run!
You can! You can load cogs and do other stuff in the newly added setup_hook method that is called once after the bot logs in, more about that and how to implement it in ?tag setuphook.
Ah thanks
question. so for games to have that icon in the bottom left above ur avatar, is there a way I can get the url that discord uses to load it? like maybe the application_id?
trying to see if I can have a script grab it for a bunch of games I put in a db. here's an example of one for valorant.
<Activity type=<ActivityType.playing: 0> name='VALORANT' url=None details=None application_id=700136079562375258 session_id=None emoji=None>
i tried an if statement setup like this, but it didn't grab the icon :/
if before.activity != after.activity:
if after.activity:
application = await self.bot.application_info(after.activity.application_id)
avatar = application.avatar
What
the thumbnail that discord has for game activities. so like, the data discord has for this. how can a bot obtain it? I got the name via after.application_name, but i'm trying to see if I can grab the thumbnail too.
!d discord.Activity.large_image_url
property large_image_url```
Returns a URL pointing to the large image asset of this activity, if applicable.
!d discord.Member.activity
property activity```
Returns the primary activity the user is currently doing. Could be `None` if no activity is being done.
Note
Due to a Discord API limitation, this may be `None` if the user is listening to a song on Spotify with a title longer than 128 characters. See [GH-1738](https://github.com/Rapptz/discord.py/issues/1738) for more information.
Note
A user may have multiple activities, these can be accessed under [`activities`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.activities "discord.Member.activities").
It turns out I think it was just replit being dumb
What
like am i importing it correcting
for mobdrop in itemlist.mobdrop_list:
Is that list inside the itemlist file
yes
Then it should be good
Admins bypass the permissions 
Show file hierarchy and your entrypoint script
💀
wtf language are u talking in
Idk
Guys i am trying to make a docs command like @unkempt canyon and i have the objects.inv file
How can I use that file to get docs on a symbol?
set ephemeral=True in send_message
how can you check if you deselected an item in a dropdown?
like only you can see that message
in english ephemeral means something that exists temporarily
nope, only for interaction responses
how can you check if you deselected an item in a dropdown?
Hi, if there's anyone who has used telethon's api library for telegram before, do you know if its possible to remove a user from a group with a bot using the api?. Have tried it with the available methods but it only seems to work for channels.
this channel is for discord bots, you should ask this in a help channel ( #❓|how-to-get-help )
i get no error but its bothering me
i already did, just wanted to try out my luck in case someone also codes telegram bots on here.
ah, fair enough
there isn't a discord.commands 
which library are you using?
pycord
oh
there might be a discord.commands then, I'm not sure about pycord
I think you can import Option directly from discord though
What i am trying to accomplish
I am trying to make a command that when i do "/add 123" it will add 123 to a txt file on github. My bot is hosted by myself using Visual Studio Code.
why does this not work?
from threading import Thread
import discord
def master_thread():
intents = discord.Intents.default()
intents.messages = True
client = discord.Client(intents=intents)
@client.event
async def on_ready():
print('Logged in as')
print(client.user.name)
print(client.user.id)
print('------')
@client.event
async def on_message(message):
print(message.content)
client.run('blahblahblah')
Thread(target=master_thread, args=()).start()
It says RuntimeError: There is no current event loop in thread 'Thread-1 (master_thread)'.
It means exactly what it says
There's no event loop in that thread
!e
import threading
import asyncio
def main():
async def inner():
print("meow")
loop = asyncio.get_event_loop()
loop.run_until_complete(inner())
thread = threading.Thread(target=main)
thread.start()
@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | Exception in thread Thread-1 (main):
002 | Traceback (most recent call last):
003 | File "/usr/local/lib/python3.11/threading.py", line 1038, in _bootstrap_inner
004 | self.run()
005 | File "/usr/local/lib/python3.11/threading.py", line 975, in run
006 | self._target(*self._args, **self._kwargs)
007 | File "<string>", line 9, in main
008 | File "/usr/local/lib/python3.11/asyncio/events.py", line 692, in get_event_loop
009 | raise RuntimeError('There is no current event loop in thread %r.'
010 | RuntimeError: There is no current event loop in thread 'Thread-1 (main)'.
whats more valuable Java or Python
Depends on what you're comparing those two on
Hey guys, I used to make discord bots when the discord library died and then I shifted to disnake but soon I stopped making bots. So now again I am going to make bot, so what discord library most of you using?
speed
how fast it can analyze and execute
Java is a compiled language, so of course it's faster than Python
py -3 -m pip install git+https://github.com/Rapptz/discord.py
okay so discord library came back
Depends on what you want to do
!pypi discord.py
is it updated as per the discord.com docs?
I am asking because i am trying to make my bot fast enough to compile data and store it {every 6 seconds it stores it in python currently} but also be able to run commands that people may use {Without timing out}
Then asynchronous programming is enough
language?
Python
copy that thank you
it is
okay thx
wait no, not that discord.com lmao
those are the docs only for their API
not discord.py
no I mean IK
just asking if discord.py have the latest features rolled out by discord,com
Ye
"really new ones"
Because the last time I used discord.py, it was dead
It was when I started using disnake, which was updated
that was 2 years (or maybe 1) ago
I don't think it was this long, but maybe time went really fast
when discord.py was 1.7.3
yes
yo so i see other bots like save the options you have chosen before in a select. How do i do this?
but like how does the dropdown automatically like save those selects
can i show u an example in dms?
oh thats a discord feature, I am not familiar with it. Maybe someone else can answer
Their callbacks
Found out the hard way

why not?
As your JSON file gets bigger, the more data it needs to load into the memory to use
oh ye
and if your bot goes down while your bot is writing into the file, your data may get corrupted or in the worst case scenario, completely lost
can i show u an example in dms idk how to explain it?
how can you disable a button on disnake after it being pressed?
Nah
I don't understand purpose of it at all
Why not just use local IDE
Hi
!d disnake.ui.Button.disabled
https://github.com/DisnakeDev/disnake/blob/master/examples/views/disable_view.py
property disabled```
Whether the button is disabled.
No I mean for hosting
For hosting it's unisuitable
how do i save the options they have clicked before? like once they rerun the command on the dropdown those selects they clicked before will automatically be checked
!d discord.ui.Select
class discord.ui.Select(*, custom_id=..., placeholder=None, min_values=1, max_values=1, options=..., disabled=False, row=None)```
Represents a UI select menu with a list of custom options. This is represented to the user as a dropdown menu.
New in version 2.0.
there was some defaut kwarg somewhere
No documentation found for the requested symbol.
!d discord.SelectOption
class discord.SelectOption(*, label, value=..., description=None, emoji=None, default=False)```
Represents a select menu’s option.
These can be created by users.
New in version 2.0.
right, set it to True in the option's default kwarg
hello i want to send this embed with a discord bot command. exactly the same. what should i use. (add.field) or something else?
how to send a body content in an embed
is itembed.set_body(title="title", description="description")?
!d discord.Embed
class discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, timestamp=None)```
Represents a Discord embed.
len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.
bool(b) Returns whether the embed has any data set.
New in version 2.0.
x == y Checks if two embeds are equal.
New in version 2.0...
\2063 isn't an invisible char?
i want invisible char because when I write title="" it does that
hello
wat does exactlly mean by >For your app to be considered active, it will need to have executed an application command in th
application commands
does that i mean i have to use / slash in the start of my bot command like
if message.content.startswith("/"):```
No, you need to use a specially registered slash command. They look like this
so its called slash commands in discord
so the bot should have that particularly
Discord officially calls them "application commands" but yeah
Colloquially we refer to them as "slash commands"
roger that
@sick birch
code looks this way isnt it
Does it work?
yes
So what's the problem?
just clearning doubts
the event is on_command_error, not on_error
let me try
thanks 🤝
also there was on_error in logs too
whats that used for then
!d discord.on_error
discord.on_error(event, *args, **kwargs)```
Usually when an event raises an uncaught exception, a traceback is logged to stderr and the exception is ignored. If you want to change this behaviour and handle the exception for whatever reason yourself, this event can be overridden. Which, when done, will suppress the default action of printing the traceback.
The information of the exception raised and the exception itself can be retrieved with a standard call to [`sys.exc_info()`](https://docs.python.org/3/library/sys.html#sys.exc_info "(in Python v3.11)").
Note
`on_error` will only be dispatched to [`Client.event()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.event "discord.Client.event").
It will not be received by [`Client.wait_for()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.wait_for "discord.Client.wait_for"), or, if used, [Bots](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#ext-commands-api-bot) listeners such as [`listen()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.listen "discord.ext.commands.Bot.listen") or [`listener()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Cog.listener "discord.ext.commands.Cog.listener").
Changed in version 2.0: The traceback is now logged rather than printed.
based on what this says i think you can override it to change how the error is dispalyed
for example writing the error to a file instead of stderr
Is it impossible to print variables in embed's description?
It's possible
how?
you're trying to use an f-string ig
!f-string
Creating a Python string with your variables using the + operator can be difficult to write and read. F-strings (format-strings) make it easy to insert values into a string. If you put an f in front of the first quote, you can then put Python expressions between curly braces in the string.
>>> snake = "pythons"
>>> number = 21
>>> f"There are {number * 2} {snake} on the plane."
"There are 42 pythons on the plane."
Note that even when you include an expression that isn't a string, like number * 2, Python will convert it to a string for you.
lol
I've not seen many question about telegram bots.
in a user db for my bot, should the primary key be 1, 2, 3, 4... or the discord user id?
Well since the used ID is already unique it's good but you don't need a PK if you aren't going to constrain it anyways.
see here's the thing
w/o a PK intellij won't let me update the db for some reason lol
That's weird
I've seen maybe, 3, telegram bot questions in the years I've been here
Why does it send the message when someone in the voice channel is muting or unmuting themself?
@client.event
async def on_voice_state_update(member, before, after):
# Check if the user is joining the voice channel 712072729406472374
if after.channel and after.channel.id == 712072729406472374:
# Check if the user is in the database
if collection.find_one({"discord_id": member.id}) is None:
channel = client.get_channel(712074759453671494)
if member.voice:
await channel.send(f"{member.mention}")
# Create an Embed object
embed = discord.Embed(title="Verification Required", description="To ensure fair gameplay, we are using an Elo system to generate the teams. In order to participate in our custom games, you must first verify your League of Legends account. Please use the `!setup YOUR SUMMONER_NAME` command and follow the instructions provided.", timestamp=datetime.datetime.now(), color=discord.Color.red())
await channel.send(embed=embed)```
The event is triggered on mutes/unmutes as well
How can I change that?
What are you looking for your code to get triggered on? When a user joins a voice channel?
u want voice channel joins?
Yes exactly. Only when a user joins in the voice channel.
iirc there is an event for that too
If there would be a channel for every subtopic the server would be hell
And not when they are muting/unmuting or deafen/undeafen themself.
lol true discord bots supremacy
Telegram bots are just scripts that make requests API what's so special about them
discord bots aren't much more complicated but at least there's websocket
make a discord api wrapper
bots aren't that complicated not you can do so much more
But at least I managed to establish ws connection 🤓
nice
I'd probably better fork JDA and make it more user-friendly
You'd check if before.channel is None and after.channel is not None
Like this?
@client.event
async def on_voice_state_update(member, before, after):
# Check if the user is joining the voice channel 712072729406472374
if after.channel and after.channel.id == 712072729406472374:
if before.channel is None and after.channel is not None:
# Check if the user is in the database
if collection.find_one({"discord_id": member.id}) is None:
.......................```
You could combine those if statements into:
if before.channel is None and after.channel and after.channel.id == 123:
...
Or you can leave it as is
It's saying user has no attribute banner what would be the proper way of doing it
@bot.command()
async def banner(ctx, user:discord.Member):
user = await bot.fetch_user(user.id)
banner_url = user.banner.url
await ctx.send("{}".format(banner_url))```
So,
@client.event
async def on_voice_state_update(member, before, after):
# Check if the user is joining the voice channel 712072729406472374
if before.channel is None and after.channel and after.channel.id == 712072729406472374:
# Check if the user is in the database
if collection.find_one({"discord_id": member.id}) is None:
.......................```
what version of dpy are you using? @slate swan
forgot how do I check
print(discord.__version__) somewhere you know it will execute
pip show discord.py ;-;
That may not use the same venv/python version that their code is using
Which is why I generally advise people to print discord.__version__
hey i'm freaking out
i am using this code
@client.event
async def on_member_update(after):
target_guild = client.get_guild(816442399039422476)
blender_role = discord.utils.get(target_guild.roles, id=830836844950192209)
for activity in after.activities:
if activity.name == "Blender":
await after.add_roles(blender_role)
break
else:
await after.remove_roles(blender_role)```
it checks if a user is playing blender and if yes gives the role "blender"
pretty easy
BUT
i get "unknown role" as error
the role in the list is above everything and the command do what it should do
discord.on_member_update(before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") updates their profile.
This is called when one or more of the following things change...
yeah i had before, it was an unused parameter so i removed it
nothing changed
i still get the error even tho everything works fine
as you can see it is unused @pliant gulch
Yes, but I wouldn't remove it completely cause that'll either error right away or give an undefined behaviour
I would just prefix it like _before which is the convention iirc
None the less, make sure target_guild is not None and that blender_role is also not None
Okay, then make sure that the person who has Blender in their activity a member of the guild you have the role in
Those are the only places I can see this going wrong, other than that it looks fine
could you rephrase please?)
hey @pliant gulch
little update
i've used _before
and now no error pops up, could you tell me what is the convention iirc?
ah nevermind, my bot was getting rate limited.... al the errors popped up rn
py -m ?
python convention for unused params indicated with a _
yes it's pycord
and pycord dosent take intents?
idk never used it but the code looks awfully wrong
it does
chatgpt moment i would guess
no lol i did it
also message commands dont have options
only slash command
from discord import Option
no option just argument ;)
bot.command is for prefix command
it won't work with just that the code has a ton of bugs
i suggest u debug it in a ide
!pypi pycord
!pypi py-cord
yeah he has the former
ahhhhh
what is the package name of the official discord library?
I know there is one named Rapptz but it doesn't look official
it is
no official but famous ones are discord.py disnake hikari nextcord
what's wrong with the code
for starters the requirements
then the bot declaration
a bunch of stuff they will be highlighted once u code in an ide
so which one should I install?
i want the official one
plus u are using ffmpeg pretty sure something related to ytdl so thats a risk too
there ain't a official one
i am not using both of them xd
its all supported by enthusiastic devs
hm
discord.py if u beginner if u intermediate disnake if u like torturing ur self or challenging use hikari
discord.py has the biggest community tho
so i would suggest that
also dont watch old video tuts those are outdated
Hikari is clean as fuck
I don't think it would be torture
You must've gotten it mixed with Hata
its torture if youre learning haha
okay, thank you
say that to a beginner 💀
my answer was from the learning curve expected perspective
hikari is a pretty big learning curve tbf
Serenity >>>
I just remembered that for Hata Huyane rewrote asyncio apparently
Or at least that's what one of my friends told me
No hata is a special case
lemme Google him up
But this will not work if the user moves from a voice channel to another specific voice channel.
So I want it to execute the code regardless of whether the user was in a voice channel before or not
Ah, if before.channel != after.channel then
Sorry. But should I use the first or second one?
if before.channel != after.channel and after.channel.id == 712072729406472374:```
```python
if before.channel != after.channel == 712072729406472374:```
All you need is if before.channel != after.channel to check if a user moved / joined a channel
But I only want it to execute if they join the voice channel with ID 712072729406472374
Ah: if (before.channel is None or before.channel.id != 712072729406472374) and (after.channel and after.channel.id == 712072729406472374)
I think if before.channel != after.channel and after.channel.id == 712072729406472374: is doing the same thing, or am I wrong?
This opens us up to NoneType has no attribute id errors
What does that mean?
If a user went from being in a voice channel to not being in a voice channel, that means after.channel is None
And then you're basically doing None.id which, of course, errors
Do you know why this is considered error logs?
0|blitzcra | [2023-01-14 23:51:51] [INFO ] discord.client: logging in using static token
0|blitzcra | [2023-01-14 23:51:55] [INFO ] discord.gateway: Shard ID None has connected to Gateway (Session ID: 97d1d9df36701e8be3ca47d36586aa16).```
That's just logging, not errors
It's listed under errors logs. But I will just ignore them
its probably shown in the error log because python's StreamHandler (what discord.utils.setup_logging() uses) defaults to stderr instead of stdout
im trying to make a discord bot but I keep getting the error "Traceback (most recent call last):
File "main.py", line 4, in <module>
bot = commands.Bot(command_prefix='!')
TypeError: init() missing 1 required keyword-only argument: 'intents'
".
my line 4 is py bot = commands.Bot(command_prefix='!')
whats the issue and how can i fix it?
!intent issue is intents is a required keyword argument you need to specify
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.
There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.
Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.
does get_guild actually work for anyone here
Why wouldn't it
Because fetch seems to be the only thing that works for me lol
Whenever I replace a get command with fetch it just works
Where do you call it then
I'll provide you with an example hang on
Before Fetch (Nonetype error)
async def msg(self, ctx, channel_id=None, server_id = None, *, txt=None):
if server_id == None:
server_id = ctx.guild.id
if channel_id == None:
return await ctx.send("You forgot to specify the channel.")
server = self.bot.get_guild(server_id)
channel = server.get_channel(channel_id)
await channel.send(txt)
After Fetch (works)
async def msg(self, ctx, channel_id=None, server_id = None, *, txt=None):
if server_id == None:
server_id = ctx.guild.id
if channel_id == None:
return await ctx.send("You forgot to specify the channel.")
server = await self.bot.fetch_guild(server_id)
channel = await server.fetch_channel(channel_id)
await channel.send(txt)
user input: .msg channel_id server_id hiya
same input, different result
The error to be precise:
channel = server.get_channel(channel_id)
AttributeError: 'NoneType' object has no attribute 'get_channel'
The above exception was the direct cause of the following exception:
seeing ctx there, i assume this is a command? by default the arguments are str, fetch_x works for str and int, while get_x works for int only
also, you might as well use the channel converter instead of explicitly do get_x
async def msg(self, ctx: commands.Context, channel: discord.TextChannel):
await channel.send("Hello, world!")
Is all you need. Let discord.py handle the parsing for you
Ohh thanks! Yeah that worked.
That's good to know as well
it appears the converter for that only uses get_channel(), and if they're having issues with get_guild i suspect their guilds intent is disabled so it would make get_channel() fail too
thanks
oh right i missed flowerpad's comment
but now its saying "NameError: name 'discord' is not defined"
Import it then
need help
how do i make it check the mongodb every 2 secs if something changed then edit the original embed, if nothing changed it wont update or edit it until something gets changed
using pymongo
Usually, I'd avoid checking over something and then doing something, it's quite demanding imo. How does the data get changed? Like via a command or
Because if it's a command or any other thing that takes in user input that you control, you can just update the embed on demand
it does the command and it does the embed and all that, all im trying to fin to add a while true to check the database if something change on the user but if nothing changed it doesnt edit the original embed or update it until something does get changed and if it does it will update it
if u need a example code then i can give u it
Well, I'm assuming parts of other commands/events update the database correct?
yes
would you like to see the code?
So rather than having your code continuously check which is heavy, you could tell the bot that the embed needs to be updated
Lets take this as an example, ```py
some_code_that_updates_database() # we call this, E.g the command in this case
update_embed() # we call this because the database was updated and we know it is, because of above
Rather than having ```py
while True:
if database_updated:
update_embed()
some_code_that_updates_database()
database_updated = True
Note it's just pseudo-code so this doesn't work but, I think you can see what I'm getting at here
Hey @dapper breach!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
no i think
dont understand
pymongo is blocking, use motor instead
blocking what?
!blocking
Why do we need asynchronous programming?
Imagine that you're coding a Discord bot and every time somebody uses a command, you need to get some information from a database. But there's a catch: the database servers are acting up today and take a whole 10 seconds to respond. If you do not use asynchronous methods, your whole bot will stop running until it gets a response from the database. How do you fix this? Asynchronous programming.
What is asynchronous programming?
An asynchronous program utilises the async and await keywords. An asynchronous program pauses what it's doing and does something else whilst it waits for some third-party service to complete whatever it's supposed to do. Any code within an async context manager or function marked with the await keyword indicates to Python, that whilst this operation is being completed, it can do something else. For example:
import discord
# Bunch of bot code
async def ping(ctx):
await ctx.send("Pong!")
What does the term "blocking" mean?
A blocking operation is wherever you do something without awaiting it. This tells Python that this step must be completed before it can do anything else. Common examples of blocking operations, as simple as they may seem, include: outputting text, adding two numbers and appending an item onto a list. Most common Python libraries have an asynchronous version available to use in asynchronous contexts.
async libraries
The standard async library - asyncio
Asynchronous web requests - aiohttp
Talking to PostgreSQL asynchronously - asyncpg
MongoDB interactions asynchronously - motor
Check out this list for even more!
it isnt really
the problem is it updates every 2 seconds with out me updating anything
I'm just saying that it's blocking
Querying the database every 2 seconds with pymongo in asynchronous app like discord.py isn't a very smart idea
especially when loads of people are simultaneously trying to access your db
also, not sure why you used mongodb as a db, as I suppose most objects in dpy are relational, so an object-relational db would be more fitting
the most common answer to that is "I made another project where I used that db, so I kept going with it"
but can anyone help or not?
Damn who in your banner they bad fr
can anyone help me with the code?
bro wtf
im jus bein honest
You're down bad
Guys i am trying to make a docs command like @unkempt canyon and i have the objects.inv file
How can I use that file to get docs on a symbol?
it seems you've tried using sphobjinv before, you should look into their api documentation and its source code to learn how to use it
https://sphobjinv.readthedocs.io/en/stable/api_usage.html
https://github.com/bskinn/sphobjinv/blob/stable/src/sphobjinv/inventory.py
or if you want to write your own parser, you can follow their unofficial specification of the v2 format and read the source code of the python bot
https://sphobjinv.readthedocs.io/en/stable/syntax.html
https://github.com/python-discord/bot/blob/main/bot/exts/info/doc/_inventory_parser.py
Actually the src of python bot is very hard for me i am not much pro to read it
I tried encoding it and got a huge dictionary type thing
the parser itself seems to be relatively simple compared to the rest, i would focus on that first and turn the file into a useful data structure
I used this for reading file
So how can I get docs now?
import sphobjinv as s
inv = s.Inventory('objects.inv')
print(inv.objects)
src/sphobjinv/inventory.py lines 430 to 431
def suggest(self, name, *, thresh=50, with_index=False, with_score=False):
r"""Suggest objects in the inventory to match a name.```
Code works, everything is fine, it just won't add the user's data into the DB. ```py
if difference <= timedelta(seconds=3600):
query = 'INSERT OR REPLACE INTO Robbed (Timestamp, Placeholder, UserID) VALUES (?, ?, ?, ?)'
await cursor.execute(query, (int(time.time()), 0, member.id))
await cursor.close()
await db.close()
return await ctx.send(f"{member.mention} has already been robbed recently, please choose a different user.")
else:
query = 'INSERT OR REPLACE INTO Robbed (Timestamp, Placeholder, UserID) VALUES (?, ?, ?, ?)'
await cursor.execute(query, (int(time.time()), 0, member.id))
try:
await db.commit()
except Exception as e:
print(e)
if wallet - rob_amount < 0:
rob_amount = wallet
await cursor.execute(f"UPDATE Economy SET Wallet = Wallet - {rob_amount} WHERE UserID = {member.id}")
await cursor.execute(f"UPDATE Economy SET Wallet = Wallet + {rob_amount} WHERE UserID = {ctx.author.id}")
await db.commit()
await cursor.close()
await db.close()
return await ctx.send(f"{ctx.message.author.mention}, You've successfully robbed {member.mention} for $``{rob_amount}``.\n``Your Previous Wallet Balance``: ${wallet}.\n``Your Current Wallet Balance``: ${wallet + rob_amount}.", delete_after=5)
I got
:py:class:discord.Embed
You're not committing the changes
!d sqlite3.Connection.commit
commit()```
Commit any pending transaction to the database. If there is no open transaction, this method is a no-op.
And the placeholders amount is incorrect
Bro.
I am.
Do you need to commit them in that specific code block? Because it didn't work the last time.
It wasn't there before, tried it with and without, just put it there to see if it'd render through that way.
You need to commit every time you want to make changes to the database
Just rewrote some parts, and even made a line for it to create the table, and yet it still won't insert the changes.
Just commit the changes then
db.commit()
Before closing the database and cursor
U need to commit/save the changes u made to the database
Like
-Creating table
-Updating stuff on table
-Inserting stuff on table
-Altering stuffs on table
And so on
Also as catglal said, the placeholder amount is fr i correct, u r trying to change the value of 3 diff datas, but u inserting the value of 4 datas
💀
heyo!
import discord
from discord.ext import commands
from Rankcard import Main
class Rank(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.rankcard = Main.RANKCARD()
@commands.command()
async def rank(self, ctx):
card = self.rankcard.rank_card(
username=ctx.author.name, # user name
avatar= ctx.author.avatar_url,
level=1, # user level
rank=1, # user rank
current_xp=0, # user xp
custom_background= "#000000", # background colour
xp_color="#FF7A7A", # Foreground colour
next_level_xp=100) # Next level xp
file = discord.File(card)
await ctx.send(file=file)
def setup(bot):
bot.add_cog(Rank(bot))
I found this online but I dont quite understand, its giving me a bunch of errors like an attribute error with ctx and rankcard, does anyone know a better library for a rankcard?
Is it possible to make it so that when I send a link using the webhooks, that it doesn't show the preview or "unfurl"?
Yeah, surround the link in <>
For example:
https://www.youtube.com/watch?v=dQw4w9WgXcQ
or you can use supress_embeds=True in your send
what's the best way to do slash command?
app_command, tree command, pycord, slash_command?
bot.tree.command is a decorator
app_commands.describe also
Put @ infront of them
Also sync your commands in setup_hook
Tryna get me code to check if a message has a word in a json called narrators, and if it has the value "weak" it should add it to a list and send the keys present, but its not working, theres no traceback.
async def rijal(self,ctx,*,message):
narrators = message.content.split()
found_keys = []
for message in narrators:
for key in narrators.keys():
if narrators == key and narrators[key] == "weak":
found_keys.append(key)
if found_keys:
await message.channel.send("Weak keys found in the message: " + ', '.join(found_keys))```
heres the json
{"aban": "weak"}
Guys i am trying to make a docs command like @unkempt canyon and i have the objects.inv file
How can I use that file to get docs on a symbol?
How many times have you said this already
I not got help so I asked again
Someone already told you how to read the inventory file
for loop D:
thats even worse in my case
You should just take those as arguments
also, _init_ cannot be async like that
^ you could handle the async part in a classmethod and pass the actual values to the init
or alternatively, do the fetching lazily
I have read so what I do after that?
hello, how can i mention a user and the bot, in this type of function:
async def test_command(interaction:Interaction, question:str):```
i have no idea on how to fix this
but if i need 10 variables at once
i need to do
var1 = blahblah
var2 = blahblah
var3 = blahblah
var4 = blahblah
...
var10 = blahblah
yo so cos autocomplete only takes 25 values how can i make it so it displays 25 but i can search for more
this is working
but once i add async its not working
are there any other way other than async def init thats not going to work
__init__ can't be async
yo can som1 help
Just take them as variable or make a classmethod to construct the insurance
?
!e
import asyncio
class J:
def __init__(self, var1, var2):
self.var1 = var1
self.var2 = var2
print(self.var1, self.var2, sep="\n")
@classmethod
async def new(cls):
# do some async things
var1 = await asyncio.sleep(0, result="Variable 1: Cat")
var2 = await asyncio.sleep(0, result="Variable 2: Meow")
return cls(var1=var1, var2=var2)
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
ins = loop.run_until_complete(J.new())
@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | Variable 1: Cat
002 | Variable 2: Meow
Basic OOP
Discord.py can't convert your argument to member object
How did you call the command
yo so cos autocomplete only takes 25 values how can i make it so it displays 25 but i can search for more
