#discord-bots
1 messages · Page 253 of 1
!d discord.Message.components
A list of components in the message. If Intents.message_content is not enabled this will always be an empty list unless the bot is mentioned or the message is a direct message.
New in version 2.0.
this is a list of all components message has
thanks
when you gather button you need you just need to set .disabled to True
!d discord.ui.Button.disabled
property disabled```
Whether the button is disabled or not.
so i dont need to edit the view after?
?
when you wanna set a buttonn to disable you need to edit the view after
yes
WHY ????
Traceback (most recent call last):
File "/home/container/.local/lib/python3.11/site-packages/discord/app_commands/commands.py", line 842, in _do_call
return await self._callback(interaction, **params) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/container/otrobot.py", line 671, in kick
await interaction.followup.send(f"{interaction.user.mention} you can't kick my developers!")
File "/home/container/.local/lib/python3.11/site-packages/discord/webhook/async_.py", line 1800, in send
data = await adapter.execute_webhook(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/container/.local/lib/python3.11/site-packages/discord/webhook/async_.py", line 219, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10015): Unknown Webhook
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/container/.local/lib/python3.11/site-packages/discord/app_commands/tree.py", line 1248, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/container/.local/lib/python3.11/site-packages/discord/app_commands/commands.py", line 867, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/container/.local/lib/python3.11/site-packages/discord/app_commands/commands.py", line 860, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'kick' raised an exception: NotFound: 404 Not Found (error code: 10015): Unknown Webhook```
show code of the kick command
@bot.tree.command(name="kick", description="Kick member from guild")
async def kick(interaction, member : discord.Member, *, reason : str):
if (not interaction.user.guild_permissions.kick_members):
await interaction.response.send_message(f"You are not authorized to use this command {interaction.user.mention}")
return
if (interaction.user == member):
await interaction.followup.send(f"{member.mention} you can't kick yourself!")
return
if (member.id == 944574924234846298):
await interaction.followup.send(f"{interaction.user.mention} you can't kick my developers!")
return
await member.send(f"You have been kicked by {interaction.user} from {interaction.guild.name}.\nReason : {reason}")
await member.kick (reason = reason)
await interaction.response.send_message(f"{member.mention} has been kicked from the guild")```
I know lol
!d discord.Member.kick
await kick(*, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Kicks this member. Equivalent to [`Guild.kick()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.kick "discord.Guild.kick").
Its just followup.send
yes
Is there a @app_commands check to see if the bot itself has a certain permission
!d discord.app_commands.checks.bot_has_permissions
@discord.app_commands.checks.bot_has_permissions(**perms)```
Similar to [`has_permissions()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.checks.has_permissions "discord.app_commands.checks.has_permissions") except checks if the bot itself has the permissions listed. This relies on [`discord.Interaction.app_permissions`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction.app_permissions "discord.Interaction.app_permissions").
This check raises a special exception, [`BotMissingPermissions`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.BotMissingPermissions "discord.app_commands.BotMissingPermissions") that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CheckFailure "discord.app_commands.CheckFailure").
New in version 2.0.
thank you
👍
Like this? ```py
@app_commands.checks.bot_has_permissions("manage_webhooks")
oh nvm
🤦
@app_commands.checks.bot_has_permissions(manage_webhooks=True)
no here is example usage for has_permissions its the same for this one ```py
@tree.command()
@app_commands.checks.has_permissions(manage_messages=True)
async def test(interaction: discord.Interaction):
await interaction.response.send_message('You can manage messages.')
ye lol
how can i add the description for an embed? I though add_field would, but it needs a name
guys, i'm getting the error
AttributeError: 'NoneType' object has no attribute 'global_name'
when i try to use guild.owner.global_name in my code, i'm using the 2.3.0 discord.py library, someone know why this is happening?
i'm doing a for guild in bot guilds: guild.owner.global_name
it works fine in my pc version but dont work fine in the venv version
!d discord.Embed.description
The description of the embed. This can be set during initialisation. Can only be up to 4096 characters.
when you create embed you can pass the description embed = Embed(..., description=...)
looks like guild.owner is None
i see
how that can be possible?
no idea 
and how can u remove all the fields? i see remove_field(), but anyway to remove all of them?
!d discord.Guild.owner
property owner```
The member that owns the guild.
it is optional in the docs
alright ty ' ~'
oh, clear_fields
there is method to remove all
!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...
!d discord.Embed.clear_fields
clear_fields()```
Removes all fields from this embed.
This function returns the class instance to allow for fluent-style chaining.
Changed in version 2.0: This function now returns the class instance.
yeah got it, ty
for comp in msg.components:
comp.disabled = True
await msg.edit(view=msg.components)
why does this not work? i get no error
hi! i'm making a discord bot using python using vscode, and the code runs fine and it logs into discord (bot becomes active). None of the commands work , how can i fix this?
cause view has to be View not components list
and you are prolly looking for view=self but hard to say from this small amount of code
(i'll change hte token later)
what do you get in console?
in terminal?
yes
and nothing below?
nothing under that
i already got it, ty tho
what do you see when you do .help?
in the terminal or in my bot testing channel?
in discord channel
👍
do u know by chance if editing a embed with an image attached feels laggier than editing an embed without?
well, does it for you?
I would think it does
yeah, it does, like, there is a small, very small, delay before showing the edited embed. I tried editing the embed without an image and it is faster. But i saw another bot which is more fluent with a thumbnail instead
how to check by whom a member is invited?
hint might be to use ctx.typing:
so it actually shows the user the bot is doing something
They literally just did
Why would you even want that though when there are better examples on the github repo
in text form
just use an ocr tool 💀 or even just type it
Is it possible to do this, so basically my bot is a word blocker if you say a swear it will delete and warn, now I want it so if I have the highest role in my server, I can say anything I want and not getting deleted if that makes sense
U can just exclude the roles that u want to
Any code reference for this?
How are you checking the messages for swear words?
if any(word in content for word in blocked_words):
await message.delete()
Ok create a variable for excluded role and put the role ID there
How would I add it into my if statement
if any(word in content for word in blocked_words) and not any(role.id == excluded_role_id for role in message.author.roles):```
Alr thanks I’ll try it
excluded_role_id = '1116182568421830696'
if any(word in content for word in blocked_words) and not any(role.id == excluded_role_id for role in message.author.roles):
If i have the role it still sends
Role ids are stored as integers
Another way to check if user has role is message.author.get_role(id) is not None
In some cases it's better
async def on_message(message):
if not message.author.bot:
content = message.content.lower()
if any(word in content for word in blocked_words):
deleted_message = message.content, {message.author.mention}
await message.delete()
await message.channel.send(f"bad word ")
webhook.send(deleted_message)```
how can i make it instead of sending the bad word i want to send the whole message so if i had "chain is a (BAD WORD)" it wil send the whole message to logs
can anyone help
put it in a codeblock
done!
Your deleted_message is a tuple of message content and set with single string of author's mention
How much sense does it make
that should work, u just have to format the message, and also remove deleted_message = message.content, {message.author.mention} and change it, not correct syntax
And how is webhook defined
not the whole code
i just sent the function for referece
Yeah but how
webhook = Webhook.from_url("", adapter=RequestsWebhookAdapter())
How could i do it
i dont want to spoonfeed you, but ill tell you a tiny bit, just how you're defining deleted_message, if you are trying to make it concatenate message.content and the users mention, you'd use a + not a comma, and remove the curly braces
There's not even adapter param is there? Is this a fork
and you'd prob just want to f-string it, so u can add a space
Ty
ofc
hellooo i made this bot and it should react to a emoji and it gives you a one in 15,000 chance of getting a certain role and else you get a different role and you cant react anymore to it for 10 minutes and this bot will be used for a minimum of 15k people is there any way i can optimize it so it doesnt crash on launch?
If it crashes, a traceback is more useful than the code
Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.
A full traceback could look like:
Traceback (most recent call last):
File "my_file.py", line 5, in <module>
add_three("6")
File "my_file.py", line 2, in add_three
a = num + 3
~~~~^~~
TypeError: can only concatenate str (not "int") to str
If the traceback is long, use our pastebin.
Is there any way to show bot embed to members who don't have permission to chat on a channel and on the same channel other members with permissions see their daily chats?
is it possible to get the latest message in a certain channel?
is client.name a thing?
Yes it's possible, there's a few ways to do it
!d discord.Client.user
property user```
Represents the connected client. `None` if not logged in.
The user’s username.
the bots name
@client.tree.command(name="update", description=f"get the latest update on {name}")
async def update(interaction: discord.Interaction):
channel2 = client.get_channel(1112066492574478378)
message = await channel2.fetch_message(channel2.last_message_id)
await interaction.response.send_message(f"the latest update is: ``{message}``")
``` i tried this
the latest update is: <Message id=1117364590334971914 channel=<TextChannel id=1112066492574478378 name='bot-updates' position=6 nsfw=False news=True category_id=1112053260879147134> type=<MessageType.default: 0> author=<Member id=821789676255969301 name='zagzag990' discriminator='0482' bot=False nick=None guild=<Guild id=1112053259604074618 name='zagzag support' shard_id=0 chunked=True member_count=8>> flags=<MessageFlags value=1>>
but thats the response
Your bot or other bots?
my bot
And? What's wrong
does client.name work?
And what's wrong with it
No, it's client.user.name
I literally just sent the docs
i just want the message not info of the channel
just the latest message
That's the message
It's the repr of a message object, which is returned by the fetch_message method
what should i do?
I just want to get the latest message
thats all
And you got it?
no i got the channel id, channel name, the guild name, and way more
i didn't even get the message
You're kidding
that is not the message that is the message id
no the latest message
not all messages
Are you on the same topic
yes
And the last message not a message object???
oh wait is it?
You literally just fetched the last message and store it as message
I shouldn't have to explain this
message is a varible
And?
so do i just do message = message.content_channel2
Do you know discord.py or just Python in general
i know more in python in general
File "main.py", line 19, in <module>
name = client.user.name
AttributeError: 'NoneType' object has no attribute 'name'```
uhh idk why i got that error
what does that mean if it not logged in
||spolier: client did not log in to discord api yet||
oh
let me do a quick guess and say you're trying to make a startup task?
No
doesnt work im on centos 7 vm and its commandl ine only
then navigate to the directory that contains python files and look for file that could install the certificate
for macos its Install Certificates.command
file
which?
Me first time seeing someone else using termius
hey
i am getting such a error wile importing token form .env file
ImportError: cannot import name 'load_dotenv' from 'dotenv
can anyone help me out pls
did you install python-dotenv package?
yup
thank u for the help
but issue is sloved
did a messy mistake
mhm
btw can i ask one more thing?
why not?
like i am trying to make a map for a dsicord bot game
and i want to put latitude and logitude system in it
but cant make my brain think how to do it any idea?
how you want that to work?
well i want to assin servers some locations and track the ppl movements with it
to make it like a game
like two server have locations and lat and long will help to determain distance and time for person to travel like a real life traveling
tho u can consider hrs to secs in game
code: https://hastebin.skyra.pw/zikacodife.py
error:https://hastebin.skyra.pw/uhiyehexay.nginx
this code worked before and honestly have no idea why it doesnt work
you could store it in database or something like this
where this guild is located
like coordinates
yup i am planning to use mongo db
consider it like u are in real life and
its __init__
u wana taravel form one place whose cordinates are 11 long and 22 lat
and u wana go to 44 long and 33 lat
so thats what i wana do in discord
yeah i understand
im saying that you can store it in the database
the coordinates for each guild
yaa data can be stored
i can use a class
tho i have never used a class i am a biggner
never done oops programmign

when you use a class then the data will be removed when you restart the bot
sorry which line do i need to change?
data in the database is always there
so using class wont be a good idea in case of bot right?
the constructor of your custom client the constructor method in python is called __init__ not init
so i can ressgin the data
not in this case
ohke will consider that in mind
ig first i should finish my discord.py basics
one more question @slate swan
and the base class init call must be __init__ as well
well as i am a biggner in python
i have learnd till oop
like just know little basics of classes
so do i need to learn more or shall i shift to discord.py for now
as i want to build the bot
will it affect the bot making ?
Traceback (most recent call last):
File "C:\Users\Pablo\PycharmProjects\teknikbot\testing.py", line 58, in <module>
client = MyClient(intents=intents)
^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: MyClient.init() missing 1 required positional argument: 'args'
that gives this error
yes you need to know classes good if you want to create bots that are written in pythonic way
:)
it worked before
idk what changed
its *args
the * matters
so need to learn them
or shall i use chat gpt

you can make basic bot without classes but when it will grow you will need classes at some point
its better to know them from the beggining
alr
well the bot is quit big and will take a month
and need to plan the layouts to
so i can make a basic structure and learn the python simantaniously
i will make sure to put bot in pefrect conditon before i launch it
@slate swan ahh can i ask one more thing if u dont mind pls
dont ask to ask just ask
ohh alr thank u sir
its like as i have started learning python i wana polish my skills in it now
for basics
so i tried leetcode
but quesitons there were out of my understanding even the first one
any suggestion
where can i fix that issue of mine
well i didnt understand half of the coding problems too and what i did was watching someone solve them on youtube
worked for me
alr
how do make it so the user has a choice on what person they want to kick?
In slash command?
No
Where then
So a dropdown
!d discord.ui.UserSelect
class discord.ui.UserSelect(*, custom_id=..., placeholder=None, min_values=1, max_values=1, disabled=False, row=None)```
Represents a UI select menu with a list of predefined options with the current members of the guild.
If this is sent a private message, it will only allow the user to select the client or themselves. Every selected option in a private message will resolve to a [`discord.User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User").
New in version 2.1.
https://github.com/Rapptz/discord.py/blob/master/examples/views/dropdown.py
and here is example usage it uses default Select you need to swich it to UserSelect
and you dont pass options
options are all users already
what library are you using?
my discord bot should add a role but it gets to the print("loser") and doesnt give the role it doesnt give any errors and i cant find out why it doesnt give the role
want to know your issue? 🙂
it's your try except
you're only handling the HttpException, which hides all other errors
so you have 2 options:
- remove that stinky try except
- also except handle all other errors
ily
imma try that
@client.tree.command(name="help", description="get help on commands")
async def help(interaction: discord.Interaction, choose_command: Literal["welcome setup", "leave setup", "verification setup", "anti spam setup"]):
channel2 = client.get_channel(1112053260879147130)
await channel2.send(f"help command used by {interaction.user}")
if choose_command == "welcome setup":
embed1 = discord.Embed(name="How to setup welcome manager")
embed1.add_field(name="welcome manager", value="type /welcome-setup put your welcome channel and your welcome message if you want to mention a user do {mention}.")
await interaction.response.send_message(embed=embed1)
if choose_command == "leave setup":
embed2 = discord.Embed(name="How to setup leave manager")
embed2.add_field(name="leave manager", value="/leave-setup put your leave channel and your leave message do {mention} to mention a user.")
await interaction.response.send_message(embed=embed2)
if choose_command == "verification setup":
embed3 = discord.Embed(name="How to setup verification system")
embed3.add_field(name="leave manager", value="type /verify-setup your channel is the channel for the users to verify in and the verified_role is your verified role")
await interaction.response.send_message(embed=embed3)
if choose_command == "anti spam setup":
embed4 = discord.Embed(name="How to setup anti spam")
embed4.add_field(name="how to setup anti spam", value="Type /anti-spam-on your mute_duration_minutes is how many minutes you want the member to get muted when they spam. (only works in minutes) 1 hour = 60 minutes, 2 hours = 120 minutes and 1 week = 10080 minutes")
await interaction.response.send_message(embed=embed4)```
File "/home/runner/zagzag/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 842, in _do_call
return await self._callback(interaction, **params) # type: ignore
File "main.py", line 52, in help
embed4 = discord.Embed(name="How to setup anti spam")
TypeError: Embed.__init__() got an unexpected keyword argument 'name'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/zagzag/venv/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1248, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/runner/zagzag/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 867, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/home/runner/zagzag/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 856, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'help' raised an exception: TypeError: Embed.__init__() got an unexpected keyword argument 'name'
what does this error mean
ive done the embed right right?
unfortunately not no
what does the error say & what do you understand by it?
how?
that name is not a thing in the field
idk this makes no sense
dude
let's have a look at the docs together, ok?
ok.
you're basically doing discord.Embed(name="something")
ssst, don't tell him yet
find your attribute
that should be enough of a hint
ohhh title right?
indeed
im ngl why are u hardcoding all that
wdym?
you can have subcommands
cause thats only way i know how to do it
at least it works
i mean yes it does work
but it's not really the most satisfying code to look at or the most efficient
true
fairly sure this is a error where i just did something dumb but this is my error and how the code looks:
2023-06-16 21
06 ERROR discord.client Ignoring exception in on_raw_reaction_add
Traceback (most recent call last):
File "C:\Users\Pablo\PycharmProjects\teknikbot\venv\Lib\site-packages\discord\client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "C:\Users\Pablo\PycharmProjects\teknikbot\test2.py", line 57, in on_raw_reaction_add
await payload.member.add_roles(role)
File "C:\Users\Pablo\PycharmProjects\teknikbot\venv\Lib\site-packages\discord\member.py", line 1044, in add_roles
await req(guild_id, user_id, role.id, reason=reason)
File "C:\Users\Pablo\PycharmProjects\teknikbot\venv\Lib\site-packages\discord\http.py", line 738, in request
raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access
code:https://hastebin.skyra.pw/kocivoraye.py
error says it all
you're most likely editing permissions while your bot doesn't even have the correct roles for it
hmm
if your bot has default roles, don't expect it to give you a role he doesn't have
Doesn't it raise BotMissingPermissions in that case (or whatever the exact error is)
also true
hmmm
bot it's a permissions issue either way
because i am pretty sure it has administrator
you're not trying to edit roles of an admin, right?
nope
i am trying again
wait\
That's not how you use redirect
i am smart
check in your actual bot roles, not that link
No you are not at all
Why do you even need identify scope
You know what it is?
When generating oauth2 link if you dont know what it does choose only bot and application commands
If its for the bot only
i know i just didnt understand anything 😭
If you know what you are doing and what redirect is you can choose rest
it had a role that was above everhtying with admin perms i deleted the role gave him a new role and now it works
thank you guys i appreciete it:)))
Traceback (most recent call last):
File "/home/runner/DevHood/venv/lib/python3.10/site-packages/discord/ext/commands/converter.py", line 1233, in _actual_conversion
return converter(argument)
TypeError: 'module' object is not callable
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/DevHood/venv/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 1350, in invoke
await ctx.command.invoke(ctx)
File "/home/runner/DevHood/venv/lib/python3.10/site-packages/discord/ext/commands/core.py", line 1015, in invoke
await self.prepare(ctx)
File "/home/runner/DevHood/venv/lib/python3.10/site-packages/discord/ext/commands/core.py", line 932, in prepare
await self._parse_arguments(ctx)
File "/home/runner/DevHood/venv/lib/python3.10/site-packages/discord/ext/commands/core.py", line 839, in _parse_arguments
transformed = await self.transform(ctx, param, attachments)
File "/home/runner/DevHood/venv/lib/python3.10/site-packages/discord/ext/commands/core.py", line 709, in transform
return await run_converters(ctx, converter, argument, param) # type: ignore
File "/home/runner/DevHood/venv/lib/python3.10/site-packages/discord/ext/commands/converter.py", line 1342, in run_converters
return await _actual_conversion(ctx, converter, argument, param)
File "/home/runner/DevHood/venv/lib/python3.10/site-packages/discord/ext/commands/converter.py", line 1242, in _actual_conversion
raise BadArgument(f'Converting to "{name}" failed for parameter "{param.name}".') from exc
discord.ext.commands.errors.BadArgument: Converting to "discord.member" failed for parameter "member".
I Made a ban system
and i got this error
discord.Member
Lemme try it
anyone know why interaction fails when im using embeds to respond to a button interaction?
class Confirm(nextcord.ui.View):
def __init__(self):
super().__init__()
self.value = None
@nextcord.ui.button(label="Confirm", style=nextcord.ButtonStyle.danger)
async def confirm(self, button: nextcord.ui.Button, interaction: nextcord.Interaction):
await interaction.response.send_message("Confirming", ephemeral=True)
self.value = True
self.stop()
@nextcord.ui.button(label="About Moon", style=nextcord.ButtonStyle.blurple)
async def cancel(self, button: nextcord.ui.Button, interaction: nextcord.Interaction):
embed = nextcord.Embed(title="About Moon", description="This server is completely based around the Discord bot 'Moon' as a support server for all of the users around the world.")
embed.add_field(name="Quick Links", value=" (Documentation)[https://moon-10.gitbook.io/moon/]")
await interaction.response.send_message(embed=embed, ephemeral=True)
self.value = False
self.stop()
@client.command()
async def ask(ctx):
view = Confirm()
await ctx.send("Do you want to confirm somthing.", view=view)
await view.wait()
if not view.value == None:
print("Timed Out")
if view.value == True:
print("Comfirmed")
if view.value == False:
print("Cancelled")```
Can you tell us more about what you're doing and what happens?
i fixed it its all g
Hi
You can help me please for create command for get number member join with all invite create by one member and check if all member have join is already on the server or if he have leave
how do i have text in the same line with the spaces
just looks like name fields of inline fields
embed.add_field(name = 'Moderator', value= f'@Soul#9346', inline = True)
embed.add_field(name = 'Reason', value= f'Bad Word Usage', inline = True)```
what am i doing wrong 😭
What's even wrong
await message.channel.send(f"{message.author.mention}, Please refrain from using those words. Please use appropriate language.")```
Traceback (most recent call last):
File "C:\Users\chain\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "C:\Users\chain\Desktop\Recover_Cord (1)\Recover Cord\PRIVATE BOTS\MEE6 (Blacklist Words + Links)\blocker.py", line 52, in on_message
await message.delete()
File "C:\Users\chain\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\message.py", line 1023, in delete
await self._state.http.delete_message(self.channel.id, self.id)
File "C:\Users\chain\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\http.py", line 250, in request
raise NotFound(r, data)
discord.errors.NotFound: 404 Not Found (error code: 10008): Unknown Message
Show the full code
What? They're trying to send a message to the deleted message's channel
yeah you're right im stupid
fixed
Can you point me to an online resource that explains how to make discord bot in python
read the channel description
Hey, I am trying to create slash commands the code is fully okay with no errors or anything but the slash commands are not registering event at guild level
even after it its not showing
Not Showing Slash Cmd Even after this command
Hi, i need help with discord intents
Error Code : AttributeError: 'Intents' object has no attribute 'message_content'
My Code : import discord
from discord.ext import commands
import requests
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix='!', intents=intents)
Try printing the await self.tree.sync()
Like assign it as a variable then print(f"{len(variable_name)} commands have been synced")
There doesn't seem to be an issue here
Try doing pip freeze
Okay i will
And check dpy version
How to make my mysql db never timeout? im using python to make my discord bot.. but it stops working every 8 hours (if no one uses the commands)
how do you connect to the database?
python code and connect to db using mysql workbench
okay but how do you connect in code
what library
mysql.connector
i belive this is synchronous library
in discord bot everything must be asynchronous
!pypi aiomysql
this looks promising
use the async library
guys any library that can translate text
Translate language or what
might want to look for some apis (if not all of them are paid anyway)
so no lib for it?

There's aiogoogletrans too
im jw if u can help
so when i made this bot last night just as a small bot for the server i am using for the bot thats being made, How comes whenever i first started last night is fine, as soon as my pc goes off, it stops working and if my pc comes back on and i laucnh to bot again it doenst work, it doesnt respond to any commands or nothing but before that everything is working fine before i went off with 0 error messages this was last night
obviously it wont work when you turn off your pc (if you host if on your local pc)
no like
i came back on and it isnt working after restarting the cmd if ygm
like i turn off my pc, come back on, and then launch the bot and it just comes online and nothing else
no idea what you mean
one was last night, one is now
before i turnt my pc off, it was fine
i come back online today and it isnt working after starting the bot again
do you get any errors in terminal?
no nothing
code?
yeye 2 secs
!paste use this
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
show what prints in the console when you run it
mhm something something weird
the only commands that work are the / commands, anything else doesnt owkr
and i havent tocuehd the code since i went off
switch to @client.listen()
just read the link, you'll get it
line 224
read the docs link i sent
igy
ty it working
why would that stop it working if my bot goes offline?
no it does everytime
mhm probably you updated the code adding that event handler yesterday whitout restarting the bot so you're seeing the consequences only today
ohh okay
am sorta new to the discord side of .py im a .js .lua dev my b ty for the help
and why is because in the background it just catches every message in on_message and if it matches any of your commands and starts with your prefix it calls this command
and by creating on_message event by your own you kinda override it
in short, on_msg gets called first, so you were "eating" your command handlers
that is if you use @client.event coz it overrides the default on_message implementation
👍
so everytime @client.event for on_message it should be @client.listen instead?
@client.listen i belive you can create multiple and they are called one after another
ah okay
yes, or add bot.process_commands(message) at the end
but client.listen is just faster i belive
it depends on your usecase but generally it's better to use .listen
ok thank you
in some cases you may even want to override the base implementation though at that point you'll probably use a subclass of commands.Bot
ImportError: cannot import name 'Intents' from 'discord'
Do you have any files named "discord"?
uhh i am using discord.py
!d discord.Intents
class discord.Intents(value=0, **kwargs)```
Wraps up a Discord gateway intent flag.
Similar to [`Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions "discord.Permissions"), the properties provided are two way. You can set and retrieve individual bits using the properties as if they were regular bools.
To construct an object you can pass keyword arguments denoting the flags to enable or disable.
This is used to disable certain gateway features that are unnecessary to run your bot. To make use of this, it is passed to the `intents` keyword argument of [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client").
New in version 1.5.
actually its working fine in all my other codes
why this particular code got a problem?
for context i just made this code
Can u tell us how are you trying to import it
Either because you have a file named 'discord.py' or because you're using some old discord.py version
from discord import intents
It's Intents
yea its correct case
Then this
i actually copy pasted the code from my other git were its working fine
just not in my vsc
Try using a variable directly
Like intent =discord.Intents
Or just check your dpy version
That might be old
If I am correct intents were introduced in v2.0
yup
okay i deleted the github from python lib
though if they have a file named discord.py in their folder, intents won't help
That's why asking to directly call the intents
Done resolved . maybe some duplicated files
won't help

the file is overwriting the import
is there a way to get user id of person who iis running cmd in my discordbot
alright thanks
!d discord.ext.commands.Context
class discord.ext.commands.Context(*, message, bot, view, args=..., kwargs=..., prefix=None, command=None, invoked_with=None, invoked_parents=..., invoked_subcommand=None, ...)```
Represents the context in which a command is being invoked under.
This class contains a lot of meta data to help you understand more about the invocation context. This class is not created manually and is instead passed around to commands as the first parameter.
This class implements the [`Messageable`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable "discord.abc.Messageable") ABC.
if you need to learn more about ctx
i cant do smthin like this user = ctx.author.id if user = '909646276419809340':
You are trying to restrict a command to someone??
yea i forgot ==
yea i am trying on hwo to restrict cmds if it works i will just code a function for it
U know to restrict it to the owner u could have just used @commands.is_owner()
This would have restricted the command so only u could use it
No need to write an if statement
Then can't you just make a role for the ppl who can use the commands and use the @commands.has_role() decorator??
in that case:
do smthin like this
user_id = ctx.author.id
if user_id == 909646276419809340:
...
in on_presence_update does status count to the profile bio?
is there a reason as to why this isnt working when the bot comes online?
provide code of your command please
okay
@client.event
async def on_connect():
print(f'Connected as {client.user}')
await client.wait_until_ready()
print("Bot is online")
await client.change_presence(status=nextcord.Status.dnd, activity=nextcord.Game(name="placeholder", emoji="💻"))
guild_id = 1119244868326260776
tos = 1119261246177423413
info = 1119250090645790751
help = 1119693456210665573
guild = client.get_guild(guild_id)
tos = guild.get_channel(tos)
info = guild.get_channel(info)
help = guild.get_channel(help)
await tos.send(">tos")
await info.send(">ask")
await help.send(">helpchannel")
```
it seems like you are trying to execute your own command by your bot
is there no way for that to be allowed in py?
or would i need to do that every time the bot restarts
what are you trying to do exactly when the bot restarts
send a message?
so due to the bot restarting the buttons wont work, so im asking the bot once it is connected to client
it will do its own command therefor refreshing the buttons every time it restarts to ensure they are working
also instead of using on_connect and then waiting until bot is ready you can just use on_ready
what buttons wont work
are you trying to make a message with buttons that work always?
not only for the time bot is ran
and when restarted they wont work
there is a thing for that its called persistent view
so on my help embed i have 2 buttons, if i restart my bot those buttons work work
would that be
im not really sure if this is what you want but have a look
https://github.com/Rapptz/discord.py/blob/master/examples/views/persistent.py
(timeout=None) or no
yes but you need to register it as persistent
see example
view=PersistenView
oooo ok ty
yesh
examples/views/persistent.py lines 39 to 45
async def setup_hook(self) -> None:
# Register the persistent view for listening here.
# Note that this does not send the view to any message.
# In order to do this you need to first send a message with the View, which is shown below.
# If you have the message_id you can also pass it as a keyword argument, but for this example
# we don't have one.
self.add_view(PersistentView())```
yeah sumn like this?
class Helping(nextcord.ui.View):
def __init__(self):
super().__init__()
self.value = None
async def interaction_check(self, interaction: nextcord.Interaction) -> bool:
return interaction.user.id == self.ctx.author.id # Only allow the original command invoker to interact with the view
@nextcord.ui.button(label="Community Commands", style=nextcord.ButtonStyle.green, emoji=":bot~1:")
async def confirm(self, button: nextcord.ui.Button, interaction: nextcord.Interaction):
emm = nextcord.Embed(title="Community Commands", description="These are all the commands that anyone in the server may use!")
emm.add_field(name="Ping", value="This will show the bot's current latency in ms form \n Aliases: 'Pong' 'latency' \n Usage: `ping`", inline=False)
await interaction.response.send_message(embed=emm, ephemeral=True)
self.value = True
@nextcord.ui.button(label="Support Team Commands", style=nextcord.ButtonStyle.green, emoji=":moderation:")
async def cancel(self, button: nextcord.ui.Button, interaction: nextcord.Interaction):
embed = nextcord.Embed(title="Support Commands", description="These are commands for our Support/Payment team")
embed.add_field(name="Sale", value="This command is used to DM all members with a role to let them know about an active sale! \n Usage: `sale <@role>`", inline=False)
embed.add_field(name="TOS", value="Post all of the TOS in the used channel \n Usage: `tos`", inline=False)
embed.add_field(name="Reminder", value="Sends a reminder to a mentioned user's DM reminding them about their open ticket! \n Usage: `reminder <@user>`")
await interaction.response.send_message(embed=embed, ephemeral=True)
self.value = False
@client.command()
async def help(ctx):
view = Helping()
em = nextcord.Embed(title="Help Centre", description="Welcome to the help command of our Discord bot! This command is designed to provide you with comprehensive assistance and guidance on how to effectively utilize the features and functionalities of our bot. Whether you're a new user or a seasoned veteran, this command will help you navigate through the vast array of commands and make the most out of your Discord experience.", color=nextcord.Color.green())
message = await ctx.send(embed=em, view=view)
await view.wait()
# Use the value property of the view to determine which button was clicked
if view.value is True:
await message.edit(content="Community Commands selected.")
elif view.value is False:
await message.edit(content="Support Team Commands selected.")
else:
await message.edit(content="No button selected.")```
im guessing
?
All right so, maybe you want to delete that link and reset your bot token first
The point of os.getenv is to have a KEY=value and you use os.getenv("KEY")
It's not to put your bot's token in there
!paste can you use this instead? it has syntax highlighting and is verified website
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
Then I'd be awesome to use a non scammy-looking website for sharing your code indeed
guys does the discord python still work?
because when i try run my code none of the commands work
yes it does
show the code
import discord
from discord.ext import commands
import time
import datetime
from colorama import Fore
import pymongo
intents = discord.Intents.default()
intents.members = True
token = ""
client = commands.Bot(command_prefix=".", intents=intents)
client.remove_command('help')
@client.event
async def on_ready():
global startTime
startTime = time.time()
print('''------''')
print('''Bot Online: ''' + str(datetime.datetime.now()))
print('''Logged in as: ''' + client.user.name)
print('''------''')
@client.command()
async def add_account(ctx, username, password, account_type, balance):
user = username
passy = password
acc_type = account_type
bal = int(balance)
client = pymongo.Mongoclient("")
db = client['Haliflex']
col = db['Accounts']
a = col.find_one({"username":user})
if a:
ctx.send("User already taken")
else:
b = col.insert_one({"Username": user, "password": passy, "account_type":acc_type, "balance":bal})
if b:
ctx.send("User created")
else:
ctx.send("Error somewhere")
you need message_content intent enabled
it is
!d discord.Intents.message_content
Whether message content, attachments, embeds and components will be available in messages which do not meet the following criteria:
• The message was sent by the client
• The message was sent in direct messages
• The message mentions the client
This applies to the following events...
where did you enable it
you need to enable it in code too
thank you
Oke oke
cause im getting so many errors every time somone sends a message
because they havent got a channel id in the db
pls someone quick
error spam
plssss
someone
too many errors
help
What?
so if an error happens in an on_message event
is there an if statement for that?
Just use try except to handle it...
channelv = db[f"vchannelid {str(message.guild.id)}"]
try:
if message.channel.id == channelv:
if message.content:
await message.delete()
except:
pass
the error is still printing
oh wait nvm
nah wait i need help
whats the error
okay guys, i have a question
if i use purge(after=message) will it also erase the message included in after=?
i believe so
test it :)
!d discord.TextChannel.purge
await purge(*, limit=100, check=..., before=None, after=None, around=None, oldest_first=None, bulk=True, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Purges a list of messages that meet the criteria given by the predicate `check`. If a `check` is not provided then all messages are deleted without discrimination.
You must have [`manage_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") to delete messages even if they are your own. Having [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") is also needed to retrieve message history.
Changed in version 2.0: The `reason` keyword-only parameter was added.
Examples
Deleting bot’s messages...
hey! So i run a command for my discord bot, and it runs twice..anyone know why?
Or you have two instances of your bot open and you didn't realize
I once had 2 running and couldn't figure out why tf that happens, turned out while I was migrating from one VPS to another I just stopped the docker container, but it had restart:always policy, so when I rebooted the original VPS it started 💀
we can't even see the full error
and code
you need a tab at line 246
yes
await self.isJoinhub(...)
do you know python's OOP?
self is the class object itself that is being auto-filled by python
idk your code
if you share the affected part maybe i can help you
bot isn't an attribute of View, so you can't use self.bot
you can use interaction.client in the callback, or take the bot instance in the _init_ and set the bot attribute yourself
does anyone know why im getting an AttributeError for a Select object?
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Aa
here's the full error log: https://www.pastebin.com/vEngcj0n
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
show LangSelect class
oh you provided code my bad
the problem is that for the view you create instance of your Select and not actual View
in this line await interaction.response.send_message("Select a language to translate to:", view = LangSelect(), ephemeral = True)
you create LangSelect and not LangSelectView
@pseudo flicker ^
ooooh
ok now the error is now another attributeerror
but its choices
oh its for self.choices[0]
ok mb it should be values
pip install tls-client is not python code
It's a command you are supposed to run in a shell/terminal
is there any examples of a queue system that can be adapted to users instead of music?
What do you mean by that?
what event is called when a user boosts a server? is it on_guild_update?
er idk
i would jus make it easier and do
on_member_update
add role "server booster"
or wtv
hmm
or i could just detect if the default booster role got added
and then do sum
hey how can i make my bot send a message when someone boots the server. what is the event?
i found something
you could check in the on_message event if the messag type is "premium_guild_subscription"
thnks
Oh fu-
Traceback (most recent call last):
File "C:\Users\thill\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ui\view.py", line 427, in _scheduled_task
await item.callback(interaction)
File "c:\Users\thill\Desktop\py\bot.py", line 70, in tos
await interaction.response.send_message(embed=tosembed)
AttributeError: 'Button' object has no attribute 'response'
class Menu(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
self.value=None
@discord.ui.button(label="TOS", style=discord.ButtonStyle.red)
async def tos(self, button: discord.ui.Button, interaction: discord.Interaction):
tosembed = discord.Embed(title="Moon Terms Of Service")
tosembed.add_field(name="The official TOS for all official Moon Discord Servers \n Please follow all of these to avoid recieving punishment", value="** **", inline=False)
tosembed.add_field(name="** **", value="** **", inline=False)
tosembed.add_field(name="**[1] Refunds**", value="All purchases are final, and you **Can not** recieve a refund. The only reason you may recieve a refund is if the issue is caused by us!", inline=False)
tosembed.add_field(name="** **", value="** **", inline=False)
tosembed.add_field(name="**[2] Respect**", value="Treat everyone with respect. Absolutely no harassment, sexism, racism, or hate speech will be tolerated.", inline=False)
tosembed.add_field(name="** **", value="** **", inline=False)
tosembed.add_field(name="**[3] Spam**", value="No spam or self-promotion (server invites, advertisements, etc) without permission from a staff member. This includes DMing fellow members.", inline=False)
tosembed.add_field(name="** **", value="** **", inline=False)
tosembed.add_field(name="**[4] NSFW**", value="No age-restricted or obscene content. This includes name, images, or links featuring nudity, sex, hard violence, or other graphically disturbing content.", inline=False)
tosembed.add_field(name="** **", value="** **", inline=False)
tosembed.add_field(name="**[5] Support**", value="The moderation team includes all @Support members. The Support team holds the final say in all matters involving this server", inline=False)
tosembed.add_field(name="** **", value="** **", inline=False)
tosembed.add_field(name="**[6] Respect**", value="Treat everyone with respect. Absolutely no harassment, sexism, racism, or hate speech will be tolerated.", inline=False)
await interaction.response.send_message(embed=tosembed)
@bot.command()
async def menu(ctx):
view = Menu()
await ctx.reply(view=view)
what is causing this error
It says there in the error
And the interaction parameter should always be in front of the item
So, just move the interaction parameter in front of button
run that in the shell
and better do poetry add [package], unless you want to install the libs every time
Hello i made a bot and the bot is connecting to the channel but after this line the code break.
PS: The bot connect to the channel its just the code that not pass through.
self.voice_client = await ctx.author.voice.channel.connect()
Piece of code:
@commands.command()
async def play(self, ctx, *, query):
if ctx.author.voice is None or ctx.author.voice.channel is None:
await ctx.send("Você precisa estar conectado a um canal de voz.")
return
print(self.voice_client)
if self.voice_client is None or not self.voice_client.is_connected():
print("aqui")
self.voice_client = await ctx.author.voice.channel.connect()
print('passou')
await ctx.send(f"Conectado ao canal de voz: {self.voice_client.channel}")
Thank you!!
!d discord.Member.voice
property voice```
Returns the member’s current voice state.
is there any examples for adding buttons after a button is pressed
so like i press the "click me" button and an embed will appear with buttons attached to that?
just on button click send another message with another message you want if you want buttons attatched to the message attatch another view to it
so like
interaction.response.send_message(embed=embed, view=view) or wtv?
yeah
ohh ok ty
for the class, would i create the class inside the original classes indent or just like a normal class?
Im going to try
no like a normal class
its fine i done it thanks !
I think the problem is that the code is not assuming that the bot is inside the channel
i was just having issues but i forgot parentheses
use discord.Guild.voice_client
instead of making a variable yourself
okay
Hey guys, does youtube-dl
lib, working?
Or maybe u can advise other lib for that, I want to make smth kinda music bot
and how and what do i have to to do with it?
I mean how to use that fix
4. Use English to the best of your ability. Be polite if someone speaks English imperfectly.
!rule 5 *
5. Do not provide or request help on projects that may violate terms of service, or that may be deemed inappropriate, malicious, or illegal.
is that adressed to me?
I see, sorry then, i didnt know
np
hey so can anyone tell me how to make it so if my bot sends a dm to a user it prints out like the userid of the person the bot dmed
await user.send("stuff")
print(user.id)
!ytdl
Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.
For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:
The following restrictions apply to your use of the Service. You are not allowed to:
1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service; (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;
3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTube’s robots.txt file; (b) with YouTube’s prior written permission; or (c) as permitted by applicable law;
9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
TL;DR just dont.
ImportError: cannot import name 'Option' from 'discord' (C:\Users\chain\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord_init_.py)
fix?
what library are you using?
fixed, any fix to that
without any context, I can do nothing
this is equally as useless as me sending
I need help
My discord bot is currently running and online, but when I try to use a command that I coded like !help it doesn't work
D:
@nova summits
either you don't have message_content intents enabled
or you have an on_message event that's not coded correctly:
https://discordpy.readthedocs.io/en/stable/faq.html#why-does-on-message-make-my-commands-stop-working
so i have
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.invites = True
intents.message_content = True
bot = commands.Bot(command_prefix='!', intents=intents)
client = discord.Client(intents=intents)
@client.event
async def on_ready():
does domething
@bot.event
async def on_ready():
print bot is ready
@bot.command()
async def return_input(ctx, *, message):
await ctx.send(message, allowed_mentions=discord.AllowedMentions.none())
print("Command ran.")
so i cant do
bot.run(token)
clinet.run(token)
and basically upon running the bot i want the client event to continously happen but only the command when called upon
anyone know how to go about doing this?
Why do you have both client and bot
that's your first issue
remove the client
the bot is basically a client on steroids
=> it has all client functionality + the commands on top
oh right so i can just put whatever i had under client event inisde bot event?
just remove everything client related and only use your bot variable...
know that your client was never running in the first place... because that bot.run() line is blocking...
yeah i had client originally and looked at some tutorials and thought i spefically needed another "bot.event" on top of my client to do commands
Tutorials, huh
no, in most "tutorials" they use commands.Bot, because they also want commands...
ok thanks for the help
22222222222222222222222222222222222222222222222222222222
My keyboad is being a bitch
the 2 key keeps triggering itself
and wont die
I need help
please post your question along with relevant code/error
Okay, tysm
I have a problem with my Discord.py bot code. I'm trying to get the bot to play music, but I haven't been able to.
Are you getting an error?
no
Did you install discord.py with voice support?
Voice support? what is it?
Then it's probably an issue with your code
!paste
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
If you can send it here we can take a look
My idea was to make the bot able to play music based on Youtube results.
I have my code in Replit. Can I pass it on?
I see, we might not be able to help with that here because it may violate youtube tos
!ytdl
Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.
For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:
The following restrictions apply to your use of the Service. You are not allowed to:
1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service; (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;
3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTube’s robots.txt file; (b) with YouTube’s prior written permission; or (c) as permitted by applicable law;
9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
Oh, what can I use to do it, then?
Don't think there is a legal way of doing it besides buying the copyrights to the music you want to play
So why does Youtube provide API for that?
youtube doesn't provide an API for obtaining audio/video from it
it has an API for searching for videos
but it doesn't give the video's content
So isn't there a legal way with any program to do that?
right
some popular bots like groovy and rythm were taken down by youtube because of this, btw ^
Oh, it´s okay. Tysm
how would i make a check so only a certain role can use a command?
!d discord.ext.commands.has_role
@discord.ext.commands.has_role(item)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member invoking the command has the role specified via the name or ID specified.
If a string is specified, you must give the exact name of the role, including caps and spelling.
If an integer is specified, you must give the exact snowflake ID of the role.
If the message is invoked in a private message context then the check will return `False`.
This check raises one of two special exceptions, [`MissingRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") if the user is missing a role, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
Changed in version 1.1: Raise [`MissingRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") instead of generic [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")...
yall know any free programs to host a python discord bot?
Like
free not cheap... free
None
Using free hosting options like repl.it or Heroku for continuous 24/7 bot hosting is strongly discouraged.
Instead, opt for a virtual private server (VPS) or use your own spare hardware if you'd rather not pay for hosting.
See our Discord Bot Hosting Guide on our website that compares many hosting providers, both free and paid.
You may also use #965291480992321536 to discuss different discord bot hosting options.
Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.
Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.
Example
def foo():
bar = 'baz' # indented one level
if bar == 'baz':
print('ham') # indented two levels
return bar # indented one level
The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.
Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines
More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation
and uh, how can i get my bot to edit its message
@snow coral what u mean?
like if my bot says "hi" if i react with something it could change to "hello" or something
bro i keep getting some goofy error when i use the page buttons:
@tree.command(name='help', description='Show available commands and their descriptions')
async def help_command(interaction: discord.Interaction, page: int = 1):
commands_per_page = 5
all_commands = list(tree.walk_commands())
total_pages = (len(all_commands) - 1) // commands_per_page + 1
if page <= 0 or page > total_pages:
await interaction.response.send_message("Invalid page number.")
return
start_index = (page - 1) * commands_per_page
end_index = start_index + commands_per_page
commands = all_commands[start_index:end_index]
embed = discord.Embed(title='Bot Commands', color=0x141414)
for command in commands:
command_name = f"`{command.name}`"
command_description = command.description
embed.add_field(name=command_name, value=command_description, inline=False)
embed.set_footer(text=f"Page {page}/{total_pages}")
class HelpView(discord.ui.View):
def __init__(self, page):
super().__init__()
self.page = page
async def update_page(self, interaction2: discord.Interaction, new_page: int):
await interaction.edit_original_message(embed=embed)
self.page = new_page
@discord.ui.button(label="Last Page", style=discord.ButtonStyle.gray)
async def go_previous(self, button: discord.ui.Button, interaction2: discord.Interaction):
new_page = self.page - 1
await self.update_page(interaction, new_page)
@discord.ui.button(label="Next Page", style=discord.ButtonStyle.gray)
async def go_next(self, button: discord.ui.Button, interaction2: discord.Interaction):
new_page = self.page + 1
await self.update_page(interaction, new_page)
view = HelpView(page)
message = await interaction.response.send_message(embed=embed, view=view)
view.message = message```
AttributeError: 'Interaction' object has no attribute 'edit_original_message'
They changed it to edit_original_response
What?
my bot is not mentioning users... though the ode states
message = f"**Hey** {ctx.author.mention}**,** **here's the final result!**"
if prompt_enhancement is not None and prompt_enhancement.value == 'True':
embed_info.add_field(name="Orignial prompt: ", value=f"> {original_prompt}", inline=False)
embed_info.add_field(name="Prompt used for Image Generation: ", value=f"> {prompt}", inline=False)
embed_info.add_field(name="Visual Setting: ", value=f"> {style.name}", inline=True)
embed_info.add_field(name="Proportion: ", value=f"> {ratio.name}", inline=True)```
the bot should be mentioning the user but its not
You used the slash command, why would you need a mention to notice that you used it
cause its image generation... it takes time and the server owne wants it so yeah
Can you show the code where you send the response
1 sec plz
Idk at this point, maybe you can't mention on a response to an interaction?
Try mentioning someone in other ways
we can
out of ideas and methods ;-;
I meant mention with a ping
Are you deferring the response
yeah we can... it used to work with djs
🤷
ie am not
Then why wouldn't it work
Add the allowed_mentions kwarg
thats what confusing me
the what now?
!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...
When using .send()
i see... alright i can try that
Controls the users being mentioned. If True (the default) then users are mentioned based on the message content. If False then users are not mentioned at all. If a list of abc.Snowflake is given then only the users provided will be mentioned, provided those users are in the message content.
whats kwarg though?
keyword argument
ohhhh
allowed_mentions=...
so i do allowed_mentions=True?
^
ohohoh okokokokok
allowed_mentions=discord.AllowedMentions(users=True)
ahh.... makes sense
nope... stil not mentioning
Then dunno, you're most likely doing something that shouldn't be done
:/
pip install disnake ?
in the command line
This is app python

i always program on a laptop or pc so dont have issues like that
i told you already its command to run in command line
not in python script
you scribbled out your token, yet the comment on the top is a token
i have no idea what that is i told you i dont code on a phone
why would you code on a phone
Because I don't have a pc
I have only mobile
You can send me name wibsite
Use python?
?
Send me a website using the python language
i dont know any website that lets you run python scripts using 3rd party libraries
who can code a button for me pls
from discord.ext import commands
bot = commands.Bot(command_prefix="!", intents=discord.Intents.all())
@bot.event
async def on_ready():
print("Bot is online")
@bot.command()
async def ping(ctx):
await ctx.send("pong")
@bot.command()
async def info(ctx, member:discord.Member = None):
if member == None:
member = ctx.author
embed = discord.Embed(title="!info - Help Command", description="This is for people who have trouble remembering commands.")
embed.add_field(name="!ping", value="Simple command, You play the !ping command, the bot responds with pong.")
embed.add_field(name="!info", value="Help command.", inline=False)
embed.set_footer(text="Visit for updates.")
await ctx.send(embed=embed)```
Just look at the examples and do it yourself https://github.com/Rapptz/discord.py/blob/master/examples/views/confirm.py
how does one get a button to open a modal/
Combine that with the example above with buttons and magic happens
Well we do not write code for you but we can certainly help
who can help me to use Cogs?
I tried to read the related documents and follow, but no success
You get any errors?
Others than command not found?
The bot.py Has to be outside cogs folder
ok let me try again
Show other error then
nothing then, just there's that error
What error
Ignoring exception in command None
discord.ext.commands.errors.CommandNotFound: Command "ping" is not found
discord, os, sys, asyncio
Yes i can see but i'm asking for library for discord you are using
discord.py, nextcord, disnake, pycord
?
ver: 2.4.0a4858+gdc4ed438
Full output
Version: 2.4.0a4858+gdc4ed438
Summary: A Python wrapper for the Discord API
Home-page: https://github.com/Rapptz/discord.py
Author: Rapptz
Author-email:
License: MIT
Location: D:\Dev\discord_bot\venv\Lib\site-packages
Requires: aiohttp
Required-by:
okay theb
I belive you need to await that load extension and add cog calls
!d discord.ext.commands.Bot.load_extension
await load_extension(name, *, package=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Loads an extension.
An extension is a python module that contains commands, cogs, or listeners.
An extension must have a global function, `setup` defined as the entry point on what to do when the extension is loaded. This entry point must have a single argument, the `bot`.
Changed in version 2.0: This method is now a [coroutine](https://docs.python.org/3/glossary.html#term-coroutine "(in Python v3.11)").
await add_cog(cog, /, *, override=False, guild=..., guilds=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Adds a “cog” to the bot.
A cog is a class that has its own event listeners and commands.
If the cog is a [`app_commands.Group`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Group "discord.app_commands.Group") then it is added to the bot’s [`CommandTree`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree "discord.app_commands.CommandTree") as well.
Note
Exceptions raised inside a [`Cog`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Cog "discord.ext.commands.Cog")’s [`cog_load()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Cog.cog_load "discord.ext.commands.Cog.cog_load") method will be propagated to the caller...
Its awaitable as well
explanation and code example of that:
https://discordpy.readthedocs.io/en/stable/migrating.html#extension-and-cog-loading-unloading-is-now-asynchronous
Who can create the prefix command in python?
I can't find it on google and youtube
@slate swan
You want to create a custom prefix for each guild?
Yes
Well this is doable but i cant help you rn im not at home
Alright accepted add me?
They way you do it is that you store those prefixes in database and then for the command_prefix you specify function that will fetch database and return desired prefix to use
You can for sure find it on the YouTube
Look
Look up custom prefix discord py
This part should be similar to disnake if not the same
!d disnake.ext.commands.Context
class disnake.ext.commands.Context(*, message, bot, view, args=..., kwargs=..., prefix=None, command=None, invoked_with=None, invoked_parents=..., invoked_subcommand=None, ...)```
Represents the context in which a command is being invoked under.
This class contains a lot of meta data to help you understand more about the invocation context. This class is not created manually and is instead passed around to commands as the first parameter.
This class implements the [`abc.Messageable`](https://docs.disnake.dev/en/latest/api/abc.html#disnake.abc.Messageable "disnake.abc.Messageable") ABC.
there's a small difference between disnake.Context and disnake.ext.commands.Context
Dude can you read?
Literally this
You mean import?
Let me rephrase.
You have disnake.Context
You must have disnake.ext.commands.Context
Ty man fixed
Insane the magic that happens when we read
Hey how could I fix this issue?
Exception has occurred: ImportError
cannot import name 'AppCommandOptionType' from 'discord.enums' (C:\Users\berka\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\enums.py)
File "C:\Users\berka\Desktop\Ticket bot\main.py", line 3, in <module>
from discord import app_commands
ImportError: cannot import name 'AppCommandOptionType' from 'discord.enums' (C:\Users\berka\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\enums.py)```
import discord, os
from datetime import datetime
from discord import app_commands
from discord import utils
from discord.ext import commands
from config import token
from discord import ui
from discord.ext import tasks
import random
Indeed
Update discord to latest
Alright
Is there a way to set a time limit for tasks in a discord bot? Every 15min I call another script (server request) via async and at some times, it just won't respond. Therefore I cannot really change the called script and kinda have to rely on the discord bot, to just cancel the task after 30s.
cancel()```
Cancels the internal task, if it is running.
if i follow the tutorial of freecodingcamp org for discord bot the only diff being that i do it on vs code instead of replit the bot should still be able to run 24/7 right since the uptime robot pings it on the web page rather than pinging the code itself
that doesn't work like that
VS Code is a development environment, not a hosting provider
for the bot to be up your pc needs to be on 24/7
Replit is a website development environment and pseudo-hosting. Neither are made for hosting a bot
Get a cheap VPS to run your bot 24/7 as it should be done and use VS Code to code the bot and test it
wont using replit do the same thing?
alr thanks
hey guys, so discord changed the way usernames work and now some commands I wrote for a private server bot dont work
anyone else facing this issue?
That's what happens when you rely on usernames and not user IDs
so for you it would be like $command krypton.ninja testCommand
Sooo?
So?
using userID
You should be relying on the user ID and type hint the command argument as a user
That way you can do
$command 562359123086409729 blah
$command @slate swan blah
or whatever and you will have access to a user object in your command
hmm alright Ill give it a shot using that method.
Hybrid command?
So you don't do @bot.hybrid_command()
@bot.tree.command()
class discord.Interaction```
Represents a Discord interaction.
An interaction happens when a user does an action that needs to be notified. Current examples are slash commands and components.
New in version 2.0.
Ah okay! Thx!
How can I get member's avartar url?
!d discord.Member.avatar
property avatar```
Equivalent to [`User.avatar`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.avatar "discord.User.avatar")
!d discord.Member.guild_avatar
property guild_avatar```
Returns an [`Asset`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Asset "discord.Asset") for the guild avatar the member has. If unavailable, `None` is returned.
New in version 2.0.
Thank you soo much
I need help with a command
When im using json.dump its returning a long error with the key words being “Extra data line 2 column 1”
how to get server icon url? i tried ctx.guild.icon_url but it isnt working
!d discord.Guild.icon
property icon```
Returns the guild’s icon asset, if available.
thx
show the actual error
yea anyone here good with discord bot? i am trying to add an ticket command but i got some errors idk how to solve them
You should post your code and errors
my whole code?
the code you need help with
Traceback (most recent call last):
File "C:\Users\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 229, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\OneDrive\Dokument\Discord Bots\import discord.py", line 144, in ticket
Button = Button(label="📥 Create Ticket", style=discord.ButtonStyle.green)
UnboundLocalError: local variable 'Button' referenced before assignment
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 1350, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 1023, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "C:\Users\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 238, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: UnboundLocalError: local variable 'Button' referenced before assignment
show code
how do i send it if its too long
!paste
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
you are overriding Button class since you named the varriable the same
replace it with button or other cool name
whhich line
the line where you create a button
right there right?
yes
i think that it wont work
