#discord-bots
1 messages · Page 115 of 1
Do you have intents enabled? (Specifically message intents or all)
should work
no
yes all
Your going to have to loop through or select them manually your list etc keywords[0] or keywords[1].
if (keywords[0] in message.content) or (keywords[1] in message.content). Iterating for keyword in keywords: if keyword in message.content:
i am on mobile i can’t really explain it much better
Why would you do that?
if any(word in message.content for word in keywords)
or that
Might have to make it a list not sure if any works on generators 🤔
word isn't a word though
his list
It's a character
oh bruh im stupid af
!e ```py
for word in "Hello World!": print(word)
@wary crystal :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | H
002 | e
003 | l
004 | l
005 | o
006 |
007 | W
008 | o
009 | r
010 | l
011 | d
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/ticabedine.txt?noredirect
It should be split first
Oh I looked at your comp wrong
it answers to the message but not to the right keywords
indent probably
But it would also make sense imo to split message.content as well
@slate swan Do you want the message to be one of the keywords or do you want it to contain one of the keywords?
that they contain a keyword
So my comp should work fine
if any(word in message.content for word in keywords) ?
Yeah although you might have to cast the generator as a list
Don't think so though
Lemme see
You don't
it doesn't work
How so
anyone here knows javascript too?
Is there any packages I can use to help me moderate nicknames on Discord & change things such as h€rr0 to "herro"? Like take away the special characters and replace them for 'normal' ones?
hey i want to get the user who added the bot to the server to send him a greeting message... I can always do that for the owner but it's not always the owner who invites the bot
^ didnt think of that, although its not always feasible as per the answer stating it requires mange guild perms
Not really since that would be a pain to make.
Zalgo brr
For those who don't know what zalgo is -> e̸̽́x̶͌̕ȁ̸̑m̴͋̇p̷̐̎l̸̽̓e̷̓͗
well if its just diacritics you can remove those, but for other characters i remember seeing a library with handcrafted mappings to ascii, but i forgot its name
!charinfo e̸̽́
\u0065 : LATIN SMALL LETTER E - e
\u0338 : COMBINING LONG SOLIDUS OVERLAY - ̸
\u033d : COMBINING X ABOVE - ̽
\u0301 : COMBINING ACUTE ACCENT - ́
\u0065\u0338\u033d\u0301
Thеsе аге гцssiаи lеttегs
Combining so could be filtered.
!charinfo и
\u0438 : CYRILLIC SMALL LETTER I - и
!pip unidecode i think was what i remembered, although its not necessarily meant to convert unicode to their closest latin character, e.g. € becomes EUR
can someone tell me how i can send the result into the same channel as the command was used in?
!d nextcord.Interaction.channel
The channel the interaction was sent from.
Note that due to a Discord limitation, DM channels are not resolved since there is no data to complete them. These are PartialMessageable instead.
!d nextcord.Status.idle
The member is idle.
Tried to add an option to make a title but this came?
Error is at 22
And 13
and whats wrong there?
Found it out
but the only error was that i wrote "title" instead of "name" on line 13
Wait u did wrote title xd
You're looking for: https://discordpy.readthedocs.io/en/stable/ext/commands/extensions.html
Thanks I'll check it out
U can’t name it self.title
if message.content.lower() == 'hello':
#helloflag = True
message = await message.channel.send('Hello. How are you feeling today? ')
if message.content.lower() in ['good', 'fine', 'great', 'happy']:
await message.channel.send("That's good")
How do I make it so that when the user responds to “Hello, how are you feeling today?”, if the user says “good”, the bot says “that’s good”
!d discord.Client.wait_for
wait_for(event, /, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.10)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.10)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.10)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/latest/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
@sick birch hey where do you see future of text based commands, will discord totally remove it?
I don't think so but they're making it unfeasible for larger verified bots
I would suggest building your bot from the ground up with slash commands in mind to account for scalability
even if you don't like it (i know many don't)
why is it that in this code, my bot is still responding to its own message
async def on_message(self, message):
if message.author == self.user:
return
if message.content == 'ping':
await message.channel.send('pong')
if not self.helloflag and message.content.lower() != "hello":
await message.channel.send('Say hello to start')
if message.content.lower() == 'hello':
self.helloflag = True
message = await message.channel.send('Hello. How are you doing today?')
if self.helloflag:
if message.content.lower() in ['good', 'fine', 'great', 'happy']:
await message.channel.send("That's good")
self.helloflag = False
elif message.author != self.user:
print(message.content.lower())
await message.channel.send("Oh ok")
self.helloflag = False
self.client.user
or self.bot.user
whichever ur using
alright thanks
How do I make my bot send a embed after a certain amount of messages are sent
Ik how to make a embed
every message, add 1 to the message variable and if message variable is bigger than number, send embed and set message variable to 0
Hey, simple issue here that my tired brain can't fix
@bot.command()
@commands.cooldown(1, 86400, type = discord.ext.commands.BucketType.user)
async def daily(ctx):
try:
query = { "user_id": ctx.author.id }
existing_user = money_other.find(query)
for result in existing_user:
current_points = result["points"]
actual_money = result["money"]
moneyamount_two = actual_money + (random.randint(350, 420))
addpoints = current_points + 1
original_query = { "user_id": ctx.author.id }
updated_money_values = { "$set": { "money": moneyamount_two } }
updated_points = { "$set": { "points": addpoints}}
money_other.update_one(original_query, updated_points)
money_other.update_one(original_query, updated_money_values)
embed_title = f"Daily collected, f{ctx.author.name}!"
embed = discord.Embed(title=embed_title, description="", color=1000000)
await ctx.send(embed=embed)
except CommandOnCooldown:
embed = discord.Embed(title=f'{ctx.author.name}, You need to wait {retry_after} seconds until you can claim your daily again!', description="", colour=1000000)
await ctx.send(embed=embed)
Why doesn't the except part execute?
Just ignores it and gives me the error code in the terminal
cuz the CommandOnCooldown isnt being raised inside of the command
its command.error
look it up in the docs
Aight
lets see if I can find something
What would the solution be though? Or could you link the exact place?
There's like, 30 different instances of it being mentioned in the docs...
Just saying it isn't a good idea to do such cooldown with decorator
Cause if you shutdown the bot it will reset
I was told it was the best idea 
Better to use a db
That's the easiest way to implement, yet if you restart the bot cooldowns will reset
not for a daily cooldown
yea that might be a problem on small-scale bots
Got that, doesn't affect what I'm doing too much as the cooldowns will be short and I don't update the bot much
Is for a small server. Daily command is just to see if I can get it working
all I need to know is
if there is a solution to my error
where to find it
If there isn't a solution
Then I'll go back and experiment
as said command.error
Could you point me to where in the docs is it explained?
As I said, there were quite a few places it was mentioned.
!d discord.ext.commands.Command.error
@error```
A decorator that registers a coroutine as a local error handler.
A local error handler is an [`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") event limited to a single command. However, the [`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") is still invoked afterwards as the catch-all.
Changed in version 2.0: `coro` parameter is now positional-only.
Epic, thanks a ton
How do i make a simple music bot iwth auto song search
have you ever heard of youtube?
there are millions of tutorials
Guys, is there an issue with discord.py imports not working in python 3.11?
My imports arent working so i am unsure
on 3.10 it works, not on 3.11
Several interpreters issue most likely
Do you think that will be fixed soon?
That issue happens because of bad interpreters management, you caused it and can fix by yourself, it's not a code problem
I had python 3.10.5 which worked, when i switch to 3.11.0 nothing, like i deleted 3.10.5 to be sure, but it still doesn't work, i even tried uninstalling and reinstalling the package, any idea what I should do?
Uninstall all python versions and install 3.11 with "Add Python to PATH" checkmark. Also use venvs for packages management
I never used venvs Lol
You should
How come
!venv
Virtual Environments
Virtual environments are isolated Python environments, which make it easier to keep your system clean and manage dependencies. By default, when activated, only libraries and scripts installed in the virtual environment are accessible, preventing cross-project dependency conflicts, and allowing easy isolation of requirements.
To create a new virtual environment, you can use the standard library venv module: python3 -m venv .venv (replace python3 with python or py on Windows)
Then, to activate the new virtual environment:
Windows (PowerShell): .venv\Scripts\Activate.ps1
or (Command Prompt): .venv\Scripts\activate.bat
MacOS / Linux (Bash): source .venv/bin/activate
Packages can then be installed to the virtual environment using pip, as normal.
For more information, take a read of the documentation. If you run code through your editor, check its documentation on how to make it use your virtual environment. For example, see the VSCode or PyCharm docs.
Tools such as poetry and pipenv can manage the creation of virtual environments as well as project dependencies, making packaging and installing your project easier.
Note: When using Windows PowerShell, you may need to change the execution policy first. This is only required once:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
Not to have this problem in the future
I just added to path, still doesn't work lol
Then use venv
maybe discord package is in wrong file
Lmfao on 3.10.5 it works again
Something wrong with 3.11 then
Hey @light violet!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
!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)
@vocal snow dont help me with ytdl btw if u see in play cmd it plays a file from storage i want help regarding that
ok what's your code
W8
@commands.command()
async def play(self, ctx, *, query):
"""Plays a file from the local filesystem"""
source = discord.PCMVolumeTransformer(discord.FFmpegPCMAudio("./Mood.mp3"))
ctx.voice_client.play(source, after=lambda e: print(f'Player error: {e}') if e else None)
await ctx.send(f'Now playing: {query}')
@vocal snow
how would I go about making an economy command for my bot in a separate subfolder and linking it to the main.py with a cog?
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'NoneType' object has no attribute 'purge'
User.dm_channel is returning None, the bot doesn't have a private channel with the specified user
yeah it has a dm with me
unrelated but that's not how you put docstrings
lol i use them as comments
Then probably it can't be found in the bot cache, anyway just use the create_dm coroutine
PEP8 triggered
put it at the beginning of the function body
like
def x():
"""Does x blah blah blah"""
pass
hmm i was wondering if this can be somehow used by the bot
Yes
how
I think docstrings are automatically set to the help property of that command
Only works if you properly place the docstring
hmm but im not using text commands how does that help
maybe if you ever decide to write a front-end for that bot, iterate through the bot's commands
ty
Python 3.11 still ain’t working for me like I can’t do discord imports, someone help
are you in a venv
No
what IDE are you using?
Like python versions
no, at the beginning of the function body
how
no like vscode, pycharm, or?
Vscode
@commands.slash_command(...)
async def cleardm(...):
"""slash command blah blah"""
got it
at the bottom right it will show which interpreter VSCode is using
maybe it's using the old one
Ye I changed to 3.11,
Then the imports for discord don’t work
If I switch back to 3.10.5
what do you mean by "don't work"
It says that missingImport. Like it’s an error
did you install the discord.py library for 3.11?
Wdym?
different python version will have different packages
try py -3.11 -m pip install discord.py
I use discord.py2.0 the one from github that was download
Real ubuntu 22.10
Hello! I want to add an option to add custom colors to the embed and if no hex was given it will use a random color but it still uses random colors even when a hex was given
or is there no such thing called number in modals? If so what should it be?
Because you're telling it to choose a random colour if the self.number is not None, because you set its value in the __init__, it will always exist and never be None. I assume that you want to check if the colour was provided or not. You should check its value if it's None instand
Ah so it’s finally out and 2.0 can be downloaded like on vs code normally?
i think so
Ok
how can i run a discord bot in a thread with threading.Thread ?
when i made it to if self.number.value == None: this came in the console (also changed self.number.. to name2 because i thought that might cause the issue before)

