#discord-bots
1 messages · Page 1105 of 1
Not possible, I don't think spaces are allowed in argument names
You shouldn't be using globals in the first place
Unless you mean a bot variable
Alright no biggy
second question,
you should be able to use load_extension on cogs inside a cog itself right
Well, I suppose you can
Because I'm trying to /unload a cog thats already loaded because it loads with the bot in the main.py file but it returns an error saying it isnt loaded
But when I try to load it, it now tells me it could not be loaded
hmm
Even tho I can still use the commands inside said cog
I dont know if its because of how I organized my files or if that matters or what
Whats the syntax to refer to files in the same directory
or do you need to specify that
Like if I wanted to do something to another file in the same folder I should just be able to refer to the file by its name
Or do I need to do like \filename or something
Nevermind fixed it!
Needed to change how I was typing the file name
@stats.error
async def stats_error(ctx, error):
if isinstance(error, commands.CommandOnCooldown):
if ctx.author.id == 92786442891169792:
args = (player)
kwargs = {}
await ctx.invoke(ctx.command, *args, **kwargs)
else:
msg = f'Try again in {round(error.retry_after)}s'
await ctx.respond(msg, ephemeral = True)
in pycord am i using invoke incorrectly? i want it so if i use the command that has argument player: discord.User, i override the cooldown
you're probably looking for ctx.command.reinvoke
No, however I think there’s a special character
what is this special character
Im just trying to get rid of the _ that shows up in the command line
which doesnt make sense to me why I would be able to name it if that name isnt used for it
Scroll down a bit
embed = discord.Embed(
color= 0x19ff19
)
file1 = discord.File("./ImageO/Экономика/Work/Выбери Профессию.png")
embed.set_image(url='attachment://Выбери Профессию.png')
await ctx.send(f"{e_iron}{e_organic}{e_wood}{e_details}{e_batteries}{e_shards}", file = file1, embed = embed, view=Counter(ctx.author.id))
Dear, tell me why the picture is on top of the embed and not in it
my·Call()
U could use that dot
Np
!d discord.app_commands.rename
@discord.app_commands.rename(**parameters)```
Renames the given parameters by their name using the key of the keyword argument as the name.
This renames the parameter within the Discord UI. When referring to the parameter in other decorators, the parameter name used in the function is used instead of the renamed one.
Example:
```py
@app_commands.command()
@app_commands.rename(the_member_to_ban='member')
async def ban(interaction: discord.Interaction, the_member_to_ban: discord.Member):
await interaction.response.send_message(f'Banned {the_member_to_ban}')
graci
I have it spelled correctly
Question, so I have the specific error inside of my on_command_error event but instead of using the message for it, it uses else: and raises the error even tho the error codes match where the yellow line is
oh and _ just read
did you put @bot.event
it does not seem like it
Im using
bot.tree.on_error = self.on_command_error
in my init
It still uses it, it just used else: instead of the isinstance extensionalreradyloaded
hm, no idea about the on_error in the CommandTree
shouldn't it be on_command_error there too
is this just like unnecessary confuser
it was because originally I had an event but it wasnt working properly
I mean, its on command error so it makes sense to me
its just w/out the client event
built differently
how can i make my bot show in it's game activity how many servers it's in?
wym game activity
len(botvar.guilds)
!d discord.Client.change_presence
await change_presence(*, activity=None, status=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Changes the client’s presence.
Example
```py
game = discord.Game("with the API")
await client.change_presence(status=discord.Status.idle, activity=game)
``` Changed in version 2.0: Removed the `afk` keyword-only parameter...
no, this only sends the guy who interacted with a direct message, but i want to let it send a message to a certain user
like me
So like you can fetch your user object using discord.Interaction.client.fetch_user and you can just call the discord.User.send method on that.
Example:
interaction = ... # Interaction obj here
user = await interaction.client.fetch_user(idhere)
await user.send("whats up pimps")
no members intents? 🥺
?
I dont assume everyone has intents so 
yeah but people that do have intents will end up fetching anyways
@sick birch hey robin, a quick question
so remember how I used
bot.tree.on_error = self.on_command_error
for the error event but it only responds to app_commands errors, I.E CommandInvokeError instead of the discord.ext.commands errors which are the ones I need it to respond to bc CommandInvokeError is to general, do you know how I would change that
if they dunno
Well yeah the tree is meant for slash commands, not regular commands
async def on_member_join(memeber):
welcomebed = discord.Embed(
colour = (discord.Colour.black()),
title = 'i worked',
description = f' i worked'
)
await memeber.send(embed=welcomebed)```
ye Im using slash commands
when doing thos command, it doesnt work
i was wondering why
you dont need to wrap that method btw
well i mean function
it triggers when someone joins
But you want error handling for regular commands?
you need members intents for it
you can just make it colour=discord.Colour.black()
correct i have this on via dev portal
No its all slash commands, I have no regular commands
in code as well?
Im getting both errors, yellow is what I need it to respond too, red is what it is responding to
So what's the issue then?
Ah I think I see
So it responds to app_commands.errors but not commands.error
thanks
i do not, let me add that and try rq
CommandInvokeError is picking up and encapsulating ExtensionAlreadyLoadedError
Get the original using error.original
bro's speaking like a doctor
I wanna speak like that too
On the isinstance(error.original, ...)?
@heady sluice yep same issue, just added intents to my code
show how
Robins english is honestly really good for not being from the US.
or UK
Sorry, we use that term a lot in networking (PDU encapsulation in different OSI layers) so it kinda bled through haha.. gets the point across
why don't you include the UK
wait, something is missing up via my color, just wait 1 moment and let me fix this
Thank you 😊 I have lived here for a good while so I suppose it isn't that great a feat
what the
can anyone send the kwargs for ctx send
are you like 35
!d discord.ext.commands.Context.send
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
This works similarly to [`send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") for non-interaction contexts.
For interaction based contexts this does one of the following...
ah, it's a channel, mb
No haha.. only 17
it would've been discord.abc.Messageable
yeah, I hate that it doesn't autocomplete tbh
you're old either way
oh yeah, that doesnt exist.

😔
shouldn't default be gray
discord-theme gray
topic
What happens to a View after you delete the message it was sent with?
Does it timeout?
looks black to me
looks normal to me idk I'm not racist
...?

💀
So basically discord is slowly eliminating the need for bots
but I've been thinking of this for like two months
please help my sleep schedule
if command_name != 'critical' or 'core':
Can you do something like this or do you need to write command_name twice
does the View live after the message was deleted?
!or
When checking if something is equal to one thing or another, you might think that this is possible:
# Incorrect...
if favorite_fruit == 'grapefruit' or 'lemon':
print("That's a weird favorite fruit to have.")
While this makes sense in English, it may not behave the way you would expect. In Python, you should have complete instructions on both sides of the logical operator.
So, if you want to check if something is equal to one thing or another, there are two common ways:
# Like this...
if favorite_fruit == 'grapefruit' or favorite_fruit == 'lemon':
print("That's a weird favorite fruit to have.")
# ...or like this.
if favorite_fruit in ('grapefruit', 'lemon'):
print("That's a weird favorite fruit to have.")
rip
best looking and most useless one:
if any(favourite_fruit == fruit for fruit in ("grapefruit", "lemon")):
Confused on why its saying cogs.corecogs when it should just be cogs.core
Is core like a name you cant use?
You leaked your token, might wanna regen it
yea i do that like every 10m no worries
Maybe, try changing to see if it works
What can someone actually do with ur token, just recode your bot basically?
grief ur server
the problem is, the interaction is failing everytime and that's what I want to fix
Yes
They can do anything you can
I just have to use your token in my bot.run()
Good thing its just in some test server that I just use to test bots 😂
Hmm its still doing it
Oh I forgot a ,
derp
that would make sense
yup lol
The cogs. from the previous one would leak into it
Is there a way to check if a cog is already loaded/unloaded without actually loading/unloading it since that would give an error
pretty sure
interaction.response.defer() fixes that
i could be wrong tho
!d discord.ext.commands.Bot.cogs
property cogs```
A read-only mapping of cog name to cog.
you could look at this
dont really understand that, I was just going to use a try except statement
Is this suppose to be like
if cog:
# Then extention is loaded?
@sage otter
no you literally just check if the name of the cog that you want to see is loaded or not is in the mapping's keys
What is mapping's keys
if "cogs.cog_name" in bot.cogs:
# cog is loaded
if not "cogname" in bot.cogs.keys():
#if this condition passes. The cog isnt loaded
i hate you Robin
Ooh
lol
beat you to it + better
Literally took me an hour to write that because im like mentally drained rn
Nah it's good, both work
perfect, now it's working
Don't be mean to me I know I'm stupid but I'm leaning LMAO
@client.event
async def on_message(message):
prefix = (message.content.split(' ')[0]).lower()
msg = message.content.split(' ')[1:]
I kinda have a feeling this is REALLY bad XD
But I don't know what approach I should use, if you guys have suggestions
use the commands extension, it has a built-in parser so you don't have to do all of that string splitting mumbo jumbo
docs: https://discordpy.readthedocs.io/en/latest/ext/commands/commands.html
thank youuu !
you're welcome, happy coding!
initial_extensions = [
'cogs.suggestion',
'cogs.ping',
]
@app_commands.command(name='load', description='Enable a command')
@app_commands.describe(command_name="Command name")
async def load(self, interaction: discord.Interaction, command_name: str):
if command_name in ['all', '*']:
for ext in self.initial_extensions:
# If cog not loaded
if ext not in self.bot.cogs:
await self.bot.load_extension(ext)
Is there something obviously wrong with this portion of code, I'm trying to script the command to work with 'all' or '*' to run on all extensions inside the initial_extensions list, and the script doesn't break it or anything but it gives me very broad errors that dont really tell me whats wrong with it
You're looking at the wrong command, looks like unload is causing issues
That's just the command I used to test it but it'll do the same for load as well
its all basically copy paste in terms of code
# Disables a command
@app_commands.command(name='unload', description='Disable a command')
@app_commands.describe(command_name="Command name")
async def unload(self, interaction: discord.Interaction, command_name: str):
if command_name in ['all', '*']:
for ext in self.initial_extensions:
# If cog loaded
if ext in self.bot.cogs:
await self.bot.unload_extension(ext)
unload_embed = discord.Embed(
title='Commands Unloaded',
description=f'All available commands have been successfully **unloaded**.',
timestamp=datetime.now(),
color=0x49ba8b) # Green
unload_embed.set_footer(text='All Commands Disabled')
await interaction.response.send_message(embed=unload_embed, ephemeral=True)
elif command_name not in ['main', 'core']:
await self.bot.unload_extension(f'cogs.{command_name}')
unload_embed = discord.Embed(
title='Command Unloaded',
description=f'The requested command has been successfully **unloaded**.',
timestamp=datetime.now(),
color=0x49ba8b) # Green
unload_embed.set_footer(text='Command Disabled')
await interaction.response.send_message(embed=unload_embed, ephemeral=True)
elif command_name in ['main', 'core']:
# more stuff here just didnt paste
heres unload tho
You probably meant to unindent the interaction.response.send_message(...)
He beat me by a second
haha, we knew exactly what to look for
That for loop was trouble
I knew there was some responding to interaction inside loops going on
initial_extensions = [
'cogs.suggestion',
'cogs.ping',
]
# Disables a command
@app_commands.command(name='unload', description='Disable a command')
@app_commands.describe(command_name="Command name")
async def unload(self, interaction: discord.Interaction, command_name: str):
if command_name in ['all', '*']:
for ext in self.initial_extensions:
# If cog loaded
if ext in self.bot.cogs.keys():
print(ext)
await self.bot.unload_extension(ext)
I dont think my for loop for unload command isnt working properly because its not printing ext and its not disabling the command/returning any errors
cogs.keys() return the Cog names, not their extension path, so you "if ext in ...." will never be True @stiff fern
List of your cog names
Right
oh
yea
Im doing it right then
ext is the cog name?
Is it suppose to be w/out the cogs.
so its just suggestion
class MyCog(commands.Cog):
``` here MyCog is the cog name
gottcha
if you do something like ```py
class MyCog(commands.Cog, name="potato")
🙏
Do you know how I would remove the first 4 characters of the file name then so it would match up, I know I can do like ext[-3] but that would remove the last 3 I believe or something like that?
!e print("654321"[3:])
!e print("654321"[:4])
@stiff fern :white_check_mark: Your eval job has completed with return code 0.
6543
Oh you reverse the :
here you go
graci
Anyone know why the # isn't working for comments?
oh nvm I think it does work it just doesnt look like it
def check(m, message):
return m.author == message.author
msg = await client.wait_for('message', check=check)
This whole thing is inside a function, in a file, that I'll call from another file. How can I pass message to check please?
oh no no not that one. I means message the variable, not 'message' the argument
don't define it in the check, it'll render invalid, instead, instead define it in the main function as a separate parameter
I can't do it... I don't know
I'll try something
ohhhhhhh indeed !!!! I did it thank you !
Hey I have like 9 buttons is there any callback that calls when any one of them of the buttons is clicked
I mean to say 9 buttons but 1 callback
are you using the @button decorator to make those buttons?
class View(ui.View):
async def callback_for_all(self, button, interaction):
...
@ui.button(...)
async def foo(self, button, interaction):
await self.callback_for_all(button, interaction)
@ui.button(...)
async def bar(self, button, interaction):
await self.callback_for_all(button, interaction)
``` ez
ohk :D thanks lol
or use the discord.ui.Button method and set thr callback of all buttons to a single function
okay
@stats.error
async def stats_error(ctx, error):
if isinstance(error, commands.CommandOnCooldown):
if ctx.author.id == 92786442891169792:
args = (player)
kwargs = {}
await ctx.invoke(ctx.command, *args, **kwargs)
else:
msg = f'Try again in {round(error.retry_after)}s'
await ctx.respond(msg, ephemeral = True)
in pycord am i using invoke incorrectly? i want it so if i use the command that has argument player: discord.User, i override the cooldown
it's ctx.command.invoke isnt it
its not documented
ctx.invoke is a thing too
weirded
but that's not how you pass args and kwargs 
man just literally copy pasted it from the docs
nvm
at least robo danny shows it
is player defined?
i thinkthats what im confused about?
how would i define it in this error
from my command
Hello i want to ping everyone who has @role role. How to do it?
you can't access command arguments in error handler. thats not how discord.py is designed
just ping the role, easy
!d discord.Role.members requires member intents
property members```
Returns all the members with this role.
!d discord.Role.mention ...?
property mention```
Returns a string that allows you to mention a role.
What if they muted the server?
how could i then instead make it so when i use a command, i dont get a cooldown?
!d discord.ext.commands.Context.invoke
await invoke(command, /, *args, **kwargs)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Calls a command with the arguments given.
This is useful if you want to just call the callback that a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") holds internally.
Note
This does not handle converters, checks, cooldowns, pre-invoke, or after-invoke hooks in any matter. It calls the internal callback directly as-if it was a regular function.
You must take care in passing the proper arguments when using this function...
cant do anything
how can i disable all buttons is a view without disabling them one by one?
not that, ash used !d discord.ext.commands.Command.invoke which is not documented
the message got deleted by by the bot
just stop the view?
ohk thanks
finnaly i have done with my tic tac toe game
doesn't stopping the view just stops listening for interaction, the buttons don't change right
ye
!d discord.ui.View.stop
stop()```
Stops listening to interaction events from this view.
This operation cannot be undone.
if (self.but1.disabled and self.but2.disabled and self.but3.disabled and self.but1.emoji == "❎" and self.but1.emoji == "❎" and self.but3.emoji=="❎") or (self.but4.disabled and self.but5.disabled and self.but6.disabled and self.but4.emoji == "❎" and self.but5.emoji == "❎" and self.but6.emoji=="❎") or (self.but7.disabled and self.but8.disabled and self.but9.disabled and self.but7.emoji == "❎" and self.but8.emoji == "❎" and self.but9.emoji=="❎") or (self.but1.disabled and self.but5.disabled and self.but9.disabled and self.but1.emoji == "❎" and self.but5.emoji == "❎" and self.but9.emoji=="❎") or (self.but3.disabled and self.but5.disabled and self.but7.disabled and self.but3.emoji == "❎" and self.but5.emoji == "❎" and self.but7.emoji=="❎") or (self.but1.disabled and self.but4.disabled and self.but7.disabled and self.but1.emoji == "❎" and self.but4.emoji == "❎" and self.but7.emoji=="❎") or (self.but2.disabled and self.but5.disabled and self.but8.disabled and self.but2.emoji == "❎" and self.but5.emoji == "❎" and self.but8.emoji=="❎") or (self.but3.disabled and self.but6.disabled and self.but9.disabled and self.but3.emoji == "❎" and self.but6.emoji == "❎" and self.but9.emoji=="❎"):
💀
ugh
any idea
how can i do it better or its fine
https://github.com/DisnakeDev/disnake/blob/master/examples/views/disable_view.py exactly what you want
Bro
Please, for the love of God and sanity and PEP 8, use a different line for each condition
uh ok
Or take this to #esoteric-python before someone gets a stroke in this channel after seeing that if statement
lol
Good morning, or evening guys...
I use module mcstatus
And have a simple line of code,
server = JavaServer.lookup("palmproject.joinserver.ru")
status = server.status()```
It works okay, and then I use it to:
@bot.event
async def on_ready():
while True:
palmus = "Players: ", status.players.online
palmus = str(palmus)
await bot.change_presence(activity=discord.Game(name=palmus))
await sleep(15)
It works correctly, but why bot shows not Players:3(it's not smile lol), it shows... (on the image)
How to have bot status ``Players: 2``?
||about changing activity i found information here https://stackoverflow.com/questions/59126137/how-to-change-activity-of-a-discord-py-bot||
well that seems to be an issue with the mcstatus module, since that is what returns status.players.online.
You might want to open a help channel for this issue
it's cz you load it on start and nobody is in the server :)
set a task to change it every time instead
problem isn't in number of players
then?
async def on_ready():
while True```
the sound alone is haunting me
index the tuple
Ah
yes.
thx
Nah ignore that
palmus[0]
palmus[1] <- returns thr number of players
f"{palmus[1]} {palmus[0]} are online"
Will return 0 Players are online
set a task....
That too
oh ve just read about tuple, useful thing😎
from discord.ext import commands, tasks
def server_lookup():
server = JavaServer.lookup("")
return server.status()
@tasks.loop(seconds=15)
async def status_c():
#wait until ready
status = await bot.loop.run_in_executor(None, sever_lookup) #same as server.status() but not blocking
...
okay I hate autocorrect
dickord wht
autocorrect
t9
uh, maybe...
NameError: name 'tasks' is not defined
what..
from discord.ext import tasks
thx
nice import u got there btw
da
return (',\n').join(imgs)
someone knows why the result is correct in console but bot messes it up? D:
return ",\n".join(imgs) try this
can you show the actual response?
oh wait no im blind
lmao
just tried, doesn't work
Hunter's too smort
this is crazy
You can see /n in the bottom image so make sure you are doing \n
https://via.placeholder.com/300.png,/nhttps://via.placeholder.com/300/09f.png,/nhttps://via.placeholder.com/300/09f/fff.png,/nhttps://via.placeholder.com/728x90.png,/nhttps://pp.vk.me/c624121/v624121992/3cf22/YRIx_w-QySg.jpg,/nhttps://pp.vk.me/c624121/v624121992/3cf22/YRIx_w-QySg.png,/nhttps://pp.vk.me/c624121/v624121992/3cf22/YRIx_w-QySg.jpg,/nhttps://pp.vk.me/c624121/v624121992/3cf22/YRIx_w-QySg.jpeg
I'm getting this from the bot lol
Yeah you can see the ,/n
Have you reloaded the command if you made any changes?
reloaded?
use a for loop ? if that doesnt work
Can you show the full code
I'm so stupid !
I coded the bot to store data in a dictionnary
so obviously \n won't work !
Ah
none is stupid we are just confused 😔

we all are stupid....except Hunter 
😐
why use asyncio.AbstractEventLoop.run_in_executor() over creating a task with asyncio.AbstractEventLoop.create_task()?
create_task doesn't wait for a result
wdym and why would that matter here?
can i get a message from dms of a user through the bot
if yes can someone give an example
async def foo():
...
async def bar():
create_task(foo())
# this doesn't wait for foo to be completed
run_in_executor(foo)
# this waits for foo to complete
interesting, does run_in_executor only stop when the function object is completed since it uses thread pools?
okimmi
u got any idea abt this ?
!d discord.DMChannel.fetch_message
await fetch_message(id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a single [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message") from the destination.
ohh
await fetch_message(id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a single [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message") from the destination.
that returns the return value of the coro, so yes
ah so it waits for the result of the coro and it doesnt block your code
but wouldnt create_task be better as it doesnt make a thread pool and it has the same purpose, in this case ofc.
well you see, they are trying to get some result from that blocking def
well it seems like asyncio.loop.run_in_executor returns the coros value is that so?
im not sure if create_task will return it, unsure
nah
yes it does
it returns a Task object
ah interesting thats kinda cool
exactly, that's the point
mhm thats nice
how many fields can i have in one embed line?
alright
going back to what i asked earlier as well, is there no way to disable cds for specific users?
in pycord
you can do that for sure, but im not aware of "how" atm, need to check source code
alright, thank you!
@discord.ext.commands.dynamic_cooldown(cooldown, type)```
A decorator that adds a dynamic cooldown to a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command")
This differs from [`cooldown()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.cooldown "discord.ext.commands.cooldown") in that it takes a function that accepts a single parameter of type [`discord.Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message") and must return a [`Cooldown`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Cooldown "discord.app_commands.Cooldown") or `None`. If `None` is returned then that cooldown is effectively bypassed.
A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of `type` which must be of enum type [`BucketType`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.BucketType "discord.ext.commands.BucketType").
If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CommandOnCooldown "discord.ext.commands.CommandOnCooldown") is triggered in [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") and the local error handler.
A command can only have a single cooldown.
New in version 2.0.
bruh we can give more than 25 with basic_autocomplete in utils
imagine trying to find fault in each example
well you want to show good examples to users, no?
well, what's the issue in that example smh
there is no issue but it doesnt mean it cannot be improved
smh I'll just stop visiting this channel instead
easier
You can't leave us like that
how do you install discord.py v2?
nobody cares :)
pip install git+https://github.com/Rapptz/discord.py
That hurts, right into my meow meow
Thanks
I think I saw that on disnake master, the automod was added. Has anyone used it? If so what does it look like?
uhm no they didn't add an automod integrated 
the last great change were released on 7 May
with a bug fix a few days after
||this morning i can't fuckin write||
Is there a kind soul willing to walk me through the steps to create a telegram bot? I'm a newb and the instructions on this page, while they seem clear enough, are overwhelming for my skill level:
https://betterprogramming.pub/how-to-turn-your-google-form-into-a-telegram-bot-108ac382c58a
sorry this is not a channel for it
!rule 7
7. Keep discussions relevant to the channel topic. Each channel's description tells you the topic.
there is a telegram community for aiogram, you can ask there for help
hi guys
so im making a bot and it's not coming online
shows me this on the terminal
oh nvm

remove the parentheses
parenthesis*
parenthesis is singular
omg not here bruh
one parenthesis, multiple parentheses
well doesnt parenthesis refer to the pair?
What does this mean?
idk im indian
bro
We use brackets!
exactly. so much easier
I mean, we can build a list for larger than 25 options though we can provide different input than the autocomplete list, but that's easily manageable
Ah, yea that's a hacky way haha
That's what I asked for yesterday 👀
And no one had any idea because that's more of a hacky way and i won't be surprised if discord patches that
And this is more of a bug imho, than a proper way to do so
it's basically codeblock with syntax highlighting
Text : 1
yaml
you don't, you can use \n
or just make a docstring (but be sure to use inspect.cleandoc on it since docstrings include indents)
yaml is not widely use with python, btw there is some example:
name: my_project
version: 1.0
commands:
test_command:
command_name: test
description: just a test
parameters: None
When we set a category's perms and then create channels under it. Do we have to use something to sync the perms with the category or is it automatic ?
I think the latter, not sure
Guess i will have to try then
role_Bot: discord.Role = await GUILD.create_role(name="Bots",color= Colour.yellow(),hoist=True,permissions=Permissions.administrator)
what might i be doing wrong
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'flag_value' object has no attribute 'value'
The permissions parameter accepts a Permissions instance, while you passed a flag value. In your case, it should be something like:
perms = Permissions()
perms.administrator = True
await Guild.create_role(..., permissions=perms)
``` or you can also use `Permissions.all()`
oh, thanks
How can i check member invites?
you mean if he has an invite link or to get when a member joins with an invite to detect which member invited him?
running it in pycharm ig :/
!d discord.Embed.set_footer
set_footer(*, text=None, icon_url=None)```
Sets the footer for the embed content.
This function returns the class instance to allow for fluent-style chaining.
show us your code
wth
@bot.command()
async def status(ctx):
embed = discord.Embed(footer = "test" , title = "Status Checker" , description=f"The Bot Is Online ") , Timestamp=datetime.datetime,utcnow set_footer(*, text= "test", icon_url=None)
await ctx.send(embed=embed)
@bot.command()
async def status(ctx):
embed = discord.Embed(title = "Status Checker",
description=f"The Bot Is Online")
embed.set_footer( text="Test")
await ctx.send(embed = embed)
^
you're getting that error because you tried to read json from a file that was empty
Add {} to the JSON and the error gonna go away
as long as something’s there
are you running low on space?
i have a question i want to kick a tagged member out of the channel but if i run this it kicks everyone out of the channel
@commands.command(name='Kick')
async def Kick(self, ctx, membertokick : discord.Member):
guild = ctx.guild
user = membertokick
await ctx.channel.set_permissions(user, read_messages=False, manage_channels=False, manage_messages=False, manage_permissions=False)
await user.move_to(None)
await ctx.channel.purge(limit=1)
await ctx.send(f"Kicked {user} for you")
what am i doing wrong ?
bruh first of all why pass all those variables to other variables, you have one there is no need to re-assign it
why remove from a voice channel
cause its a private one
oh yeah seems logic
but the command's used in a text channel?
its used in the voice text channel
is there any reason why this message would stop updating
status_channel = client.get_channel(948495137846210571)
status_message = await status_channel.fetch_message(948496382254264360)
while True:
await status_message.edit(content=content, components=dev_components)
await asyncio.sleep(600)``` 
the new thing discord added
do you have to re-fetch the message every few hours or something
oh you'll probably check for that later I see
mm no
well it's not editing it after a few hours-days randomly
oh after days
maybe 
I won't say anything cuz I don't know
even BlackBull's question, there has to be something that went wrong in the implementation of voice channel text channels
if before.channel is None and after.channel is not None:
if after.channel.id == config.CustomChannelLobby:
guild = member.guild
name = 'Custom Channels'
category = discord.utils.get(member.guild.categories, name=name)
overwrites = {
guild.default_role: discord.PermissionOverwrite(read_messages=False, manage_channels=False, manage_messages=False, manage_permissions=False),
member: discord.PermissionOverwrite(read_messages=True, manage_channels=True, manage_messages=True, manage_permissions=True)
}
channel = await guild.create_voice_channel(member.name, category=category, overwrites=overwrites)
await member.move_to(channel)
await channel.send(f"I Created this channel for you {member.mention}")
seems allright ?
yes
then i still dont know what i am doing wrong Xd
the everyone role isn't able to read messages when the channel is created
is that intended
yes
its a private channel where i need to invite people to
and i want to be able to kick them out of it too
I actually have a bot that does the same thing lmao
but in my bot you can rename the voice channel with a command and set it to private with a command
and these stuff are stored

no my stuff isnt stored Xd
my internet went off so many times my database went offline and I can't get it online again
oof
so the bot ain't running
class vacancies(discord.ui.View):
def __init__(self, id, ctx):
super().__init__()
self.id = id
e_iron = discord.utils.get(ctx.guild.emojis, name="iron")
@discord.ui.button( label=f'{e_iron}', style=discord.ButtonStyle.red, row=1)
async def coun(self, interaction: discord.Interaction, button: discord.ui.Button):
button.label = "123"
await interaction.response.edit_message(view=self)
Dear, tell me why it gives an error?
It takes 2 arguments
But 1 was given
Do like (ctx.author.id,ctx)
@slate swan 
U cant do like this.
make the decorator indent same as init method
Lol
Oh, how do you write it all down?
Yeah
Also
it's emoji
Not label
!d discord.ui.Button.emoji
property emoji```
The emoji of the button, if available.
class vacancies(discord.ui.View):
def __init__(self, ctx.author.id, ctx):
super().__init__()
self.id = id
e_iron = discord.utils.get(ctx.guild.emojis, name="iron")
@discord.ui.button( label=f'{e_iron}', style=discord.ButtonStyle.red, row=1)
async def coun(self, interaction: discord.Interaction, button: discord.ui.Button):
button.label = "123"
await interaction.response.edit_message(view=self)
@commands.command(aliases = ["Вакансии", "вакансии"])
async def vacancies(self, ctx: commands.Context):
with open("./Эмодзи/Ресурсы/Железо.png", "rb") as image:
iron_1 = image.read()
iron = bytearray(iron_1)
await ctx.guild.create_custom_emoji( name = "iron", image = iron)
e_iron = discord.utils.get(ctx.guild.emojis, name="iron")
embed = discord.Embed(
color= 0x19ff19
)
file1 = discord.File("./ImageO/Экономика/Work/Выбери Профессию.png")
embed.set_image(url='attachment://Выбери Профессию.png')
await ctx.send(f"{e_iron}{e_organic}{e_wood}{e_details}{e_batteries}{e_shards}", file = file1, embed = embed, view=vacancies(ctx.author.id))
await asyncio.sleep(0,1)
await ctx.guild.delete_emoji(e_iron)
I write a command, it creates a button and an emoji. The emoji is for the button name. ID so that only the author of the command can press the button
lmao
Although if the command is immediately entered by 2 people, I think the bot will get confused in the name and give an error. really, as I was advised, I will make separate servers for emoji😅
Thank you all
hello, is it possible that a discord.py bot sends a message when my play activity changes?
Yes it's possible.
I can't find anything on the internet
My answers are amazing lol
yours specifically?
yes
!d discord.on_presence_update
discord.on_presence_update(before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") updates their presence.
This is called when one or more of the following things change:
• status
• activity
This requires [`Intents.presences`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.presences "discord.Intents.presences") and [`Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members "discord.Intents.members") to be enabled...
i think you need presence intent for that too
thank you very much !!
And member intents.
oh, probably
I have intents = discord.Intents.all()
Like a true coder has.
ofc have to enable it in bot setting too (tho i think you'd be gettimg an error if you hadn't)
does anybody know how can I check if the arg is not a member arg
!d isinstance
isinstance(object, classinfo)```
Return `True` if the *object* argument is an instance of the *classinfo* argument, or of a (direct, indirect, or [virtual](https://docs.python.org/3/glossary.html#term-abstract-base-class)) subclass thereof. If *object* is not an object of the given type, the function always returns `False`. If *classinfo* is a tuple of type objects (or recursively, other such tuples) or a [Union Type](https://docs.python.org/3/library/stdtypes.html#types-union) of multiple types, return `True` if *object* is an instance of any of the types. If *classinfo* is not a type or tuple of types and such tuples, a [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError") exception is raised.
Changed in version 3.10: *classinfo* can be a [Union Type](https://docs.python.org/3/library/stdtypes.html#types-union).
I tried this but didint worked
Are we talking about slash commands or message commands?
message comamnds
if isinstance(member, Member): you did like this?
Could you show what you've got so far?
ok
you probably need a type hint on the parameter too
More like need.
The typehint is also a converter.
Code:
async def avator(ctx,member:discord.Member=None):
if isinstance(member, commands.MissingRequiredArgument):
if isinstance(member, commands.errors.MemberNotFound):
#Mycode
else:
embed=discord.Embed(title="Error",description="Opps, There arg is not a member")
await ctx.send(embed=embed)```
def thing(ctx, member: Union[str,Member,None]) or something
The first one will never pass since that error is outside the scope.
so what should I do
Well since you made it an optional argument you need to remove the whole MissingRequiredArgument and error msg.
yeah the converters are pretty nice
how
I recommend separating the code so you first check if Member is not None then check if obj == Member
ok
it's supposed to be a member or nothing ?
ahh, its not working leave it
@client.event
async def on_presence_update(before,after):
channel=client.get_channel(986077790296231997)
await channel.send(f"New activity: {after.name} , {after.activity.name}")
tried this but not working
wait not obj == Member actually
What have you changed? I will code a bit for you for a small example.
@client.command()
async def balance(ctx):
await open_account(ctx.author)
users = await get_bank_data()
wallet_amt = users[str(users.id)]["wallet"]
bank_amt = users[str(users.id)]["bank"]
em = discord.Embed(title=f"{ctx.author.name}'s balance", color = discord.Colour.dark_theme())
em.add_field(name = "Wallet", value = wallet_amt)
em.add_field(name = "Bank", value = bank_amt)
await ctx.send(embed=em)
error:
Traceback (most recent call last):
File "C:\Python310\lib\site-packages\discord\ext\commands\bot.py", line 1329, in invoke
await ctx.command.invoke(ctx)
File "C:\Python310\lib\site-packages\discord\ext\commands\core.py", line 995, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "C:\Python310\lib\site-packages\discord\ext\commands\core.py", line 209, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'dict' object has no attribute 'id'
I changed to this:
if member is None:
Do you get an error.
How have you applied it to your code?
yes
but still not working so I left it
np
Okay, if you ever want to pick it up there are enough helpers here.
Did you enable intents inside the dev portal?
Yeah, normally everything is fine
hmm
any help?
intents = discord.Intents.all()
client = commands.Bot(command_prefix="m?",description="Mascarpone", intents=intents)
try to make it a listener
I can't help sorry
@client.listen()
async def on_presence_update(before,after):
channel = client.get_channel(986077790296231997)
await channel.send(f"New activity: {after.name} , {after.activity.name}")
I'm sorry I also don't help with this kind of code.
I can't think of anything atm maybe some other underlying issue here, I gotta eat as well parents are screaming.
no prob, thank you still! bon appetit
@sick birch You got some time?
Thanks :3
@commands.command(aliases = ["Вакансии", "вакансии"])
async def vacancies(self, ctx: commands.Context):
embed = discord.Embed(
color= 0x19ff19
)
file1 = discord.File("./ImageO/Экономика/Work/Выбери Профессию.png")
embed.set_image(url='attachment://Выбери Профессию.png')
await ctx.send(file = file1, embed = embed, view=vacancies(ctx.author.id))
Dear, tell me why the picture is not inside the embed
the file and the embed are separate
if you want an image in the embed use
!d discord.Embed.set_image
set_image(*, url)```
Sets the image for the embed content.
This function returns the class instance to allow for fluent-style chaining.
So I also wrote🥺
embed.set_image(url='attachment://Выбери Профессию.png')
the url cant be an attachment
Any help?
The get_bank_data function returns a dict and u can't use. .id with it
well it kinda can if you do
with BytesIO() as image_binary:
img.save(image_binary, "PNG")
image_binary.seek(0)
file = disnake.File(fp=image_binary, filename="image.png")```
embed.set_image(url="attachment://image.png")```
Uh then what should I do?
What do u want
and send the file
To show user’s balance
Use ctx.author.id there
k
async def open_account(user, ctx):
user = await get_bank_data()
with open("mainbank.json","r") as f:
user = json.load(f)
if str(user.id) in user:
return False
else:
user[str(ctx.author.id)] = {}
user[str(ctx.author.id)]["wallet"] = 0
user[str(ctx.author.id)]["bank"] = 0
with open("mainbank.json","w") as f:
json.dump(user,f)
return True
async def get_bank_data():
with open("mainbank.json","r") as f:
user = json.load(f)
return user
``` k?
str(user.id) needs to be str(ctx.author.id)
missed this line if str(user.id) in user:
Ye
Don't name var same
also you could just do user[str(ctx.author.id)] = {"wallet": 0, "bank": 0} to save lines
try setting a name to the file py file1 = discord.File("./ImageO/Экономика/Work/Выбери Профессию.png", filename="image.png") embed.set_image(url='attachment://image.png')
I think it's better to use message as an argument instead of ctx
if tou went to send a message, type message.channel.send
if you want the author, type message.author
The error is kind of self explanatory
your host wont allow you to write more data in your server's storage
Delete files you don't use anymore
Idk what he didn't understand
if you want to get the author of a message, you can use message.author
Union[User, Member]: Returns the author associated with this context’s command. Shorthand for Message.author
Ur works. You always help me thanks@slate swan
pleasure
..
i think you meant to write users which is a dict, instead of user
tutorial from swas.py right?
yes sir
yeah it gotta be users

Add {} to the json
k
Remove users
Error knowledge is must
ye
Add {} to mainbank.json
i did
Can u show
uh maybe put them in one line like {}
💀
isnt normal file opening and closing sync and u need aiofiles for async?
beg & balance works but my wallet isnt updated
it should add the amount i got in beg command
can I share my problem here or should I create a thread not to flood
share
Change load to dump
@client.event
async def on_member_update(before,after):
channel=client.get_channel(986077790296231997)
await channel.send(f"New activity (on_member_update): {after.name} , {after.activity}")
The bot detects when I start a game but after.activity returns my custom status and not the game I'm playing
why don't u just print the after object which prolly a dict then see what u need
there can be more than 1 activity
!d discord.Member.activities check all of them for your game
The activities that the user is currently doing.
Note
Due to a Discord API limitation, a user’s Spotify activity may not appear if they are listening to a song with a title longer than 128 characters. See GH-1738 for more information.
@discord.ui.button( emoji = f"{e_shards}", style=discord.ButtonStyle.secondary, row=3)
how to make a button inactive?
what library are you using?
oh thanks
i have a bot command which send image to a channel and uses that link in an embed so what do u think is the limit before bot gets rate limited for spamming message in a channel
thank you very much!
New activity (on_member_update): Noémimolette 🍰 , (<CustomActivity name='Every day I wake up, then I start to break up' emoji=<PartialEmoji animated=False name='🍰' id=None>>, <Activity type=<ActivityType.playing: 0> name='Baba Is You' url=None details=None application_id=576482762446602270 session_id=None emoji=None>, <Spotify title='Scarlet Forest' artist='Toby Fox' track_id='4zLEqCe2KCWBJLKN3RyWAG'>)
I do find my game inside of it "ActivityType.playing: 0" but how can I display that?
the ratelimits are dynamic so i have no idea about that
ic
dump(json, file)
it is loads
💀
thats actually a list of of Activity objects, you can iterate on it and see what activity is ActivityType.playing
it's not
It is
okay, thank you!
load and loads both exist, loads loads a dictionary from a string.
in the tutorial?
i thought u were telling loads instead of dump...
just json.dump
!d json.dump
json.dump(obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)```
Serialize *obj* as a JSON formatted stream to *fp* (a `.write()`-supporting [file-like object](https://docs.python.org/3/glossary.html#term-file-like-object)) using this [conversion table](https://docs.python.org/3/library/json.html#py-to-json-table).
If *skipkeys* is true (default: `False`), then dict keys that are not of a basic type ([`str`](https://docs.python.org/3/library/stdtypes.html#str "str"), [`int`](https://docs.python.org/3/library/functions.html#int "int"), [`float`](https://docs.python.org/3/library/functions.html#float "float"), [`bool`](https://docs.python.org/3/library/functions.html#bool "bool"), `None`) will be skipped instead of raising a [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError").
The [`json`](https://docs.python.org/3/library/json.html#module-json "json: Encode and decode the JSON format.") module always produces [`str`](https://docs.python.org/3/library/stdtypes.html#str "str") objects, not [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes "bytes") objects. Therefore, `fp.write()` must support [`str`](https://docs.python.org/3/library/stdtypes.html#str "str") input.
If *ensure\_ascii* is true (the default), the output is guaranteed to have all incoming non-ASCII characters escaped. If *ensure\_ascii* is false, these characters will be output as-is.

gn
No I'm not sleeping now lol
ic why send a pillow then
I'm on bed
oh
pj...
Just bored tbh
mhm
This channel description should be set to don't know python? coding a bot? , don't worry we are here to help
🤣
@shrewd apex I got another idea to prevent making a paginator!

I can show the information on a jinja template instead 👀
u don't write it down or save somewhere👀
The last time I used those were like 1-2 years ago
And they were saved in my old laptop
For some reason they weren't saved to my google ac

by the way do you know why on_member_update sends the same message twice?
cz u got two on_member_update events?
remove the port kwarg
I got only one on_member_update event?
my man loves those spaces/newlines
Another thing which can be added to PEP 9001!
I don't have any cog nor listener
Prolly double bot instances
def uwu():
\
\
\
\
\
\
\
\
return UwU()
better
NameError: name 'uwu' is not defined
uwu = UwU; uwu() better
what should I do I am doing this:
embed=discord.Embed(title="Error",description="Opps, There was no member")
await ctx.send(embed=embed)```
but its still giving that error
no
why u seeing for member?
check for error lol
you have to pass in the error not member
no
Nice
see now I edited it
so what should I do
...
Its still the same?
yea, it still gives me the error of missingrequiredarguement
@command.error
async def command_errorrororororo(ctx: Context, member: CommandError):
Give_Pep8_A_Stroke()
looks beautiful
nope
Then what does yr event looks like?
Hey guys anyone know why these buttons listed above each other?
This is giving me error:
embed=discord.Embed(title="Error",description="Opps, There was no member")
await ctx.send(embed=embed)```
it still gives me this error
I made sure there was only one instance and??
which buttons?
Niceee
These
??????
which library?
literally sent the message 8 times 😭
discord_components
on phone?
Do one thing
No im on PC
strange
create a nested list
buttons = [
[
Button(...),
Button(...)
], #this list is the first row
[
Button(...),
Button(...),
], #this is the second row
]
Ok
it changes with format in components
?
You're a Genius
.....
@maiden fable
This is the correct:
This is giving me error so tell me how to fix it:
embed=discord.Embed(title="Error",description="Opps, There was no member")
await ctx.send(embed=embed))```
it still gives me the MissingRequiredArguement error
Show the whole event dude
can you show more of your code?
ok:
async def avator(ctx,member:discord.Member):
if isinstance(member, commands.MissingRequiredArgument):
embed=discord.Embed(title="Error",description="Opps, There was no member")
await ctx.send(embed=embed)
userAvatarUrl = member.avatar_url
embed=discord.Embed(title=member.display_name+"'s"+" Avator")
embed.set_image(url=userAvatarUrl)
await ctx.channel.send(embed=embed)```
I disagree with all my uwuness
Isnt there a ) to much?
wtf
...
😔 ay wtf, that goes in the error handler.
@slate swan all yours
i was mind blown literally nothing left
And @slate swan's too
@bot.command(name='avator')
async def avator(ctx,member:discord.Member):
userAvatarUrl = member.avatar_url
embed=discord.Embed(title=member.display_name+"'s"+" Avator")
embed.set_image(url=userAvatarUrl)
await ctx.channel.send(embed=embed)
@avatar.error
async def avatar_error(ctx, error):
if isinstance(error, commands.MissingRequiredArgument):
embed=discord.Embed(title="Error",description="Opps, There was no member")
await ctx.send(embed=embed)
and fix the command spellings
kill python.exe and py.exe
its avatar not avator
delete*
No, I mean kill
I was being sarcastic but OKAY
ok
Cool
Wait @balmy bobcat
before launching, check if there are any other python processes
tysm it worked!
I did check, there wasnt anything named "py" or "python"
Cool
still sends me the same message twice
just reset ur bot token
yeah the file runs, but the bot wont be responding twice
🚶♂️ just use the terminal while running code tbh
Yeah
thankfully
still sends message twice yet I did reset the token, closed my IDE and launched it from terminal
I'll just send the part that matters since my code is 400 lines long
import discord
from discord.ext import commands
intents = discord.Intents.all()
client = commands.Bot(command_prefix="m?",description="Mascarpone", intents=intents)
@client.event
async def on_ready():
await client.change_presence(activity=discord.Game('m?info_mascarpone'))
msc_channel=client.get_channel(986077790296231997)
await msc_channel.send("Coucou! Me voila allumée!")
await msc_channel.send("Nous sommes le {0} et il est {1}.".format(current_time[:itime],current_time[itime:]))
@client.event
async def on_member_update(before,after):
if after.id == 475686699381424128:
channel=client.get_channel(986077790296231997)
listeactivite = str(after.activities)
if "touhou" in str(listeactivite).lower():
await channel.send("J'en connais une qui joue à Touhou :joy_cat:")
client.run(TOKEN)
pip install discord-py-slash-command
Already done
cz the on_ready event is fired multiple times, it'll run the function multiple times....
or is the member_update event erroring?
@commands.slash_command(description="help")
async def tests(ctx):
await ctx.send(":hmm: Help \n> :hmm: Misc \n> :hmm: features \n> :hmm: Commands \n> :hmm: Fun \n> :hmm: Invite\n``Type _<command> for more info.")
``` my code
not a single error
(sorry for being french)
Not working
Had the same problem yesterday, didn't find any soluce
use some fork, or discord.py v2.0, discord-py-slash-command is outdated
do anyone here know all possible arguments for the data dictionary requests.post(url, json=data) when sending discord messages using webhooks? or just embeds properties and profile pictures
Is there an API for app_commands because I can't find anything and Im trying to figure out some stuff lol
does somebody know how can I fix this error:
Error:
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'append'
Code:
async def cdcmd(ctx,cmd:str):
server_id= ctx.guild.id
file_name = f"servers_cmds\\{server_id}.yml"
if cmd == "avator":
with open(file_name, 'r+') as f:
content = yaml.safe_load(f)
content["avator_cmd"]["D_Channels"].append([ctx.channel.id])
f.seek(0)
yaml.dump(content, f)
embed=discord.Embed(title="Command Enabled",description="**Avator Command Has Been Disabled For This Channel**")
await ctx.send(embed=embed)
f.truncate()```
I guess content["avator_cmd"]["D_Channels"] is NoneType
yes it contains nothing but I want to store I am storing channel id in it
if its NoneType how do I fix it
and you have already checked https://discord.com/developers/docs/resources/webhook#execute-webhook ?
not yet, but ty for help
??????
hope it helps, i have never used discord webhooks so i don't really know that stuff, i just googles a bit
ok but I fixed it
it did, i just never know where to search
Hey... My discord bot doesnt run in discord threads :\
Does anyone know why this happens... Are there any workaround?
I did some research, and on_member_update fires twice because my bot is on two different guilds: is there any way to avoid this?
How do I make global command to check if a certain category iD and it doesn’t work in dms
glad to hear it helped 🙂 👍
Does anyone know the api for discord ui, like I'm able to make textinputs but are there other inputs for a dropdown for example?
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.
does somebody know how can I check if serverid is not in this key, I tried this:
if server_id not in data["avator_cmd"]["D_Channels"]:
its a yaml file
@discord.ui.button( emoji = f"{e_сross}", style=discord.ButtonStyle.secondary, row=4)
async def exit(self, ctx):
await ctx.message.delete()
Dear, tell me why it gives an error?
discord.ui.button(*, label=None, custom_id=None, disabled=False, style=<ButtonStyle.secondary: 2>, emoji=None, row=None)```
A decorator that attaches a button to a component.
The function being decorated should have three parameters, `self` representing the [`discord.ui.View`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View "discord.ui.View"), the [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction") you receive and the [`discord.ui.Button`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.Button "discord.ui.Button") being pressed.
Note
Buttons with a URL cannot be created with this function. Consider creating a [`Button`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.Button "discord.ui.Button") manually instead. This is because buttons with a URL do not have a callback associated with them since Discord does not do any processing with it.
async def exit(self, interaction: discord.Interaction, button: discord.ui.Button):
...
????
@slate swan put the information into an array and then check if not in
is manage_server not the name for the manage server permission?
how
like read the file, and put the informations into an array?
list = ['one', 'two']
if x not in list:
I am checking it in a yaml file
are u reading it
yes
u dont know how to put the results into an array?
i guess i'm to stupid to understand your question
im smart enough to understand his question im just to stupid to fix it lol
wait
is there an api for all the permission names
for has_permissions
@app_commands.command(name='load', description='Enable a command')
@app_commands.describe(command_name="Command name")
@app_commands.checks.has_permissions(manage_server=True)
async def load(self, interaction: discord.Interaction, command_name: str):
It says manage_server isn't a valid permission 😐
@stiff fern I am trying to check if ctx.channel.id not in white_servers: and the white_servers is an array in the yaml file
and here how the variable it made:
white_servers = data["avator_cmd"]["D_Channels"]
homie i cant even get command checks to work, i doubt i can help you lol
me?
yes
oh
this is not working?
yes
uhm, maybe try casting channel_id to str
ok
it even dont gives me an error
can you like print white_servers to see if that is correctly read ?
ok
@discord.ui.button( emoji = f"{e_сross}", style=discord.ButtonStyle.secondary, row=4)
async def exit(self, interaction: discord.Interaction, button: discord.ui.Button):
Dear, what to write to delete the message?
it prints out the correct id:
[[962655220750491661]]
but idk why is it not working when I try to compare it
lemme test something real quick
ok
the double brackets is the problem
oh
array = [[1], [2]]
if 1 in array:
print("in")
how do I fix it but in the yaml it like this:
D_Channels:
- - 962655220750491661```
uhm what does your yaml give you back when you add multiple ids?
is it like [[0][1]]?
wait
its like this:
[[962655220750491661], [962655220750491661]]
@upbeat ruin ?
array = [[1], [2]]
if any(1 in sub for sub in array):
print("in")
where is sub created
in the for part
ok
thats the fun part of a high level language 😮
is there a way to send a message, with the username/ userid ?
If I get a reaction to a message, how do I delete that reaction?
@discord.ui.button( emoji = f"{e_сross}", style=discord.ButtonStyle.secondary, row=4)
async def exit(self, interaction: discord.Interaction, button: discord.ui.Button):
Dear, what to write to delete the message?
datetime.datetime.now(datetime.timezone.utc) ?
tysm it worked
so now how do i send user messages that didn't message the bot ? 😄
huh wdym?
lets say i have guids or usernames, is there a possibility to send messages or do they have to be in a specific server/group ?
You gotta have at least one mutual guild with the user to send DMs
in short, the user gotta be in bot.users
@discord.ui.button( emoji = f"{e_сross}", style=discord.ButtonStyle.secondary, row=4)
async def exit(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.delete()
Dear, what to write to delete the message?
so the same server is not enough? because the bot.users only returns the bot
it is enough
what message u wanna delete?
I enter a command and a message with a button is displayed. I click on the button and this message is deleted
!d discord.Interaction.original_message
await original_message()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Fetches the original interaction response message associated with the interaction.
If the interaction response was a newly created message (i.e. through [`InteractionResponse.send_message()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionResponse.send_message "discord.InteractionResponse.send_message") or [`InteractionResponse.defer()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionResponse.defer "discord.InteractionResponse.defer"), where `thinking` is `True`) then this returns the message that was sent using that response. Otherwise, this returns the message that triggered the interaction (i.e. through a component).
Repeated calls to this will return a cached value.
but the bot.users only returns itself in the list?
U need members intent
@discord.ui.button( emoji = f"{e_сross}", style=discord.ButtonStyle.secondary, row=4)
async def exit(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.delete_original_message()
🥺
Ah
U first gotta reply to the msg before deleting
smth like interaction.response.defer()
hello, how do i convert this boring discord "live" notification (for twitch) into a richer notification, including the category (game) streamed, title of stream and maybe the thumbnail too
@loop(seconds=90)
async def check_twitch_online_streamers():
channel = bot.get_channel(966493808869138442)
if not channel:
return
notifications = get_notifications()
for notification in notifications:
await channel.send("We are now live at https://www.twitch.tv/stream")
Wow it works, thanks❤️
looks like i'm to stupid for this rn, thanks anyway
Nice
Nah, u ain't stupid
Its just discord being discord
just to wrap some stuff up:
the bot and i are in the same discord server, how do i send myself messages without messaging the bot?
!d discord.Member.send
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
!d discord.Guild.get_member
get_member(user_id, /)```
Returns a member with the given ID.
Changed in version 2.0: `user_id` parameter is now positional-only.
hello, i have this error with this part of my codes, can someone help me please ? thanks
ok i'm just stupid but how do i get the guild obj?
you can fetch it
COMBINING_ENCLOSING_KEYCAP is not defined
or use the Context class
ctx.guild
in short, just remove the {} around it
the member argument is None
in the ctx.guild.members is only the bot visible.. <.<
members intent
you should do member = member or ctx.author after the function signature
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot 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
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
as hunter said^
@commands.command()
async def stats(self, ctx, member: discord.Member=None):
if member is None: member = ctx.author
async with self.bot.db.execute("SELECT exp FROM guildData WHERE guild_id = ? AND user_id = ?", (ctx.guild.id, member.id)) as cursor:
data = await cursor.fetchone()
exp = data[0]
async with self.bot.db.execute("SELECT exp FROM guildData WHERE guild_id = ?", (ctx.guild.id,)) as cursor:
rank = 1
async for value in cursor:
if exp < value[0]:
rank += 1
lvl = int(math.sqrt(exp)//self.bot.multiplier)
current_lvl_exp = (self.bot.multiplier*(lvl))**2
next_lvl_exp = (self.bot.multiplier((lvl+1)))**2
lvl_percentage = ((exp-current_lvl_exp) / (next_lvl_exp-current_lvl_exp)) * 100
embed=discord.Embed(title=f"**:bar_chart: Statistiques**", color=0xFF8100, timestamp=ctx.message.created_at)
embed.add_field(name="Niveau :", value=str(lvl))
embed.add_field(name="Expérience :", value=f"{exp}/{next_lvl_exp}")
embed.add_field(name="Rang :", value=f"{rank}/{ctx.guild.member_count}")
embed.add_field(name="Progression :", value=f"{round(lvl_percentage, 2)} %")
await ctx.reply(embed=embed)
``` Hello, i have this error with this code, dont know how to fix it thanks for helping me :)
the bot has no such attribute so you must set it and over doing
if member is None: member = ctx.author
you can just do
member = member or ctx.author
if member is None then ctx.author will be member's value
i already have it in my code
how can I make every such time the presence change
try it with a loop but it doesn't change
embed = discord.Embed(
title = "Шахтер",
description= "123""321",
color= 0x19ff19
)
Dear, tell me how to write so that 123 is on one line and 321 on the other?
When do you want it to change? On a time interval?