That's because nextcord expected the embed's colour to be an instance of Colour or int, and since the modal input's value will always return as a str, you have to convert it to RGB and use nextcord.Colour.from_rgb to turn it into an instance of the Colour
not tryna be rude or anything but do you just use peoples code or something? you error is just a basic python error and you stored it a specific way so you should know the issue
what I was thinking
at this point u are just playing lego with python
tf
job_name = jobs(int[job][“name“]) 
syntax has left the chat
andy are u good at logical problems? i need answer for a question
if i put it in help channel i am prolly gonna get ignored
What
yo
what is payload in discord.py ?
async def on_raw_reaction_add(self, payload):
"""
Give a role based on a reaction emoji.
"""
if payload.message_id != self.target_message_id:
return
(like this )
!d discord.RawReactionActionEvent
class discord.RawReactionActionEvent```
Represents the payload for a [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add") or [`on_raw_reaction_remove()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_raw_reaction_remove "discord.on_raw_reaction_remove") event.
@bot.event
async def on_message(msg):
channel = bot.get_channel(996119147337494538)
embed = discord.Embed(title=f"New feedback!", description=f"User: {msg.author.mention} \n \n Feedback: {msg}", timestamp=datetime.now() , color=0x4e80cf)
embed.set_thumbnail(url=msg.author.display_avatar.url)
embed.set_footer(text=f"Requested by {msg.author} | {msg.author.guild.name}")
moji=await channel.send(embed=embed)
await moji.add_reaction('') ```
and it wont stop spamming that
i am trying to do that if they send a message in a sepcific channel
also how do i do that if the message is from a bot it wont send
you need an if statement to do both of those
if msg.author.bot:
return?
looks like a message object repr to me
you're passing in the message object instead of just the content (msg.content)
you're still passing an object directly
@bot.event
async def on_message(msg):
Channel = bot.get_channel(996119147337494538)
if msg.channel is not Channel:
return
embed = discord.Embed(title=f"New feedback!", description=f"User: {msg.author.mention} \n \n Feedback: {msg.content}", timestamp=datetime.now() , color=0x4e80cf)
embed.set_thumbnail(url=msg.author.display_avatar.url)
embed.set_footer(text=f"Requested by {msg.author} | {msg.author.guild.name}")
if msg.author.bot:
return
moji=await Channel.send(embed=embed)
await moji.add_reaction('')```
are you sure you saved your code
👍
you need to process the commands
await bot.process_commands(msg)
yes
code please
@bot.event
async def on_message(msg):
Channel = bot.get_channel(996119147337494538)
if msg.channel is not Channel:
return
embed = discord.Embed(title=f"New feedback!", description=f"User: {msg.author.mention} \n \n Feedback: {msg.content}", timestamp=datetime.now() , color=0x4e80cf)
embed.set_thumbnail(url=msg.author.display_avatar.url)
embed.set_footer(text=f"Requested by {msg.author} | {msg.author.guild.name}")
if msg.author.bot:
return
moji=await Channel.send(embed=embed)
await moji.add_reaction('')
await bot.process_commands(msg)```
so you only want commands to work in that channel?
nono
ok, so think about how the function is going to work
umm
think about it
there's no compulsion that you have to process commands at the end of the event
so at the start?
you just need to restructure the logic
you can do it at the start, but then it'll process commands sent by bots as well
oh
so you'll need to move those if statements around a bit
i cant do it that way right
think of the flow
- you check if the msg author is a bot
- if it is, return
- process commands
oh
@bot.event
async def on_message(msg):
Channel = bot.get_channel(996119147337494538)
if msg.author.bot:
return
embed = discord.Embed(title=f"New feedback!", description=f"User: {msg.author.mention} \n \n Feedback: {msg.content}", timestamp=datetime.now() , color=0x4e80cf)
embed.set_thumbnail(url=msg.author.display_avatar.url)
embed.set_footer(text=f"Requested by {msg.author} | {msg.author.guild.name}")
await bot.process_commands(msg)
if msg.channel is not Channel:
return
moji=await Channel.send(embed=embed)
await moji.add_reaction('')```
will it be like that
that would work
i will try
but there's no reason to create the embed if you're not going to send it anyways
so you can move that part after the 2nd if statement too
works
oh
also
can u help me w that-
how do i do that it will purge the author message
will await msg.channel.purge(limit=1)
would do it?
just use msg.delete
()
there is no limit since the api call is to delete that specific message
ohh okay thanks
I want that bot will dm me when someone send help message``` elif message.content.startswith("help"):
send me message
any help?
is that the whole code?
here's the code ```
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
@client.event
async def on_message(message):
if message.author == client.user:
return
elif message.content.startswith("help"):
send me message
also it's printing none``` user = client.get_user(1035557353845706762) print(user)
@slate swan 🤔
!d discord.Client.get_user - it'll return None if it can't find the user with the given ID
get_user(id, /)```
Returns a user with the given ID.
Changed in version 2.0: `id` parameter is now positional-only.
Also you have to wait until the bot have fully started before using that
but why is it showing none?
as i have given my own id
still it's showing None
🤔
]
Because the method is a cache lookup, over a method like discord.Client.fetch_user which makes a request
what to do?
make a check, that checks if discord.Client.get_user was successful or not
ok then?
e.g
user = clientvar.get_user(id) or await clientver.fetch_user(id)
ok
Not working```
user = client.get_user(788606884285251644) or await client.fetch_user(788606884285251644)
print(user)
here's the error<coroutine object Client.fetch_user at 0x0000017C90F333C0> F:\pyenv\lib\site-packages\discord\client.py:409: RuntimeWarning: coroutine 'Client.fetch_user' was never awaited await coro(*args, **kwargs) RuntimeWarning: Enable tracemalloc to get the object allocation traceback
not working
show your code
No
elif message.content.startswith("help"):
user = client.get_user(788606884285251644) or await client.fetch_user(788606884285251644)
print(user)
await message.channel.send("ok")
Did you saved your code, if you did, did you used the fetch_user method with send and only had 1 await?
i saved my code but not used fetch_user
what i did is shown to you
Well, can you show your current code?
and can you show the whole traceback?
!traceback
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.
ok
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.
please delete it
The actual whole thing!
!trace elif message.content.startswith("help"):
user = client.get_user(788606884285251644) or await client.fetch_user(788606884285251644)
print(user)
await message.channel.send("ok") ```
elif message.content.startswith("help"):
user = client.get_user(788606884285251644) or await client.fetch_user(788606884285251644)
print(user)
await message.channel.send("ok")
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 this correct ?
can someone help me w making the buttons always work? everytime i run the bot twice the buttons are not working same w select menus, how do i make it work everytime?
!d discord.Client.add_view
add_view(view, *, message_id=None)```
Registers a [`View`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View "discord.ui.View") for persistent listening.
This method should be used for when a view is comprised of components that last longer than the lifecycle of the program.
New in version 2.0.
any help?
🤔
i love border how did u do it?
Hello, I don't know about bulk message deletion, I read the document but I don't understand, can anyone help?
Lol sharex
I use that but where is the settings for it
Ohh
Search in youtube i dont rlly know how to explain
It would be nice if you could give a usage example.
yo anyone wanna make an discord bot?
I think you want .purge() if no limit is provided it would only delete the last 100 messages
🤣 i suck at it
currentyl trying rn. I was successful a couple years back and now i cant do shit
https://discordpy.readthedocs.io/en/stable/api.html?highlight=purge#discord.TextChannel.purge Docs, if you want an example
lol
what kind of bot
Does it function the same as this?
idk what do you think
i don't think 🧠❌
hmmm
This is an event, which gets called on an bulk delete. So no it is not the same.
idak
Thanks.
alr wanna do a bot or nah?
like an msg bot
it says like Hello good morning and send embed texts and stuff
I could, doing one for a school project anyway
oh school
so we doing vscode or replit
yeh that stuffs easy
btw i am not good at making an bot
I use pycharm 💀
lol
huh whats that
another IDE
lol
ok
alr dm me
oh yeah
ill send link
File "C:\Users\lende\Desktop\Desktop\Sesh-Bot-main_-_Saldo_1\aa\main.py", line 2, in <module>
import discordModules.auth as auth
File "C:\Users\lende\Desktop\Desktop\Sesh-Bot-main_-_Saldo_1\aa\discordModules\auth.py", line 4, in <module>
import clientCommands
File "C:\Users\lende\Desktop\Desktop\Sesh-Bot-main_-_Saldo_1\aa\clientCommands.py", line 4, in <module>
import commands.events.on_message
File "C:\Users\lende\Desktop\Desktop\Sesh-Bot-main_-_Saldo_1\aa\commands\events\on_message.py", line 5, in <module>
from discordHelpers.createQuestions import *
File "C:\Users\lende\Desktop\Desktop\Sesh-Bot-main_-_Saldo_1\aa\discordHelpers\createQuestions.py", line 8, in <module>
from discord_components import Button, component, ButtonStyle
ModuleNotFoundError: No module named 'discord_components'``` help me please
the library has been discontinued and you dont have it installed
you can help me? please
you'll have to use discord.py's Views to make buttons and stuff instead of this library
!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.
i put those in as follows and it says it doesnt cant import intents from discord
Way to complicated for me.. is there a way that i can make it go blue if the user writes "blue" as a color?
Hey there, im struggling to print the value from payout
Whenever i run i get None
Please let me know what im doing wrong
is there a way to run the bot async with another task that uses the terminal?
Guys, how do I add a space after the title in an embed for my description
I was told to make classmethods if I wanna call an async fuction inside __init__ but how do I await ? is it like await Class.Method()?
Rather than doing that, just define self.something: something = None and add the value to it in some function like setup_hook
you cant call an async function inside an init
a possible way would be using asyncio.create_task()
def __init__(self,author) -> None:
super().__init__()
self.value = None
self.author = author
self.damage,self.player,self.mob = Mobs(author).MobEncounter()```
```class Mobs():
def __init__(self, id):
self.id = id
async def MobEncounter(self):
async with aiosqlite.connect('db.db') as con:
cur = await con.execute("SELECT Constitution,Max_Constitution,Dexterity,Intelligence,mana,Strength,floor,class,level FROM Character WHERE user_id = ?", (self.id,))
player = cur.fetchone()
if player[7] == "Adventurer":
damage = (10 * ((player[2] * 1)+(player[3] * 0.25)+(player[4] * 0.1)+(player[5] * 1.5)))
elif player[7] == "Magician":
damage = (10 * ((player[2] * 0.25)+(player[3] * 1.5)+(player[4] * 1)+(player[5] * 0.1)))
elif player[7] == "Wanderer":
damage = (10 * ((player[2] * 0.5)+(player[3] * 0.1)+(player[4] * 0.1)+(player[5] * 0.5)))
cur = con.execute("SELECT MobName,MobHealth,MobDamage,Mobexp FROM Mobs where floor = ? and Mob_ID = ?", (player[6],))
mob = cur.fetchone()
list_mob = []
list_player = []
for i in mob:
list_mob.append(i)
for i in player:
list_player.append(i)
return damage,list_player,list_mob```
Here is code for context
!e ```py
import asyncio
class Foo:
def init(self):
asyncio.create_task(self.bar())
async def bar(self):
print("hello")
can ignore this part
async def main():
Foo()
asyncio.run(main())
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
hello
example code^, you can convert it to however you want to use
ohhh so in this case it would be
self.damage,self.player,self.mob = asyncio.create_task(MobEncounter()) I remove class and just leave empty fuction
but, you can assign self.damage etc withing the async function itself
instead of returning them
did you not understand what im trying to say?
imma be honest not really sorry for that im just trying to think in so much stuff
# dont do this.
class Foo:
def __init__(self):
self.hello = asyncio.create_task(self.bar())
async def bar(self):
return "hello"
# do this instead
class Foo:
def __init__(self):
asyncio.create_task(self.bar())
async def bar(self):
self.hello = "hello"```
so in this case I would need to move the method "MobEncounter" to the button class
correct?
your MobEncounter method is also faulty, you forgot to await many things there
A definition of instance variables outside init isn't recommended in general, there are rare cases in which it is natural.
For example, when you have a parent class that defines several variables that its child classes won't use, and whose definition will make its child waste time or resources, or will be simply unaesthetic.
It should be defined there.
oh ye I was fixing it
cause I had it without await and wanted to make it into await thats why im asking here
cause I have this problem for a long long time
alr imma try tysm to everyone

I think I mess up
Hello! No error here but how can I make this more compact? So it doesnt take so many lines?
It seems the only thing different between each is the color?
Consider using a dict to make it look better
can you show me an example?
how would i have a changing discord bot status? so one will be like watching over many members another will be like !help
!e print
@slate swan :warning: Your 3.10 eval job has completed with return code 0.
[No output]
embed_colors = {
None: random.choice(colours),
"blue": 0x...,
...
}
embed = nextcord.Embed(..., color=embed_colors[self.name2.value])
await interaction.send(embed=embed)
It kinda works but if i dont name any color it just does not send anything
I don't know if None is hashable
You might try checking if it's None seperately
Also if you don't say anything it might be "", not sure though
You mean like this? Did i do something wrong
( name2 = Color
name3 = Image)
i think it is
!e
x = {None: 34}
print(x[None])
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
34
you don't need to do that
embed_colors = {...}
if self.name2.value == "":
# use random color
else:
color = embed_colors.get(self.name2.value)
or something similar
same thing
so like this?
I need a gen bot made, can and willing pay!
!rule 9
my fucking bad yo
no worries
use a dict
In theory using .get he doesn't even need the if else block
need help by making it change the embed on the first part of the /help command aka dropdown menu
async def self(interaction: discord.Interaction):
class SelectView(View):
@discord.ui.select(options=[
discord.SelectOption(label="roblox", value="roblox", description="roblox commands"),
discord.SelectOption(label="social", value="social", description="social command"),
])
async def select(self, interaction, select):
if select.values[0] == 'roblox':
em = discord.Embed(color=0x00ff00)
em.add_field(name='roblox', value='roblox commands')
await interaction.response.send_message(embed=em)
if select.values[0] == 'social':
em = discord.Embed(color=0x00ff00)
em.add_field(name='social', value='social commands')
await interaction.response.send_message(embed=em)
view = SelectView()
await interaction.response.send_message('help command', view=view)```
im trying to make it change the first text and make it change to a embed after select a dropdown
Hello!
I am trying to make a verify command and when they clikc the button it sends them a capthca
I have the captcha down but I want to bot to respond with 'Check you dms'
But the dms part is a hyperlink to link to the bot and there dms
How would i do something like that?
Current code:
await interaction.response.send_message(f'{sender.mention} Check your [dms]()')
You can use the jump_url of the message you sent to the user's DM
how do that
Which part?
Getting the sent DM message or getting its jump URL
the linking to the dms
!d discord.Message.jump_url
property jump_url```
Returns a URL that allows the client to jump to this message.
how to i make it just to the dm?
you get the DM message and call .jump_url on it
the user can click on that and it'll take them to the message in the DM
can someone help me about discord.py custom command , permission check.
Hey!
i was wondering how to do this:
i am using pycord
those are context menus
ty
also:
I am trying to add timestamps to my embeds i have that but its off by 7 hours my time how would i fix that?
datetime.utcnow()
how would i make it do mst time?
discord.py has a method for this already, timestamp=ctx.message.created_at
returns error
Traceback (most recent call last):
File "C:\Users\xrkzl\AppData\Roaming\Python\Python310\site-packages\discord\bot.py", line 1008, in invoke_application_command
await ctx.command.invoke(ctx)
File "C:\Users\xrkzl\AppData\Roaming\Python\Python310\site-packages\discord\commands\core.py", line 359, in invoke
await injected(ctx)
File "C:\Users\xrkzl\AppData\Roaming\Python\Python310\site-packages\discord\commands\core.py", line 135, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'NoneType' object has no attribute 'created_at'
is your command a slash command?
yea
what are the commands parameters
@bot.slash_command(description="Returns the bots current ping")
async def ping(ctx):
cool = random.randint(1,3)
first = f"{round(bot.latency* 1000)}ms"
second = f"{round(bot.latency* 2100)}ms"
embed=discord.Embed(description="Pong! \n\n**Initial latency:** `Loading...` \n**Round-Trip latency:** `Loading...`", color=embedcolor, timestamp=times)
embed.set_footer(text=f'Command run by {ctx.author}', icon_url=iconurl)
await ctx.respond(embed=embed)
await asyncio.sleep(cool)
embed=discord.Embed(description=f"Pong! \n\n**Initial latency:** `{first}` \n**Round-Trip latency:** `{second}`", color=embedcolor, timestamp=times)
embed.set_footer(text=f'Command run by {ctx.author}', icon_url=iconurl)
await ctx.edit(embed=embed, delete_after=20.0)
where = ctx.channel
if botlog == True:
embed=discord.Embed(title="Command Logging", color=embedcolor, timestamp=times)
embed.add_field(name="Command ran", value="/ping", inline=False)
embed.add_field(name="Command ran by", value=f"{ctx.author.mention} | {ctx.author.id}", inline=False)
embed.add_field(name="Where", value=where.mention)
await bot.get_channel(logcha).send(embed=embed)
logweb.send(embed=embed)
else:
pass
on @app_commands.check how can I put 2 fuctions?
yea nvm, there is no actual ctx, since no message was sent
i'm sure theres a way for slash commands
don't know it off the top of my head
found the fix lol
instead of datetime.utcnow()
just do
datetime.now()
sudden urge to get back to trying to make bots any significant differences between discord.py and disnake while i was away?
that is one sus folder name
its for a discord server with my friends
but whats the error mean
how do i fix this error
whats the intents argument
Hello, i'm making a blackjack game in my bot and i'm running into an issue
in blackjack you can 'double down' but only if you have not yet drawn any cards after your original 2 starting cards, and if your 2 starting cards add up to a total of 9, 10 or 11 points.
I would like to make it so after the "draw" button has been clicked once, the "double_down" button will be disabled from then on until the game has ended, but I can not figure out how to do it.
I would also like for the "double_down" button to be disabled by default if the player's 2 starting cards do not add up to 9, 10 or 11.
I tried creating a function to evaluate the list player_hand and return true or false then use that value to define the disabled parameter for my button but that did not work out.
class BlackjackButtonHandler(discord.ui.View):
def __init__(self, ctx: discord.Interaction, player_hand, dealer_hand, deck):
super().__init__()
self.ctx = ctx
self.player_hand = player_hand
self.dealer_hand = dealer_hand
self.deck = deck
@discord.ui.button(label='Draw', emoji=bj_draw, style=discord.ButtonStyle.green)
async def draw(self, interaction: discord.Interaction, button: discord.ui.Button):
# my code here
@discord.ui.button(label='Double Down', emoji=bj_dd, style=discord.ButtonStyle.blurple)
async def double_down(self, interaction: discord.Interaction, button: discord.ui.Button):
# more code here
(I omitted most of the irrelevant code)
Please can somebody help me figure it out and thanks in advance (i am using discord.py 2.0.1)
import discord
import random
TOKEN = 'My Token'
intents = discord.Intents.all()
bot = commands.Bot(command_prefix='!', intents=intents)
@bot.event
async def on_ready():
print('We have logged in as {0.user}'.format(bot))
@bot.command()
async def displayembed(ctx):
embed = discord.Embed(
title = "Title",
description = "Description",
colour = discord.Colour.blue()
)
embed.set_footer(text="Footer")
embed.set_author("Bread")
await ctx.send(embed=embed)
bot.run(TOKEN)
it gives me this error
how do I fix it
I was trying to make a simple embed since I'm new to coding a bot
how did you invoke the command
did you do !embed or !displayembed?
you named it displayembed
what you name the function is the command's name
well for now but you'll learn how to not make the function name the command name
yeah do !displayembed
need help by making it change the embed on the first part of the /help command aka dropdown menu
async def self(interaction: discord.Interaction):
class SelectView(View):
@discord.ui.select(options=[
discord.SelectOption(label="roblox", value="roblox", description="roblox commands"),
discord.SelectOption(label="social", value="social", description="social command"),
])
async def select(self, interaction, select):
if select.values[0] == 'roblox':
em = discord.Embed(color=0x00ff00)
em.add_field(name='roblox', value='roblox commands')
await interaction.response.send_message(embed=em)
if select.values[0] == 'social':
em = discord.Embed(color=0x00ff00)
em.add_field(name='social', value='social commands')
await interaction.response.send_message(embed=em)
view = SelectView()
await interaction.response.send_message('help command', view=view)```im trying to make it change the first text and make it change to a embed after select a dropdown
Ok I will
what is the issue here?
I used !displayembed and this error came up
it's name="Bread"
it only accepts kwargs
Oh
if you check the docs the parameters has a * in it
meaning any parameters after is a kwarg
I see
It finally worked
async def displayembed(ctx):
embed = discord.Embed(
title = "Title",
description = "Description",
colour = discord.Colour.blue()
)
embed.set_footer(text="Footer")
embed.set_author(name="Bread")
await ctx.send(embed=embed)```
how would I go about turning this command into a cog in a separate sub-folder?
how did you jump that far from being new to cogs
which version of discord.py are you using, it's different in different versions i think
3.11
discord.py not python version
bruh
oh I don't know how to check that 
do pip show discord.py
how often are we allowed to repost problems here btw
if we dont manage to get help the first time
2.0.1
you should just get a help channel for that at that point
you'll have a better luck a random person will see the help channel rather than scrolling up here
okay thanks
so how would I go about making cogs for discord.py 2.0.1? Just want my commands to be organized in separate folders but still linked to the main file
can you install disnake with 3.11?
seems like some libraries aren't supporting 3.11 yet
cause this should definitely be greater than 14.0
how can i make my discord bot send a message in general when it goes online
message.channel.send
but in what function
@client.event
async def on_ready(message):
print(f'We have logged in as {client.user}')
await message.channel.send("Here's Johnny!")
but it doesnt know what message is
my bad
doesn't work
yh
my bad
how do you do it then?
@client.event
async def on_ready(message):
print(f'We have logged in as {client.user}')
await message.channel.send("Here's Johnny!")
put message in the parentheses
i need to send it to the channel
i got it to work
yh
that would never worked
like this
cool
true
ik
thanks for sharing man that was helpful
I doubt that would work
im gonna try it
it does
Thats odd how the channel object would be in cache on startup
@client.event
async def on_ready(message):
print(f'We have logged in as {client.user}')
channel = channel.get_channel("XXXXXXXXXXXXXXX")
await message.channel.send("Who's got some weed?")
that's supposed to work?
no
why
IDs can't be strings
i did that for sharing purposes
I'm using Ubuntu VM machine to host bot and SQlite ATM. To which SQL should I change to that would be compatible with Ubuntu? cause SQlite has been giving a lot of problems
fancy seeing you around
how are things with you?
wrong place to ask?
good it's just a repeating pattern of going back into bots and then being on hiatus for like 4 months
now i can't install disnake on 3.11
i'm pretty sure most of the libraries are still working on getting to 3.11
Just use poetry
its not just the redistributables you need but the actual MSVC++ build tools compiler crap
is 311 on arch repos yet
frozenlist, yarl, and multidict, which are dependencies of aiohttp, are missing prebuilt wheels for 3.11
so the desktop dev c++ option?
yeah, pretty sure you can untoggle the windows sdk on the right side of that build tools installer to save a couple GB
oh nice it got reduced to 6.7gb to 4.6gb
this definitely gonna take hours
do i still need this after the libraries adds the prebuilt wheels for 3.11?
nah
i'm deleting this shit after
also did any big differences happen when i was away
like between discord.py and disnake
not that i know of
alright ig i'll keep using disnake unless i find something in discord.py that seems better
guild = await client.fetch_guild(1026213629172924446)
role = await guild.fetch_roles()
role = discord.utils.find(lambda r: r.id == 1035377754201399307, role)
# role.members -> []
why does this return an empty list, I have members intent on
fetch_guild wont include members with it
Weird, then what would i use
get the guild object that's cached by your bot using Client.get_guild(...)
that one will be populated with members through the gateway connection
Thank you!
Damn
C:\Users\iamSkev\AppData\Local\Programs\Python\Python311\include\pyconfig.h(59): fatal error C1083: Cannot open include file: 'io.h': No such file or directory
error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio\\2022\\BuildTools\\VC\\Tools\\MSVC\\14.33.31629\\bin\\HostX86\\x64\\cl.exe' failed with exit code 2
i guess you might actually need all 6 gigabytes to install disnake
bruh
lol my bad
Why not just use poetry and 3.10👽
i would rather stub my toe
Why?!??
toe.pyi
name = client.get_guild(id).name
where client is a discord.Client instance of commands.Bot instance
noice finally
i need to somehow remind myself to get rid of this shit after they add support for 3.11
you sure you dont want to keep the build tools? python's got more where that came from
maybe
depends if i remember when they support 3.11
ValueError: mutable default <class 'disnake.utils._MissingSentinel'> for field name is not allowed: use default_factory
i'm assuming this is because of 3.11
how can I start an async fuction inside __init__? create_task doesn't work since its a ui.Select Class
you'd have to import the class from the embed.py to your main file
is there no way to link the files without doing that?
thought a cog could do that
What async function are you trying to start
Cogs can't magically import themselves
You can consider using discord.py's extensions which will allow you to hot load/unload python modules and you can add cogs in those modules
someone explain please?
I think it's just ctx.send_modal.
If it's a slash command.
nah its response
the error is referring to your view itself tho
can u show code for the view? @mossy jacinth
Ah! I've been using too much pycord lately. 😅
pretty sure its still .response.send_modal tho cause it's a slash cmd. but for non slash yea ctx.send_modal
pycord uses ctx in slash cmds too
pycord is quite literally garbage
pygarbage
trashcord
huh. no its just a namespace if ur using ctx in slash cmds. its still .response.send_modal regardless if ur using ctx or inter
but yes pycord smells
no
i mean you can,
but this exists : https://docs.pycord.dev/en/stable/api.html#discord.ApplicationContext.send_modal
you just gotta do ctx.send_modal and it returns ctx.interaction.response.send_modal
bro what the fuck
why lmfaooooooooooo
we don't hate pycord for no reason
wow. thats next level right there
Anyone got a place with examples / detailed explanation of the @ error thing?
I read the docs but I’m too dumb to understand how to use it 
!d discord.ext.commands.Command.error
Is the docs location of it
@error```
A decorator that registers a coroutine as a local error handler.
A local error handler is an [`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") event limited to a single command. However, the [`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") is still invoked afterwards as the catch-all.
Changed in version 2.0: `coro` parameter is now positional-only.
Simple Error Handling for ext.commands - discord.py - error_handler.py
same thing but command sepcific
Aight, lemme check it out
how can we format one liner for loops, like in the code below:
llist_embed.add_field(name='Activated Licenses', value='\n'.join([n for n in alic]))
i want to bold each element in the list but idk how to, i dont want to use it in the value directly coz then the format will apply to all items in the list except for the last one
Hey @slate swan!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
why is it not keeping the tickets button online
"In order to keep views persistent, all their items need to have a custom id and a timeout of None"
can you make your bot start another bot?
Wdym
i want my bot to start other bots
it is possible?
yes but not suggested
!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")...
and whats the full command?
I don't understand your question
It's an decorator
can u pls tell me the whole cmd?
You did not define botperms
how i add the role in?
Set the item argument to either the role's name or its ID
ok
How can I make that when sometimes a moderators name it sends them a dm with the message and timestamp of that message?
like this? 
u messed the indentation up
without looking at ur code we cant help u with that
u should check if something is in the wrong place (maybe just 3 spaces or so)
okay
@slate swan
thats not enough code to see the problem
sure
reaction is a class, u need the amount atribute
wait a min, i'll search in the docs
async def on_message(self,message):```
How can I send a dm to a user with their id (I get id from DB) and send it on this event?
reaction.count >= starData
fetch the user
await self.bot.get_user(id).send(...)```
no
reaction.emoji is the name (str)
reaction.count is the count (int)
starData is the number of stars needed ig, but in ur case its type str
whats starData ?
yeah, but whats the value?
yes
print(type(data[0], data[0])
was sagt dir das?
what does that tells u
sry, switched to german for a sec xD
how do i crash a discord bot within the code?
define "crash"
so, what do u have to do, if reaction.count is an int?
and u want to compare both
cut the server connection
Is your code copy pasted?
thanks
or new to python?
Seems like
Yes, i thought you might me knowing about python but i guess you are a newbie like me lol
np
is there a way to make sub options on a slash command?
what's a sub option?
ok let me explain so its easier to understand im rly bad at explaning XD
take this for example, when user chooses Level it will show another options
depending on first choice
wdym other options its only one argument
No you'll just have to make this another way
Either list all possible arguments on that arg or make 2 more optional args that are used or not depending on the first choice
There's no way to make decisions based on the first choice until the command is actually sent
Hello guys, is there a "test bot" you can invite to check if your bots functions works? I know there was 2 years ago, i just cant find it anymore 😦
Just write tests
Will try look it up
are you talking about "distest"? Or how should i write them?
to use that bot as a test bot? or to make your bot test it features on that bot
i just wannna se if the bot i created greets people when they join the server
like you could invite "FishBot" on quakenet
use an alt account then
i personally just dispatch my own events manually
slash?
if you want them to hide from normal users ( wont include owners and admins ) you can just turn it off from the server settings
yes it can definitely be done through a bot, ill let you know about the method and required perms
gimme a moment
isnt there a check for app_commands?
the commands will still appear
!d discord.app_commands.guilds
@discord.app_commands.guilds(*guild_ids)```
Associates the given guilds with the command.
When the command instance is added to a [`CommandTree`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree "discord.app_commands.CommandTree"), the guilds that are specified by this decorator become the default guilds that it’s added to rather than being a global command.
Note
Due to an implementation quirk and Python limitation, if this is used in conjunction with the [`CommandTree.command()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree.command "discord.app_commands.CommandTree.command") or [`CommandTree.context_menu()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree.context_menu "discord.app_commands.CommandTree.context_menu") decorator then this must go below that decorator.
Example...
can be added as a deco
lol wtf
https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.default_permissions
here's the decorator that you'll be using
Help!
Can i login discord as an end user, not as a bot ?
Yes. that right.
Oh :(. Thank for answer.
i'm getting back to Discord bots, what library should I use now?
hikari
my fingers fell on the keyboard
Is there a way to specify how many characters can be put into a slash command option
Which library are you using?
dpy
I use disnake so idk
do you know how its done on disnake
what's the hex for the default embed color discord.py sends?
in the docs it says 0, but 0 is meant for solid black
!d discord.Colour.default
classmethod default()```
A factory method that returns a [`Colour`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Colour "discord.Colour") with a value of `0`.
#000000
that would be the hex for the interger 0
a quick google tells me #23272A is the 'official discord color palette black'
i tried that and this is what i get
try #23272A?
pulled it from a table on this page https://gist.github.com/thomasbnt/b6f455e2c7d743b796917fa3c205f812
sweet
ty
np
what kind of bot are you looking for? theres thousands already made
- i want somting that has all in one
- i want the name and logo to be my choyce
😄
thats a lot of work. good luck in your search.
thx mate
will using two different databases throughout my bot cause any performance issues or anything i'm not aware of? One being a large mongo database and the other being a large postgre database
any possible way to stop the example link at the ")!"?
So that the )! is in a normal white color?
use "('https://......png')!" maybe
can someone help me w making the buttons always work? everytime i run the bot twice the buttons are not working same w select menus, how do i make it work everytime?
disnake.ext.commands.Param(default=Ellipsis, *, name=None, description=None, choices=None, converter=None, convert_defaults=False, autocomplete=None, channel_types=None, lt=None, ...)```
A special function that creates an instance of [`ParamInfo`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.ParamInfo "disnake.ext.commands.ParamInfo") that contains some information about a slash command option. This instance should be assigned to a parameter of a function representing your slash command.
See [Parameters](https://docs.disnake.dev/en/latest/ext/commands/slash_commands.html#param-syntax) for more info.
see min_lenght and max_lenght
ahhh
you need persistent views, what library are you using?
not really but u will have two connections open when it's not really necessary
i see no point of having two different type of database storage system just for storing data
unless u are using one for like cache and other for storage or something
It would be better to have one database with 2 tables to make things easier implementing
Ofc
Redis😳
its is because my bot is a bit larger and used mongodb mainly, with already billions of documents and members data. I plan on switching to postgre for larger data entries as mongo is beginning to slow my bot down. I dont want to have to do a whole rewrite in the entire bot
dont use a permanent postgres connection, they are resource consuming, use a pool instead
we use redis for cache
i don't think it's a mongo issue specifically u should check efficiency of ur code
You can use an algorithm to transfer all the data?
mongo connections are usually cheap
^^
discord.py is async while mongodb motors wrapper is pymongo thrown in executor

it blocks dpy after thousands of fetches
you can interact with the mongo api using aiohttp / httpx* if you really want it to be complete async
Hey how can i check if the value of self.name2.value is in a list and if not send a message? I know the code is messy and i repeat myself, I tried using a dict but failed miserably...
even there the buttons arent working all the time
You can just have a dict e.g
{"blue": 0x0000FF}
Then you can use dict.get and check the return value or just index the key with a try-except
can someone help me w making the buttons always work? everytime i run the bot twice the buttons are not working same w select menus, how do i make it work everytime?
Do these events work with slash commands?
found this
but I don't see anything on the console
yeah you just gotta add add between them
code ?
^^
# DISCORD
import discord
from discord.ext import commands
class Logs(commands.Cog):
def __init__(self, client: commands.Bot) -> None:
self.client = client
@commands.Cog.listener()
async def on_app_command_completion(
self, interaction: discord.Interaction, command: discord.app_commands.Command
):
print("REGISTRADO")
async def setup(client: commands.Bot) -> None:
await client.add_cog(Logs(client))
print(f"Module logs.py was loaded succesfully.")
AttributeError: 'Bot' object has no attribute 'listener'
@bot.listener()
did that instead of @commands.Cog.listener()
but i dont have cogs then what do i do
are you using commands.Bot or discord.Client?
commands.Bot
wasn't it bot.listen()?
ill try
can you even create discord bot in python btw?
you can
really wow!
you can create one in any language which is capable of making web requests
ohk! didnt knew that
you can build a discord Bot in assembly too
i have no idea what assembly language is
the programming language closest to the machine language
btw i never figured out what's the difference between the high level programming language and object oriented programming language
i have heard python is object oriented
or both
?
There isn't always a difference
i never figured it out
oh
Rust, is also not object-oriented and is high level (to a definition of high level)
so it it like both?
python is pretty special
It can be
Python gives you the option of using objects or not
You can do functional programming in Python if your heart desires so
like what does objected oriented and high level means?
👀
You probably want to take apart and define "object oriented" and "high level"
"object oriented" - any language that supports typical implementation details of object orientation, such as classes, objects, inheritance, polymorphism, etc
"high level" - how far away from the CPU it is, not in terms of physical distance, but that of abstraction layers
object oriented is basically dealing with data as objects, in python they are generally implemented using classes and high level basically means easier for humans to write/understand
Having both, a language can be deemed to be "object oriented" and "high level"
oh isee
Examples of high level - Java, Python, Rust, JS/TS
Examples of low level - C, Rust, Zig, Assembly, etc
oh!!
danm, didnt knew that,
A high level language is basically a language with allot of abstractions
Abstractions meaning features a user can use and other internal features
and automatic memory management ofc
import discord
from discord.ext import commands
import sqlite3
import random
class Event(commands.Cog):
def _init_(self,bot):
self.bot=bot
@commands.Cog.listener()
async def on_ready(self):
db = sqlite3.connect("main.sqlite")
cursor = db.cursor()
cursor.execute('''CREATE TABLE IS NOT EXISTS main (
user_id INTERGER, wallet INTERGER, bank INTERGER
)''')
print("BOT IS ONLINE")
@commands.Cog.listener()
async def on_message(self, message):
if message.author.bot:
return
author = message.author
db = sqlite3.connect("main.sqlite")
cursor = db.cursor()
cursor.execute ("SELECT user_id From main Where user_id is = (author.id)")
result = cursor.fetchone()
if result is None:
sql = ("INSERT INTO main(user_id, wallet, bank) VALUES ?, ?, ?")
val = ("author.id 100,10")
cursor.execute(sql, val)
db . commit()
cursor.close()
db.close()```
This is what I have in the other folder but for some reason it says it can't import it
Really can't find the issue as to why it won't import
Why dont you just use the async function named setup?
how do I go about using that function?
Guys, how do I add a spaceb etween title and description
You just add it under a class declaration e.g
async def setup(bot: commands.Bot) -> None:
await bot.add_cog(Event(bot))
and after that you would use discord.ext.commands.Bot.load_extension
Ok gotta
my discord bot wont pop up in integrations, but its in the server. Any idea why?
when using select/buttons - the buttons/selections dont work after I restart the bot.
is there a way to work around this?
SAME
im trying to get help for it too
see an example for making views persistent
Have you synced?
i did it'
and it still doesnt work
what do u mean sync?
then you mustn't have done it right :p
Sync your local commands to discord
if you don't everything stays on your computer
examples/app_commands/basic.py lines 25 to 28
async def setup_hook(self):
# This copies the global commands over to your guild.
self.tree.copy_global_to(guild=MY_GUILD)
await self.tree.sync(guild=MY_GUILD)```
It works in another server, a test server. Just not the server the bot is gonna be utilized in
Hello, I have made a blackjack game for my bot using discord.py 2.0.1. The bot uses buttons that the user can press to choose whether they want to draw, stand or double down. I also created a timeout function that disables the buttons and effectively ends the game if too much time has passed without any user input.
Everything works as intended and the game itself runs perfectly fine, however I am running into an issue where the on_timeout function will still be called some time after the player has ended their game and I am looking for a way to 'cancel' the timeout after the game has ended.
here is my relevant code:
class BlackjackButtonHandler(discord.ui.View):
def __init__(self, ctx: discord.Interaction, player_hand, dealer_hand, deck, bet):
super().__init__(timeout=3) # placeholder value
self.ctx = ctx
self.player_hand = player_hand
self.dealer_hand = dealer_hand
self.deck = deck
self.bet = bet
self.update()
@discord.ui.button(label='Draw', emoji=bj_draw, style=discord.ButtonStyle.green)
async def draw(self, interaction: discord.Interaction, button: discord.Button):
deal_card(self.player_hand, self.deck)
embed_updated = embed_new(interaction, self.player_hand)
elif determine_total(self.player_hand) > 21:
embed_add_field_dealer_unknown(embed_updated, self.dealer_hand)
embed_updated.add_field(name='Loser!',
value='😢 You went bust, better luck next time!',
inline=False)
await interaction.message.edit(embed=embed_updated, view=None)
# Game would 'end' here because the player went above 21, so the buttons will disappear and the timeout should be cancelled
async def on_timeout(self):
embed_timeout = embed_new(self.ctx, self.player_hand)
embed_add_field_dealer_unknown(embed_timeout, self.dealer_hand)
embed_timeout.add_field(name='Timed out!',
value='🕑 You ran out of time!',
inline=False)
self.draw.disabled = True
self.stand.disabled = True
self.double_down.disabled = True
await self.ctx.edit_original_response(embed=embed_timeout, view=self)
If anybody can help me figure this out it'd be much appreciated and thank you in advance.
Is there another button you can use to end the game?
class PersistentView(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
@discord.ui.button(label='Green', style=discord.ButtonStyle.green, custom_id='persistent_view:green')
async def green(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.send_message('This is green.', ephemeral=True)
@discord.ui.button(label='Red', style=discord.ButtonStyle.red, custom_id='persistent_view:red')
async def red(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.send_message('This is red.', ephemeral=True)
@discord.ui.button(label='Grey', style=discord.ButtonStyle.grey, custom_id='persistent_view:grey')
async def grey(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.send_message('This is grey.', ephemeral=True)
class PersistentViewBot(commands.Bot):
def __init__(self):
intents = discord.Intents.default()
intents.message_content = True
super().__init__(command_prefix=commands.when_mentioned_or('$'), intents=intents)
async def setup_hook(self) -> None:
self.add_view(PersistentView())
async def on_ready(self):
print(f'Logged in as {self.user} (ID: {self.user.id})')
print('------')
bot = PersistentViewBot()
@bot.command()
async def prepare(ctx):
await ctx.send("What's your favourite colour?", view=PersistentView())```
tried her code and it doesnt show it
Is the setup hook being called? It's possible you may be on an older version of discord.py and setup_hook isn't being called
Probably not but worth putting a print statement in there
oh maybe
@bot.event
async def setup_hook(self) -> None:
print(f"{bot.user.name} is online!")
try:
synced = await bot.tree.sync()
print(f"Synced {len(synced)} command(s)")
except Exception as e:
print (e)
self.add_view(PersistentView())```
``` self.add_view(PersistentView())
IndentationError: unexpected indent```
I created 3 buttons for 'draw', 'stand' and 'double down'. The bot automatically detects when certain criteria have been met for the game to end and plays it out accordingly, so the user doesn't have to click a button to end the game themselves.
I'm looking for a way to explicitly stop the timeout from elapsing when these certain criteria have met (such as the player going 'bust' and getting above 21 points)
Ah. You're looking for self.stop() within the view
Not sure if setup hook is an event
I meant something like
class PersistentViewBot(commands.Bot):
...
async def setup_hook(self) -> None:
print("Setup hook called")
self.add_view(PersistentView())
are you able to give an example? I tried self.stop() already with seemingly zero effect
.bm command linking
So my bot wont show up in my integrations page in my server. why?
how can i use a space between a slash command name
this does work when I use it in its own file like a main file, but is there a way to do this inside a cog?
Put self.stop() after you edit your message to reflect that they busted
i tried using space between the name but it always gives me error
subcommand
can u give me quick example or link to documentation
I have done, but i'm still getting timed out after going bust
elif determine_total(self.player_hand) > 21:
embed_add_field_dealer_unknown(embed_updated, self.dealer_hand)
embed_updated.add_field(name='Loser!',
value='😢 You went bust, better luck next time!',
inline=False)
await interaction.message.edit(embed=embed_updated, view=None)
self.stop()
damn i’m not home atm but i’m sure someone else can or i can once i’m back :)
oh it's okey
thanks for help
You can add_view inside your cog's __init__ given the cog is being loaded in your setup hook
you did that for each button?
well i guess the only way youd bust is on a draw...
try on_timeout(self) -> None:thats how mine looks and it works correctly
im not 100% sure what the -> does yet tbh i havent read up on it
I have a ton of scammers in a server I am a staff in. They go by the name sᴛʀɪᴋᴇ ɪᴛ ʙɪɢ or 𝗦𝘁𝗿𝗶𝗸𝗲 𝗜𝘁 𝗕𝗶𝗴. They are different fonts/language characters. Anyway to search all common fonts and languages for characters that resemble Strike It Big? I currently have some basic code that catches the newbs of the scamming world:
if member.name.lower() == 'strike it big':
await member.ban(reason='Impersonating Mark - Custom Bot Auto Ban')
print('Banned a wild SIB impersonator!')
embed = discord.Embed(
title=":sparkles: Impersonator Banned :sparkles:", description=f"A member by the name of 'Strike It Big' joined the server and was instantly banned by our auto-detection service! \nUser Name: {member} \nUser ID: {member.id}", color=0x336EFF
)
await channel.send(embed=embed)
if member.name.lower() == 'strikeitbig':
await member.ban(reason='Impersonating Mark - Custom Bot Auto Ban')
print('Banned a wild SIB impersonator!')
embed = discord.Embed(
title=":sparkles: Impersonator Banned :sparkles:", description=f"A member by the name of 'Strike It Big' joined the server and was instantly banned by our auto-detection service! \nUser Name: {member} \nUser ID: {member.id}", color=0x336EFF
)
await channel.send(embed=embed)
This is ran on_member_join.
I put self.stop() as the very first line of code within the 'stand' and 'double down' buttons and they work, I don't get timed out after standing or doubling down
still getting timed out after going bust or landing on 21 after drawing though
update: i'm getting timed out after going bust or standing like 50% of the time
@mighty pilot (sorry forgot to click reply)
So my bot wont show up in my integrations page in my server. why?
do you have 50+ Bots?
yes
the integrations page currently shows only the first 50 Bots
so then?
remove some bots
can I not manage the b ot