#discord-bots
1 messages ¡ Page 237 of 1
!followup
sir, can you tell me how can i make a new file in vs code for data storage?
.........
@slate swan ]
đ expecting i will not get ignored
can u explain sir? pls
to make my code organised can i make another file in the main.py folder for data storage by the use of mysql
ty for replying sir
Why doesnât my pip install work on python windows?
u are new?
Not really, I already created multiple bots but I always installed modules by doing -py -3 -m install (module)
ic
!dashmpip
When trying to install a package via pip, it's recommended to invoke pip as a module: python -m pip install your_package.
Why would we use python -m pip instead of pip?
Invoking pip as a module ensures you know which pip you're using. This is helpful if you have multiple Python versions. You always know which Python version you're installing packages to.
Note
The exact python command you invoke can vary. It may be python3 or py, ensure it's correct for your system.
anyone know how to make purge command
its not about me ignoring you its about me not having time to answer when i have time i look into this channel no need to ping me
man u asking to spoon feed code
ummm sir if u have time now can u explain
try how it says: python -m pip install your_package
the >>> prompt means you're in the python interpreter, not your regular terminal
Ohhh mb mb
ctrl+z then enter to exit the interpreter, then run your py command
oh did not see that
right 
Ty guys
sry for wasting ur time sir
explain what?
Im also wondering how I can separate my stuff between multiple files
I never really done that before. I got a like 500 lines code
in a discord bot?
.
use cogs
Alright imma check that out ty
why not
how tho

i dont know what exactly you mean
what you want to separate
database logic?
like there is the main code for strt command but when i want to make my data storage code in vs code in a diffrent file
what do you mean by data storage
show code or example maybe i will understand
what should i put in 'config'
delete this, you exposed your token
for sure not your token
theres no code tho
leave ty for ur time sir
i assume you're trying to create malware so im not even gonna bother to help u
cogs/extensions are discord.py's helper features for separating commands, but they build upon python's module system so you should learn how to write them correctly - afterwards it becomes easy to refactor into different files
https://docs.python.org/3/tutorial/modules.html
what is the point of creating the config file to not show your token in the code and still put it as default value
.env (dotenv) files are a type of file commonly used for storing application secrets and variables, for example API tokens and URLs, although they may also be used for storing other configurable values. While they are commonly used for storing secrets, at a high level their purpose is to load environment variables into a program.
Dotenv files are especially suited for storing secrets as they are a key-value store in a file, which can be easily loaded in most programming languages and ignored by version control systems like Git with a single entry in a .gitignore file.
In python you can use dotenv files with the python-dotenv module from PyPI, which can be installed with pip install python-dotenv. To use dotenv files you'll first need a file called .env, with content such as the following:
TOKEN=a00418c85bff087b49f23923efe40aa5
Next, in your main Python file, you need to load the environment variables from the dotenv file you just created:
from dotenv import load_dotenv()
load_dotenv(".env")
The variables from the file have now been loaded into your programs environment, and you can access them using os.getenv() anywhere in your program, like this:
from os import getenv
my_token = getenv("TOKEN")
For further reading about tokens and secrets, please read this explanation.
whats the detection on the antivirus
ty for giving ur time in writing so much for me
what are you compiling your python file into an exe with, pyarmor?
Mind explaining how that is related to the channel's topic 
good one
By asking in the correct channel first
E.g. #1035199133436354600
Command 'clear' raised an exception: InteractionResponded: This interaction has already been responded to before
@app_commands.command()
async def clear(self, interaction: discord.Interaction, amount: int) -> None:
await interaction.response.defer(thinking=True)
cleared = await interaction.channel.purge(limit=amount, bulk=True)
clearembed=discord.Embed(
title="",
description=f"Successfully cleared {cleared} message(s).",
color=0x313338
)
await interaction.response.send_message(embed=clearembed)```
hmmmmm
interaction.followup.send
You don't use interaction.response.send_message after deferring a message
Command 'clear' raised an exception: NotFound: 404 Not Found (error code: 10008): Unknown Message
hmmmm
God these 'hmmmm' are so superfluous
mhmm
sir how can i store data in my bot
@slate swan
wht is help cooldow btw
Is there a way i can do my own commands like instead of greet i can do greet {user}or something
I just did a leveling bot (really basic) but when I do my =lvl command, nothing shows up. not even an error message. my script = https://paste.pythondiscord.com/lamaxebiga
can someone help?
oh ok, thanks
send_message not send
Consider at least reading the docs https://docs.disnake.dev/en/stable/ext/commands/slash_commands.html
someone help?
which one is better? disnake nextcord or discord.py?
discord.py imo
Same
!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...
you might find more help with discord.py here, but online guides are lacking for dpy's newer features afaik, particularly app_commands
I just did a leveling bot (really basic) but when I do my =lvl command, nothing shows up. not even an error message. my script = https://paste.pythondiscord.com/lamaxebiga
How do i make the bot send sever emojis like this
in a discord embed?
type \ before the emoji and paste the emoji on the embed
!rival_check like this
yup
i undestand, but i cant seem to replicate this, with discord.py, as it looks WAY more easier than the normal use
yas
equivalent: ```py
bot = commands.Bot(command_prefix="whyisthisstillneeded", intents=...)
@bot.tree.command(name="hello", description="This is a hello command")
async def test(interaction: discord.Interaction):
"""This is a hello command"""
# ^ A docstring can be used instead of description=
await interaction.response.send_message("Sup")
@bot.event
async def setup_hook():
# Sync global commands on startup
await bot.tree.sync()```
Not really "for no reason"
well did you want me to give 0 context instead? for the goal of defining a slash command within the same file as your bot definition, it looks almost identical to disnake py @bot.slash_command(name="hello", description="This is a hello command") async def test(interaction: disnake.ApplicationCommandInteraction): await interaction.response.send_message("Sup") py @bot.tree.command(name="hello", description="This is a hello command") async def test(interaction: discord.Interaction): await interaction.response.send_message("Sup")
although disnake has interaction.send() which simplifies followup messages, so its got that going for it
instead of that, can i use description?
and if green line is equal to red line, whats the point of that
It's called proper documentation
so i can use description and it will be ok?
Try it and see
its giving me this error
docstrings are a standard way of documenting functions so i would recommend using it
plus, dpy can parse google/sphinx-style parameter descriptions from the docstring too
why do we need to use command_prefix if its outdated
dunno, if you really want to disable it then use an on_message event that doesnt call process_commands()
that's bad
personally i use slash and prefix commands but with commands.when_mentioned() to allow @mentioning the bot, it'll still work regardless of message content
i see, but if in case i wanna do it like you, commands.when_mentioned() how wold that work?
command_prefix=commands.when_mentioned()
command_prefix=commands.when_mentioned, without the parentheses
without?
discord.ext.commands.when_mentioned(bot, msg, /)```
A callable that implements a command prefix equivalent to being mentioned.
These are meant to be passed into the [`Bot.command_prefix`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.command_prefix "discord.ext.commands.Bot.command_prefix") attribute.
> Changed in version 2.0: `bot` and `msg` parameters are now positional-only.
>
>
nice formatting
oh this is taken as the callback you can create on your own


guys help
PS C:\Users\Sakura\Discord Bot> & C:/Users/Sakura/AppData/Local/Microsoft/WindowsApps/python3.10.exe "c:/Users/Sakura/Discord Bot/bot.py"
Traceback (most recent call last):
File "c:\Users\Sakura\Discord Bot\bot.py", line 43, in <module>
os.chdir(r'C:\Users\Sakura\Discord Bot\bot.py')
NotADirectoryError: [WinError 267] The directory name is invalid: 'C:\Users\Sakura\Discord Bot\bot.py'
the space
naw the filename
im wondering about how would the bot behave with that command
file is not a directory
like any other prefix, if your message starts by mentioning the bot, it tries to parse the rest of your message as a command
so it would be like @polar scroll hello
@lament depot how you doing

also a good idea to have an error handler for catching commands.CommandNotFound, usually to do nothing but lancelot tried autocompleting the command
also, another question that i wanted to ask, is about cogs.
ive seen people using cogs to organize their code, but i cant seem to undestand classes in python (yes ik its basic), do you have another way that i could do so?
technically you can define standalone commands in separate files and manually add them to your bot, but cogs will still be more convenient to write
I just did a leveling bot (really basic) but when I do my =lvl command, nothing shows up. not even an error message. my script = https://paste.pythondiscord.com/ihopotakis
here's a pretty minimal example:
https://discordpy.readthedocs.io/en/stable/ext/commands/cogs.html
https://discordpy.readthedocs.io/en/stable/ext/commands/extensions.html ```py
main.py
bot = commands.Bot(...)
@bot.event
async def setup_hook(): # called exactly once after your bot logs in
await bot.load_extension("path.to.my_extension") py
path/to/my_extension.py
from discord import app_commands
class MyCog(commands.Cog):
@app_commands.command()
async def my_command(self, interaction: discord.Interaction):
await ctx.send("Hello world!")
the setup() here gets called when load_extension() is used
async def setup(bot):
await bot.add_cog(MyCog())``` see also online guides to object-oriented programming so you can make the most out of classes
https://www.youtube.com/playlist?list=PL-osiE80TeTsqhIuOqKhwlXsIBIdSeYtc
https://realpython.com/python3-object-oriented-programming/
code seems fine, does your bot have permissions to read messages in the channel you're in?
Yes thatâs why I find it weird
can you try printing the message content when your on_message event receives it?
It doesnât
I tried with 3 different print messages
and your bot shows up as online right after you run your script?
or rather idle in your case
Yep and both "Bot is ready" and "Bot is online" print shows up
Im not really familiar with using extensions like sqlite 3 but maybe I can show you the database inside when I try sending a message and you tell me whatâs wrong
if you put a print right on top of on_message but it didnt run, aiosqlite probably isnt your issue
I see
unless aiosqlite is somehow blocking your event loop, but you can check that by terminating it early with ctrl+c and looking for a traceback
Yes ok I see, when I send an introduction message, which is on_message i little bit further into my code, it doesnât work either now
It used to work but it doesnât anymore
Do you want to see my integrate code?
Wait so I just run my code and do ctrl+c?
chat gpt said Based on the code you provided, it seems that the use of aiosqlite is not blocking the event loop. The code properly uses async with statements and awaits all database operations, which is the recommended way to handle asynchronous I/O operations in Python.
That might be because I have 2 times the on_message event in my script?
oh thats definitely the cause
So I should put the introduction on message in my other event
only the last on_message applies if you're using the @bot.event decorator
combine them together or use @bot.listen("on_message") instead
that by itself is an incorrect statement to make, because what actually matters is whether the source code for aiosqlite is implemented correctly - seeing that they are awaited implies that they would cooperate and yield to the event loop, but that doesnt mean their implementation will do that
though tbf chatgpt said "it seems" that way so its not overconfident about that answer
@bot.listen is not how that decorator's meant to be used, and you also dont need to use process_commands() if all your on_message handlers are listeners
for example: ```py
@bot.listen("on_message")
async def on_message_experience(message):
async with bot.db.cursor() as c:
...
@bot.listen("on_message")
async def on_message_introduction_thread(message):
...```
Alright cool that worked thx! My other concern is that now, my second bot.listen doesnât work anymore ->
it's @bot.listen()
you're missing the braces, also the argument there should be a message not ctx for the sake of naming
Oh woops ty
how can i do a /ping and the the answer in ms
!d discord.Client.latency
property latency```
Measures latency between a HEARTBEAT and a HEARTBEAT\_ACK in seconds.
This could be referred to as the Discord WebSocket protocol latency.
multiply it with 1000 to get in ms
Python allows you to set custom attributes to most objects, like your bot! By storing things as attributes of the bot object, you can access them anywhere you access your bot. In the discord.py library, these custom attributes are commonly known as "bot variables" and can be a lifesaver if your bot is divided into many different files. An example on how to use custom attributes on your bot is shown below:
bot = commands.Bot(command_prefix="!")
# Set an attribute on our bot
bot.test = "I am accessible everywhere!"
@bot.command()
async def get(ctx: commands.Context):
"""A command to get the current value of `test`."""
# Send what the test attribute is currently set to
await ctx.send(ctx.bot.test)
@bot.command()
async def setval(ctx: commands.Context, *, new_text: str):
"""A command to set a new value of `test`."""
# Here we change the attribute to what was specified in new_text
bot.test = new_text
This all applies to cogs as well! You can set attributes to self as you wish.
Be sure not to overwrite attributes discord.py uses, like cogs or users. Name your attributes carefully!
guys how could I make so the bot var gets type hinted on cogs?
use a bot subclass and define them as instance attributes, then typehint with your bot subclass
you can typehint them in your Bot subclass
from discord.ext import commands
class MyBot(commands.Bot):
a_bot_var: bool
def __init__(self):
...
self.a_bot_var = True
although it will be a bit inconvenient with Context/Interaction since their bot/client attribute assumes a regular bot/client
ya thats one workaround
at least with Context you could set the generic typevar yourself, or make a subclass that fills in the generic typevar: py class Context(commands.Context[MyBot]): ... but with dpy's app_commands.command() decorator your type checker would complain if you tried writing discord.Interaction[MyBot]
Hey @hushed galleon can i ask you something about mysql
I know this stuff must be placed in #databases but you give the best answers
why me
plus it sounds more appropriate for #databases, just ask whatever question you have there
can someone help?
im trying to get the bots latency, but i cant seem to get it to work
bot.latency, like that
its giving me a big number, how do i sort it out
Multiply by 1000 and you get the ms, then round that
if im not mistaken is it something like {:2f}
You end up with
round(bot.latency*1000)
i did smth like this
but it didnt work

I also have something not working on my screen, maybe you can help me without knowing the error :)
hey can someone help me out. I'm a beginner in python. I have learnt the basic stuffs. I was tryna create a discord which can stream music in order to learn about the discord.py module. But it wont run for some reason. Please help me out.
i could help

My point is, give the error
https://pastecode.io/s/dmhgmccr this is the main file
https://pastecode.io/s/w1hrfckj this is the cog file
Contains commands to the bot
the error its showing is it doesnt have the command "play"
That's not the error, the error is in your console
!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 you're breaching YouTube's Terms of Services and won't be getting help for doing it
You're using + with string and integer
you are trying to add int and str
Use f-strings or convert your integer to a string
!e "hi" + 5
@slate swan :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 1, in <module>
003 | "hi" + 5
004 | ~~~~~^~~
005 | TypeError: can only concatenate str (not "int") to str
!f-strings
Creating a Python string with your variables using the + operator can be difficult to write and read. F-strings (format-strings) make it easy to insert values into a string. If you put an f in front of the first quote, you can then put Python expressions between curly braces in the string.
>>> snake = "pythons"
>>> number = 21
>>> f"There are {number * 2} {snake} on the plane."
"There are 42 pythons on the plane."
Note that even when you include an expression that isn't a string, like number * 2, Python will convert it to a string for you.
Great, i forgot. Thanks
how do i use slash commands with this? (discord.py)
!d discord.ext.commands.Bot.hybrid_command
@hybrid_command(name=..., with_app_command=True, *args, **kwargs)```
A shortcut decorator that invokes [`hybrid_command()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.hybrid_command "discord.ext.commands.hybrid_command") and adds it to the internal command list via [`add_command()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.add_command "discord.ext.commands.Bot.add_command").
wat
Max app commands are 100 or 50? Can't find on the docs
so my =lvl enable and =lvl disable isnt working and I have no idea why. here's my code = https://paste.pythondiscord.com/onehikexun
and here's the error = https://paste.pythondiscord.com/eguvevenun
"Member "enable" not found."
Yep thatâs my error
An app can have the following number of commands:
100 global CHAT_INPUT commands 5 global USER commands 5 global MESSAGE commands
https://discord.com/developers/docs/interactions/application-commands#registering-a-command
I mean it basically told you whats wrong
â¤ď¸
I dont get what I have to change tho both enable and disable are defined
Its my first time dealing with this error
whats happening is that when you run your command, it'
s running the lvl command. You have a seperate handler for lvl enable, but the way you made it, the bot thinks you're trying to run the lvl command and passing in 'enable' as an argument for the member
Oh so if I switch lvl enable to enable it will work?
I'd suggest taking a look at command groups
I don't remember where the docs for them are though đ
Will do, its my first time dealing with them ngl
Oh ty!
Groups are super useful for grouping togther related commands.
are there any good new hosting sites?
I would recommend using Oracle or AWS đ
TypeError: CommandTree.command() missing 1 required positional argument: 'self'
I'm trying to use
@app_commands.tree.CommandTree.command()
@app_commands.describe()
inside a class ClassName(commands.Cog)
I pass self, in the initializer and super initializer, but i still get the error? đ¤ˇââď¸
use @app_commands.command() instead of the tree thingy you've got going
ty!
then would it still be
async def function(self, bot)
self.tree = app_commands.CommandTree(self)
await self.tree.sync()
No need.
Write your own syncing command, so you don't have to rely on any of that.
I can send you one.
Whereas for the command, it shld be: py @app_commands.command(name="play", decsription="A command that plays games") async def play(interaction: discord.Interaction) -> None: ...
don't make the tree yourself
but they need to be synced to be registered. no?
yes but you're syncing in the command
just use jishaku's sync
@commands.is_owner()
@commands.command()
async def sync(self, ctx: commands.Context) -> None:
await self.bot.tree.sync()
await ctx.send("Synced the command tree.")
or write something like this
Yes. I can send you a good sync comamnd if you like.
Having control over global and local syncing.
I have a question about something. The command I set earlier in my group was =lvl enable and =lvl disable. I just changed them to =enable and =disable and it says Command "enable" is bot found.
And the old one gives me an error code
Even after restarting my file and creating a new db
Can you send code?
Sure
AttributeError: 'TestSlashCommands' object has no attribute 'http' I'm not passing http? or is it because my bot's being passed as discord.ext.commands.bot.Bot?
You should be using discord.ext.commands.Bot for ur bot.
!traceback Can you send full 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.
You donât under my problem
Command used to be =lvl enable and =lvl disable
I changed it to =enable and =disable
If you are getting aerror, there should be a traceback.
What is the equal sign?
Prefix
Prefix probably
Oh
No traceback, no nothing?
But I changed them
If you just want =enable, why do you have slvl.comamand()?
#main.py
class MyBot(commands.Bot):
def __init__(self, *args, **kwargs):
intents = discord.Intents.all()
self.bot = commands.Bot(command_prefix="!", intents=intents)
super().__init__(command_prefix="!", intents=intents, *args, **kwargs)
this is how i set up my bot.
no it's ok, ty tho.
You could just do @bot.command().
Yup.
If you just want =enable, don't provide a group.
A group is for grouping commands.
I want =disable too
Then do @bot.command() for that as well.
Ye
Ur sure there isn't anything there?
Lemme try to reset again
R u using smth like db browser.
Wait, print what is returend @opaque elk
Print the type, and whatever value.
print(type(levelsys[0]))
No
R u using sqlite?
aiosqlite ye
or the dbviewer in vscode
I can see it with an extention
And is there anything there?
I see the xp stuff
But I dont see where enable/disable is located
Ok wait
Thereâs also this
Im pretty sure we need the second one
it shows 0 instead of true/false? o.O
Anybody in here familiar with payment methods for premium discord bots? Wondering if any particular one is better than others
I sent them
Discord offers built in support for that
Thought that was just premium discord servers?? I missed that update I guess
Isn't that restricted to selective bots?
I dunno. I like the way the button looks.
IIRC it is very restricted.
It looks to be available to verified bots only
You can't just be verified.
I'm aware lol
Guess I'll compare and contrast the bigger name api like patreon and PayPal for my stuff
Ig patreon and ko-fi are good options for you
Stripe is also pretty common, they have a nice API for developers
Yes but you cant use paypal
Someone mentioned that when I asked in general chat. Gonna look into stripe as well
what's wrong with my code? https://paste.pythondiscord.com/ugayisiyev
What's the best way to make a giveaway command? (with buttons)
I plan to open source my giveaway bot once I make buttons for it. Right now it uses reactions but doesn't require a database
I'm trying to just make a ,giveaway command but with buttons. I'm not sure what would be the best approach
Check what value is getting returned.
Make a /giveaway command which takes arguments for whatever you want. Put those arguments in an embed, create a View for your buttons and what they do. I recommend putting a counter in the embed so people can see it increase when they hit it
I am curious what the type is. Print that. Also, the object that we will see should have some attribute for data.
Will it need to have a database?
Not necessarily. It will all be during runtime. I don't think counter information will be useful after the fact. If you really want a database, you could use something like ReDis.
It makes it easier but it's not required. You can set a sleep function then at the end check the users
Where should I put that in my script? Sorry I lost myself TwT
In ur enable and disable callbacks.
No no I know that
Do I put it right before cursor.fetchone() ?
Or its the wrong positionnement
Put it in ur if statement where it is saying it is already enabled.
Just enable for now.
ok so by doing enable, I got <class 'int'> printed
so... which of these, or whatever solution, would fix this?
class MyBot(commands.AutoShardedBot):
def __init__(
self,
*args,
initial_extensions: List[str],
db_pool: asyncpg.Pool,
web_client: ClientSession,
testing_guild_id: Optional[int] = None,
**kwargs,
):
super().__init__(*args, **kwargs)
self.db_pool = db_pool
self.web_client = web_client
self.testing_guild_id = testing_guild_id
self.initial_extensions = initial_extensions
class MyBot(Client):
def __init__(self, *args, **kwargs):
intents = discord.Intents.all()
super().__init__(command_prefix="!", intents=intents, *args, **kwargs)
class MyBot(commands.Bot):
def __init__(self, *args, **kwargs):
intents = discord.Intents.all()
self.bot = commands.Bot(command_prefix="!", intents=intents)
super().__init__(command_prefix="!", intents=intents, *args, **kwargs)
@gusty flax
second one
but Client should be commands.Bot
and you don't need *args and **kwargs
Hey mud you got like 5-10 mins for me after?
class MyBot(commands.Bot):
def __init__(self) -> None:
super().__init__(
intents=discord.Intents.all(),
command_prefix="!",
...
)
@slate swan
then you can do your database stuff as an argument in MyBot.init
ty!
your code is littered with queries
make a helper function instead
async def _is_leveling_system_enabled(self) -> bool:
one more question. how would i pass the bot into context for the main.py? like for loading and unloading extensions?
#@commands.is_owner()
@commands.has_any_role(settings.OWNER_ROLE, settings.ADMIN_ROLE, settings.MODERATOR_ROLE)
@commands.command(name="load", aliases=["l"], hidden=True,)
async def load(self, ctx, *, module):
"""Loads a module."""
try:
self.bot.load_extension(module)
await ctx.send(f"Loaded {module}.")
except Exception as e:
await ctx.send(f"Failed to load {module}:\n{e}")
async def load_modules(self):
for root, dirs, files in os.walk("cog_extensions"):
root = os.path.normpath(root)
for file in files:
if file.endswith('Cog.py') and file != '__init__.py':
module_name = file[:-3]
module_path = f"cog_extensions.{os.path.relpath(root, 'cog_extensions').replace(os.sep, '.')}.{module_name}"
try:
await self.load_extension(module_path)
print(f"\n[{module_name}]( now loaded.)")
except Exception as e:
print(f"\n[{module_name}]( failed to load: {e}")
await asyncio.sleep(0.1)
i have these. commands for the cogs and then a for loop to autoload each.
Hm, not sure. You may need to ask someone more experienced with DBs.
as an event in on_ready
no you shouldn't load extensions in on_ready
load them in setup_hook instead
wouldn't this error? await self.bot.load_extension(module)
if it's not passed?
yeah cause it gives me AttributeError: 'MyBot' object has no attribute 'bot'
then how would I get rid of these traceback issues?
https://paste.pythondiscord.com/ixebuyifes
you're doing change_presence before your bot has started
pass activity and status to super().__init__ instead
won't they need to be awaited? i put them in the hook?
no.. that's not what i said
so... to use it.. How would that go in the init? cause the init is syncronous. I'd have to await it right?
no you don't use change_presence
creating an instance of a class is not asynchronous
and that's all you need to do
super().__init__(
...,
activity=discord.Game("..."),
status=discord.Status.dnd,
)
like i made a function for the change presence and put that in the on_ready originally.
async def set_profile(self):
activity = (discord.Streaming(
...
)
)
await self.change_presence(activity=activity)
ohhh.. ok.
so define it prior
activity = (discord.Streaming(
...
)
)
super().__init__(
...,
activity=activity,
)
then passing into the super would just initialize it when the bot starts.
ok. awesome. that solves that... now i just need to go back to figuring out why my cog for slash commands errors 'TestSlashCommands' object has no attribute 'http'
you don't need to
just define discord.Streaming inline
and you don't need the extra paranthesis around it
state = self._connection
if state._activity is not None or state._status is not None:
payload["d"]["presence"] = {
"status": state._dnd,
"game": state._activity,
"since": 0,
"afk": False,
}``` am i doing something wrong w/ the status?
what
why are you accessing _connection 
my friend did this not me
import json # For json
from pathlib import Path # For paths
import discord # For discord
from discord.gateway import DiscordWebSocket # For Discord Mobile
from utils.data import Bot # This loads the cogs
import logging # Shows important information of something goes wrong in the connection
cwd = Path(__file__).parents[0]
cwd = str(cwd)
print(f'-----')
async def identify(self):
payload = {
"op": self.IDENTIFY,
"d": {
"token": self.token,
"properties": {
"$os": "Discord iOS",
"$browser": "Discord iOS",
"$device": "iOS",
"$referrer": "",
"$referring_domain": "",
},
"compress": True,
"large_threshold": 250,
},
}
if self.shard_id is not None and self.shard_count is not None:
payload["d"]["shard"] = [self.shard_id, self.shard_count]
state = self._connection
if state._activity is not None or state._status is not None:
payload["d"]["presence"] = {
"status": state._dnd,
"game": state._activity,
"since": 0,
"afk": False,
}
if state._intents is not None:
payload["d"]["intents"] = state._intents.value
await self.call_hooks(
"before_identify", self.shard_id, initial=self._initial_identify
)
await self.send_as_json(payload)
DiscordWebSocket.identify = identify
bot = Bot(
intents=discord.Intents.all(),
command_prefix=',',
case_insensitive=True,
owner_id=924820612545916948
)
logging.basicConfig(level=logging.INFO)
config_file = json.load(open(cwd + '/config/config.json'))
bot.config_token = config_file['token']
@bot.event
async def on_ready():
print(f"-----\nlogged in as: {bot.user} : {bot.user.id}\n-----")
@bot.listen()
async def on_message(msg):
if "@crisp sail" in msg.content:
await msg.channel.send('my prefix is `,`')
bot.run(bot.config_token, reconnect=True)```
@app_commands.describe(
amount="The amount of messages to clear."
)
@app_commands.checks.has_permissions(manage_messages=True)
@app_commands.command()
async def clear(self, interaction: discord.Interaction, amount: int) -> None:
await interaction.response.defer(thinking=True)
cleared = await interaction.channel.purge(limit=amount, bulk=True)
clearembed=discord.Embed(
title="",
description=f"Successfully cleared {cleared} message(s).",
color=0x313338
)
await interaction.response.send_message(embed=clearembed)```
How I make worky
it already works
what is the issue with my code
!d discord.Interaction.followup
Returns the follow up webhook for follow up interactions.
skidded
hi
who are you
do you think its a reincarnation of bozo
it is definitely kai
oh yes 100%
so this is my ban command, and i cant use it somehow
here's the traceback that i got
2023-05-08 14:04:29 ERROR discord.ext.commands.bot Ignoring exception in command ban
Traceback (most recent call last):
File "C:\Users\user123\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\user123\Desktop\Akairo Project\bot.py", line 39, in ban
await member.ban(reason=reason)
File "C:\Users\user123\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\member.py", line 736, in ban
await self.guild.ban(
File "C:\Users\user123\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\guild.py", line 3467, in ban
await self._state.http.ban(user.id, self.id, delete_message_seconds, reason=reason)
File "C:\Users\user123\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\http.py", line 738, in request
raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\User123\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\User123\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\User123\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: Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
you should be using these checks instead:
@commands.bot_has_permissions(ban_members=True)
@commands.has_permissions(ban_members=True)
also make sure this is true before banning the user:
if (
ctx.author.top_role > member.top_role
and ctx.guild.me.top_role > member.top_role
):
alrighty thankss
you forgot to add directx support
Do we really have to use bot instead of client and commands when using dotenv?
nooo
When i try to do it the code needed str i went on several tutorials but nothing what am i doing wrong?
no lmao
dotenv just loads your token in a file
message.attachments
ĐОн
This is a soft ban right?
my code is returning an error "discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions"
This is the code
Error says it all
Missing Permissions
how do u turn on permission
i have turned on almost everything in server
One of the great things about creating communities on Discord is our permission system! In this Help Center article, you'll learn more about permissions, how to create and customize permissions bas...
Thank you sm bro i was sending the command in the wrong channel i just noticed it.
Still looks like a #databases issue
Hello bot tamers, is there any way to extract the user's timezone from the interaction? I've seen something about locale but it's no use. I need this for a event scheduler and I currently do time management relative to the server's timezone by specifying to the user the timezone needed. I would like to have access to the user's timezone, so the setup is relative their time.
Thanks
Could I use it in a list?
Yes?
!d discord.Message.attachments
A list of attachments given to a 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.
why does all of my kick, ban, and unban command doesn't work?
here's my code
so this is my ban command, and i cant use it somehow
Image
here's the traceback that i got
2023-05-08 14:04:29 ERROR discord.ext.commands.bot Ignoring exception in command ban
Traceback (most recent call last):
File "C:\Users\user123\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\user123\Desktop\Akairo Project\bot.py", line 39, in ban
await member.ban(reason=reason)
File "C:\Users\user123\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\member.py", line 736, in ban
await self.guild.ban(
File "C:\Users\user123\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\guild.py", line 3467, in ban
await self._state.http.ban(user.id, self.id, delete_message_seconds, reason=reason)
File "C:\Users\user123\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\http.py", line 738, in request
raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\User123\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\User123\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\User123\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: Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
it litrally tells you Missing Permissions
how do u fix it
give bot the desired permissions
i gave the bot all the ban and kick permission
Is the bot a high role?
i tried giving it the administrator perm but still it doesn't work
yeah
its role is already on top of all roles
Check your intents in client setup
Default can't ban or kick if I remember correctly
how can i delete images using this
alr imma check it rq
!d discord.Message.remove_attachments
await remove_attachments(*attachments)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Removes attachments from the message.
New in version 2.0.
You give the attachments to delete
await message.remove_attachments(...)
Where ... are the attachments to delete
but donât it need to detect attachments first
Then do it.
Think
Most of the time coding is about thinking about not being given the answer to every question and getting spoonfed
Try things, fail, try again
ok
how do you make a !warn command?
well you need a database
for warning yeah\
warn command aint need a db
how does it store warns
oh for that
If you're planning on storing the warns, then yes
oh welp
I don't recommend using discord.Intents.all() as it can throw errors sometimes, start with default() and build upon it as necessary. In your case, if I understood your bot's scope correctly, you might want to start with this:
intents.bans= True
intents.moderation= True```
intents are not permissions
Intents are not about errors
ik
oh
And using .all() is most of the time absolutely useless and will consume more resources for nothing
Haven't seen any bot that requires all intents to be abled at all
default already has all intents enabled without 3 ones needed to be enabled on the dev site
https://github.com/Rapptz/discord.py/blob/master/discord/flags.py#L727-L736
thats what it does in source code
discord/flags.py lines 727 to 736
@classmethod
def default(cls: Type[Intents]) -> Intents:
"""A factory method that creates a :class:`âIntents`â with everything enabled
except :attr:`âpresences`â, :attr:`âmembers`â, and :attr:`âmessage_content`â.
"""
self = cls.all()
self.presences = False
self.members = False
self.message_content = False
return self```
for fetching messages and guild data for role reacts, what function would I need to use in a slash command?
i have this for my code
@commands.hybrid_group(with_app_command=True)
async def test(self, ctx: commands.Context):
await ctx.reply('test group')
@test.command(with_app_command=True)
async def hello(self, ctx: commands.Context):
await ctx.reply('test hello command')
``` i use await self.tree.sync() in the setup hook but /test doesnt show only /test hello
That's how slash commands work
how do i get the test command then
no need to be rude
I just told you that it's how slash commands work before
Can't do magic and say that now it's no longer how they work 
dpy should allow you to specify a fallback command name which implicitly adds another subcommand used to invoke your parent command
https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.HybridGroup.fallback
the reason it exists is for what krypton said, discord doesn't perceive the root command as one you can use
https://discord.com/developers/docs/interactions/application-commands#subcommands-and-subcommand-groups
Using subcommands or subcommand groups will make your base command unusable. You can't send the base
/permissionscommand as a valid command if you also have/permissions add | removeas subcommands or subcommand groups
ok
Why my bot are not registering commands in a cog?
perhaps you aren't adding the cogs
yes i do
this is the python server
jesus christ man
consider learning a language inside of just copy pasting from the internet
it will be much faster and much more worthwhile
lmaoooo
this a different level already
you should update this graph now #1076673191143034911 message
as of today it's negative
nice simile
I am trying to set autocomplete to show first few items from a list if the user didn't input anything and using this code
if len(current) == 0:
return [Choice(name=l, value=l) for l in name_list][::3]
but it always show 10 choices for some reason
how many names are in name_list?
like a hundred
why not slice name_list instead of making a new list and then slicing that?
what are you expecting [::3] to do?
wdym the attachments cant i put nothing in there?
how do i detect the messages
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.message_content = True
client = commands.Bot(command_prefix = '/', intents=intents)
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
@client.command()
async def test(ctx):
await ctx.send('test')
client.run('')```
hi could someone please explain to me why when i type /test the discord autocompleting thingy doesnt appear?
cause those what you are talking about are slash commands not prefixed commands
example how to create slash command
ty
im getting this error when im trying to sync my slash commands.?
AttributeError: 'TestSlashCommands' object has no attribute 'client'
await self.bot.tree.sync()
this is in a cog btw^
did you set self.bot to bot? in __init__?
yup.
class TestSlashCommands(commands.Cog):
def __init__(self, bot: commands.Bot) -> None:
self.bot = bot
super().__init__()
show code then
class TestSlashCommands(commands.Cog):
def __init__(self, bot: commands.Bot) -> None:
self.bot = bot
super().__init__()
@app_commands.command(name='test', description='Test command')
@app_commands.describe(arg1='Test')
async def test(self, interaction: discord.Interaction, arg1: Optional[str]) -> None:
await self.bot.tree.sync()
if arg1 is not None:
await interaction.response.send_message(f'Test command with arg1 {arg1}')
else:
await interaction.response.send_message('Test command')
@commands.command(name='sync', description='Sync the commands')
async def sync(self, ctx: commands.Context) -> None:
await self.bot.tree.sync()
await ctx.send(f'{self.bot.latency}Synced!')
tried it in the slash command and in a normal command. i get the same error. :/
can you show full traceback?
AttributeError: 'TestSlashCommands' object has no attribute 'client'
ERROR - discord.app_commands.tree : Ignoring exception in command 'test'
Traceback (most recent call last):
File "E:\!python\Kirakota\.venv\lib\site-packages\discord\app_commands\commands.py", line 841, in _do_call
return await self._callback(self.binding, interaction, **params) # type: ignore
File "E:\!python\Kirakota\cog_extensions\commands\slashcommandCog.py", line 184, in test
await interaction.response.send_message('Test command')
File "E:\!python\Kirakota\.venv\lib\site-packages\discord\interactions.py", line 778, in send_message
doesnt look like full error traceback tho
try removing the super().__init__()
ERROR - discord.ext.commands.bot : Ignoring exception in command None
discord.ext.commands.errors.CommandNotFound: Command "sync" is not found
ERROR - discord.app_commands.tree : Ignoring exception in command 'test'
Traceback (most recent call last):
File "E:\!python\Kirakota\.venv\lib\site-packages\discord\app_commands\commands.py", line 841, in _do_call
return await self._callback(self.binding, interaction, **params) # type: ignore
File "E:\!python\Kirakota\cog_extensions\commands\slashcommandCog.py", line 179, in test
await interaction.response.send_message('Test command')
File "E:\!python\Kirakota\.venv\lib\site-packages\discord\interactions.py", line 778, in send_message
await adapter.create_interaction_response(
File "E:\!python\Kirakota\.venv\lib\site-packages\discord\webhook\async_.py", line 219, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "E:\!python\Kirakota\.venv\lib\site-packages\discord\app_commands\tree.py", line 1248, in _call
await command._invoke_with_namespace(interaction, namespace)
File "E:\!python\Kirakota\.venv\lib\site-packages\discord\app_commands\commands.py", line 867, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "E:\!python\Kirakota\.venv\lib\site-packages\discord\app_commands\commands.py", line 860, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'test' raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction
this the error you were looking for @slate swan
looks like other error
do you load the cog?
it autoloads
i've reloaded the bot several times, i went through and got the slash command to work yesterday, but no luck getting the sync tree to.
Im trying to count all my commands but print(len(bot.commands)) only counts the commands that dont use / (im using nextcord)
What do you mean by commands that dont use
it only counts commands that arent slash commands
you use discord.Client or commands.Bot ?
That should be correct
it counts @bot.command() but not @bot.slash_command()
!d nextcord.ext.commands.Bot.get_all_application_commands
get_all_application_commands()```
Returns a copied set of all added `BaseApplicationCommand` objects.
commands.Bot
this is my class for my main.py
class MyBot(commands.Bot):
def __init__(self) -> None:
super().__init__(
intents=discord.Intents.all(),
command_prefix="!",
activity=activity,
# ...
)
that gets me 0
print(len(bot.get_application_commands()))
get_**all_**application_commands()
what would i do to get the subcommands? Because it just shows the main things and i split my commands into subcommands
no idea tbh
you may want to ask at nextcord server discord.gg/nextcord
except modifying source code i dont think so
why is it taking you longer than a minute to connect to the gateway?
oh alright
yeah but sometimes cuz my internet is slow
you know you have to send heartbeats to the gateway to keep the connection alive
how are you going to do that?
if your internet takes any longer than 45 seconds-ish to send a packet you unfortunately will not be able to use the discord API
hey.. i need help
i want to create an event when a member join to the server but don't work
@client.event
async def on_member_join(member, ctx):
channel = client.get_channel(1105137318253301770) # welcome channel id
message = f'Welcome to the Tree House, {member.mention}!'
unverified_role = ctx.member.guild.get_role(
1105137365095288884) # unverified role id
await member.add_roles(unverified_role)
await channel.send(message)
message not send and role not applied
have you enabled member intents?
yeah and this in my code
intents = discord.Intents.default()
intents.message_content = True
you haven't enabled member intents
thanks
i want a bot to run a function that returns a variable constantly, and then send the variable in a channel if its not empty, but i cant get it to work
does anyone know how to do this?
!d discord.ext.tasks.loop
@discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
trying to use the discord api to retrieve all the reactions from a specific message but im not sure how so im trying to do it with a bot. and i get this error
2023-05-08 20:29:21 WARNING discord.state Member list scraping failed for 1085055846301573152 (Failed to automatically choose channels; please specify them manually).
heres my code py message = bot.get_channel(channel_id).fetch_message(message_id) for reaction in message.reactions: print(reaction)
A bot? Why would it need to scrape a member list
Sounds more like selfbot things
im not trying to scrape a member list lmao
thats why im confused
just tryna recieve a list of reactions
You sure?
100% lol
@app_commands.describe(message="Type your text here to send the announcement !")
@commands.has_permissions(manage_messages=True)
async def say(interaction: discord.Interaction, message: str, tag: str):
await interaction.message.delete()
await interaction.send(f'{tag}')
embed = discord.Embed(
title='ĐОвО ĐĄŃОйŃонио ⢠MetaverceCraft',
colour= discord.Colour.dark_purple()
)
image_path = os.path.abspath("static.png")
embed.set_thumbnail(url=f"attachment://{os.path.basename(image_path)}")
embed.add_field(name=f' **{message}** ', value='')
embed.set_footer(text=f'{datetime.datetime.now()}')
await interaction.send(embed=embed, file=discord.File(image_path))``` how to make slash commands
how can i add a view with two buttons to send?
thanks 
how to add slash command cooldown and ctx.respond for this cooldown
like i set 60s cooldown for command and i used it 2 times in 30s, i want to receive an error
Define error handler and handle CommandOnTimeout exception or smth like that
!d discord.app_commands.CommandOnCooldown
exception discord.app_commands.CommandOnCooldown(cooldown, retry_after)```
An exception raised when the command being invoked is on cooldown.
This inherits from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CheckFailure "discord.app_commands.CheckFailure").
New in version 2.0.
!d discord.app_commands.checks.cooldown
@discord.app_commands.checks.cooldown(rate, per, *, key=...)```
A decorator that adds a cooldown to a command.
A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns are based off of the `key` function provided. If a `key` is not provided then it defaults to a user-level cooldown. The `key` function must take a single parameter, the [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction") and return a value that is used as a key to the internal cooldown mapping.
The `key` function can optionally be a coroutine.
If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandOnCooldown "discord.app_commands.CommandOnCooldown") is raised to the error handlers.
Examples
Setting a one per 5 seconds per member cooldown on a command:
@tall temple
thanks
Hello! I'm using discord.ui.View and select I want to know how I can create a ticket system that the user presses a Open ticket button then a drop down menu shows what the ticket reason is for
is this possible?
anyone>
import discord
from discord import app_commands, utils
id = discord.Object(id=1092591199300370473)
class ticket_launcher(discord.ui.View):
def __init__(self) -> None:
super().__init__(timeout = None)
@discord.ui.button(label="Create a Ticket", style= discord.ButtonStyle.blurple, custom_id='openTicket')
async def createticket(self, interaction: discord.Interaction, button: discord.ui.Button):
ticket = utils.get(interaction.guild.text_channels, name = f"{interaction.user.name}-{interaction.user.discriminator}-ticket")
if ticket is not None: await interaction.response.send_message(f"{interaction.user.mention}, You already have a ticket open! {ticket.mention}", ephemeral=True)
else:
overwrites = {
interaction.guild.default_role: discord.PermissionOverwrite(view_channel = False),
interaction.user: discord.PermissionOverwrite(view_channel = True, send_messages = True, attach_files = True, embed_links = True),
interaction.guild.me: discord.PermissionOverwrite(view_channel = True, send_messages = True, read_message_history = True)
}
channel = await interaction.guild.create_text_channel(name = f"{interaction.user.name}-{interaction.user.discriminator}-ticket", overwrites=overwrites, reason=f"Ticket Opened for: {interaction.user}")
await channel.send(f"{interaction.user.mention}, I have created a ticket for you!")
await interaction.response.send_message(f"I've opened a ticket for you at {channel.mention}!", ephemeral=True)
class aclient(discord.Client):
def __init__(self):
super().__init__(intents=discord.Intents.all())
self.synced = False
self.added = False
async def on_ready(self):
await self.wait_until_ready()
if not self.synced:
await tree.sync(guild=id)
self.synced = True
print("Synced")
if not self.added:
self.add_view(ticket_launcher())
self.added = True
print("Online.")
client = aclient()
tree = app_commands.CommandTree(client)
@tree.command(name="ticket", guild=id, description="Open a ticket!")
async def ticket(interaction: discord.Interaction):
embed = discord.Embed(
title="BotBean | Tickets",
description="To open a ticket, click the button below!",
color=discord.Color.green()
)
await interaction.response.send_message(embed=embed, view = ticket_launcher())
await interaction.response.send_message("Tickets set!", ephemeral=True)
client.run(f"")
``` I have the basic command working, I just want to add my drop down menu from my other bot so the user has an option of ticket type
@earnest swift
just create a select menu
and why are you creating your own command tree
Do you know how to add a image in a embed
yes
Can u help me with it
idk
??
wheres that link gone
his link was useless
that's the api reference, which won't show anything related to buttons/select menus
@eager portal which part are you having trouble with
Can someone help me add a image to my embed
merging a button with a dropdown select menu
just add it
!d discord.ui.select
@discord.ui.select(*, cls=discord.ui.select.Select[+ V], options=..., channel_types=..., placeholder=None, custom_id=..., min_values=1, max_values=1, disabled=False, row=None)```
A decorator that attaches a select menu to a component.
The function being decorated should have three parameters, `self` representing the [`discord.ui.View`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View "discord.ui.View"), the [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction") you receive and the chosen select class.
To obtain the selected values inside the callback, you can use the `values` attribute of the chosen class in the callback. The list of values will depend on the type of select menu used. View the table below for more information.
why are my overwrites not working
overwrites = {
interaction.guild.default_role: discord.PermissionOverwrite(view_channel = False),
interaction.user: discord.PermissionOverwrite(view_channel = True, send_messages = True, attach_files = True, embed_links = True),
interaction.guild.me: discord.PermissionOverwrite(view_channel = True, send_messages = True, read_message_history = True)
}
if select_item.values[0] == "support":
channel = await support.create_text_channel(name = f"{interaction.user.name}-{interaction.user.discriminator}-ticket", overwrites=overwrites, reason=f"Ticket Opened for: {interaction.user}")
anyone able to help me out
i don't know what not working means
Hey, is there an efficient way to make responses to commonly asked "questions" where the bot reads a message, and if the words "help" or "how" etc are in the sentence, it then checks the context such as "bot" or "commands" or something else and then response with some answer?
I know I can do that "if ["how"] in message.content: if ["bot"] in message.content:" and so on to get the context of the person needing help and what to specifically help with, but is there a better way of doing this?
This is just a personal project I would like to make, and if I can I want to include my own pretrained "ai" to answer since these questions could be server specific that (for example) the chatgpt couldnt answer
You can but the chances of it giving the wrong answers is pretty high considering how ambiguous the English language is
i understand that
AI LLMs like ChatGPT aim to solve this very issue, not sure how much luck you'd have with a rule-based pattern matcher
thats why I was thinking of hardcoding commonly based words for questions
like "how to enable this feature"
If you're sure you want to do it, the code itself isn't all that difficult - just a bunch of if statements that are nested
i want to avoid that tbh
usually it's atypical to do this so there's not much of an alternative
There are services like AWS Comprehend that use neural networks to extract keywords out of sentences: https://aws.amazon.com/comprehend/features/
I've used it in the past and it did it's job pretty well for what I wanted it to do
use-
embed.set_thumbail (for small image)
embed.set_image (url="url_here")
embed.set_icon (url="url")
tho that icon, one will set the image in the footer and will be really small. If you want the biggest image size then use set_image
set_icon?
oh my bad
icon_url
That's from set_author
it will be inside the footer tho
set_author(*, name, url=None, icon_url=None)```
Sets the author for the embed content.
This function returns the class instance to allow for fluent-style chaining.
yeah this one
i made a lil mistake before, sorry đ
Btw is there anything to check whether the interaction user has certain permissions or not?
!d discord.ext.commands.has_permissions
@discord.ext.commands.has_permissions(**perms)```
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 has all of the permissions necessary.
Note that this check operates on the current channel permissions, not the guild wide permissions.
The permissions passed in must be exactly like the properties shown under [`discord.Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions "discord.Permissions").
This check raises a special exception, [`MissingPermissions`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingPermissions "discord.ext.commands.MissingPermissions") that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
iirc you can use this
alright, thanks dude
you're welcome
interaction user
The Holy Interaction
every interaction descends from me
I'm trying to create a button but it's saying inconsistent use of tabs and indentations
Even though all tutorials do it like that
lmfao
u haven't coded before right?
what that means is u cant use both tabs and spaces for indentation
pick one
got it thanks
from typing import Optional
import discord
import discord
from discord.ext import commands
from discord import app_commands
from discord.ui import button, Button, View
intents = discord.Intents.all()
bot = commands.Bot(command_prefix='-', intents=intents)
@bot.event
async def on_ready():
print(f'{bot.user.name} has connected to Discord!')
try:
synced = await bot.tree.sync()
print(f"Synced {len(synced)} command(s)!")
except Exception as e:
print(f"Sync Failed! {e}")
class applybutton(View):
def __init__(self):
super().__init__(timeout=None)
@button(label="Apply", style=discord.ButtonStyle.blurple)
async def creatorapply(self, interaction: discord.Interaction, button: Button):
await interaction.response.defer(ephemeral=True)
category: discord.CategoryChannel = discord.utils.get(interaction.guild.categories, id=1105378615299948575)
for ch in category.text_channels:
if ch.topic == f"Ticket for ID:{interaction.user.id}":
await interaction.followup(f"{interaction.user.mention} You already have an active ticket!")
return
channel = await category.create_text_channel(
name=interaction.user,
topic=f"Ticket for ID:{interaction.user.id}"
)
await channel.send(
embed=discord.Embed(
title="Thanks for applying!",
description="A staff member will be with you shortly."
)
)
await interaction.followup(f"Your ticket has been created! Please head over to {channel.mention}")
@bot.command(name="creatorapply")
@commands.has_permissions(administrator=True)
async def creatorapply(ctx):
await ctx.send(
embed = discord.Embed(
title="Click to apply",
description="A ticket will open for your application"
),
view = applybutton()
)
bot.run(Token)
For some reason whenever I click the button it says interaction failed, the bot had admin perms and I do as well, and there's no errors in the terminal, does anyone know what the problem might be?
You simply did not respond to the interaction
And interaction.followup is a property, not method
Oh so then I should use like, interaction.followup.send() ?
Even after that it says interaction failed, and it doesn't create the channel or anything
show your code now
from typing import Optional
import discord
import discord
from discord.ext import commands
from discord import app_commands
from discord.ui import button, Button, View
intents = discord.Intents.all()
bot = commands.Bot(command_prefix='-', intents=intents)
@bot.event
async def on_ready():
print(f'{bot.user.name} has connected to Discord!')
try:
synced = await bot.tree.sync()
print(f"Synced {len(synced)} command(s)!")
except Exception as e:
print(f"Sync Failed! {e}")
class applybutton(View):
def __init__(self):
super().__init__(timeout=None)
@button(label="Apply", style=discord.ButtonStyle.blurple)
async def creatorapply(self, interaction: discord.Interaction, button: Button):
await interaction.response.defer(ephemeral=True)
category: discord.CategoryChannel = discord.utils.get(interaction.guild.categories, id=1105378615299948575)
for ch in category.text_channels:
if ch.topic == f"Ticket for ID:{interaction.user.id}":
await interaction.followup.send(f"{interaction.user.mention} You already have an active ticket!", ephemeral=True)
return
channel = await category.create_text_channel(
name=interaction.user,
topic=f"Ticket for ID:{interaction.user.id}"
)
await channel.send(
embed=discord.Embed(
title="Thanks for applying!",
description="A staff member will be with you shortly."
)
)
await interaction.followup.send(f"Your ticket has been created! Please head over to {channel.mention}", ephemeral=True)
@bot.command(name="creatorapply")
@commands.has_permissions(administrator=True)
async def creatorapply(ctx):
await ctx.send(
embed = discord.Embed(
title="Click to apply",
description="A ticket will open for your application"
),
view = applybutton()
)
it doesn't create the channel and no errors
name=interaction.user
probably this part
Alr let me just try a random name
channel = await category.create_text_channel(
name="name",
topic=f"Ticket for ID:{interaction.user.id}"
)
Changed it to this but same problem
Maybe add some print statements and see where the code is freezing
print statement is the best debugger
Ideally your logger should be functional but
Yeah I did and it seems that none of the button code is working
yeah
Okayy, what does that mean sorry đ
it means it doesn't keep working after your bot reloads
It's ok ur allowed to blame it on mudkip
no

Thank you guys so much!

He likes diet coke more than coke zero can you believe

I tried with a new message and that works, I'll try and figure out how to do the persistent thing now
There's an example in discord.py docs iirc
No
Normal coke is better
it's creamy đ
Not docs in GitHub
you just have to set timeout to none, make sure your elements have a custom_id and then use add_view
There is one on GitHub
it's an example though not docs
yo can i ask if where to put a bot to stop swearing and a helpful bot in one python script would it work?
nah i rather do it on my own
i rather learn to make it then using the given bots is more fun
Guys can user token be used for login in discord.py?
No, that's selfbotting which is not allowed by discord
anyone help me pls
What help do you need specifically
So you have two existing discord bots which you want to merge?
both
Are both of your bots written with discord.py?
Then that should be possible
tq so much man so i just need to change the async right?
OK TQ đ
Do using user token to login means self bot?
yes
How do I get stream permission in this server?
@vocal snow can you help at discord bot problem
Yes
fourth sorry
Can anyone help me?
You wish to stream in the voice channels?
Ask this in #community-meta , this channel is for making discord bots
Oh ok thanks
is there a way to extract a string from a message a user sent in discord using the command thingy
like( !vote "discord") i want to extract discord from this but i don't wanna use the on_message function. Is there any way for this?
Command arguments
Are u using ctx (discord.py)?
If u have ctx then, just add a variable in function. For eg -
async def abc(ctx, word:str) :
print("word")
await ctx.send("Hello")
Here the "discord" will be extracted and assigned to variable named "word" and u can do further what u like
everyone can see the channel still
im trying to make an api to interact with my discord bot, just to get how many guilds, channels & users it has, how would i start this. im using dpy
how could you setup logging such that my extension files that contain commands logs to the same file as my main bot entry file?
I added
logger = logging.getLogger(__name__)
but it doesn't log anything when I do logger.debug
that's not
idk then
and it was my main config
logger = logging.getLogger("discord")
logger.setLevel(logging.DEBUG)
handler = logging.handlers.RotatingFileHandler(
filename="./logs/discord.log",
encoding="utf-8",
maxBytes= 16 * 1024 * 1024,
backupCount=2
)
dt_fmt = '%Y-%m-%d %H:%M:%S'
handler.setFormatter(
logging.Formatter('[{asctime}] [{levelname:<8}] {name}: {message}', dt_fmt, style='{')
)
logger.addHandler(handler)
Ok thanks
Heyo, so I'm kind of copying the file structure for this servers discord bot, and there is a directory called bot and then a file in that directory called bot.py. When I try to import the bot module in my main and the bot file file, it doesn't like it because it thinks its a circular import, and it gets fixed by changing the name of the bot.py file. How does this bot avoid that issue?
Circular import errors generally indicate faulty design structure - you should extract out common components into their own modules so everything isn't importing everything else
The bot is laid out in such a way that this does not happen
Yeah, but I copied the file structure and the files exactly, with the same imports
Do you have this uploaded to a github or something I can take a look at?
Traceback (most recent call last):
File "/Users/ellalbrys/CodingProjects/Python/coconut-capitalist/bot/__main__.py", line 13, in <module>
import bot
File "/Users/ellalbrys/CodingProjects/Python/coconut-capitalist/bot/bot.py", line 7, in <module>
from bot import exts
ImportError: cannot import name 'exts' from partially initialized module 'bot' (most likely due to a circular import) (/Users/ellalbrys/CodingProjects/Python/coconut-capitalist/bot/bot.py)
Yeah, let me push the changes real quick
Wait sike, its private. Is there any way I can add you to view it?
Yeah my GitHub username is Robin5605
@sick birch also changes havent been pushed yet one sec
đ
Reason I wanted to look at the git repo is I'd like to be able to see all the files, what's importing what, and the file structure
@abstract kindle would not recommend putting your commands in __main__.py
__main.py__ should be only for creating the bot constructor and starting the event loop
https://github.com/python-discord/bot/blob/main/bot/__main__.py notice how there's no command here
Yep, that's one change I'm working on. When I was trying to copy this bot's structure, I wasn't sure how to move those commands elsewhere and still have them work
Also, the changes are on the testing branch
Yup found them
Should be in cogs. A "core" cog for instance
Ideally cogs shouldn't be importing each other
Got it. And core implies functionality that is necessary for the bot to run?
Okay. Those commands have been there since I made the bot, so it's definitely time for them to move
And what if the cogs aren't loading properly? How would I check if the "core" cog itself isn't loading?
I'm trying to switch over to the BotBase from the pydis_core library so that I can just run load_extensions in the setup_hook method, but I haven't got that all down yet
Bot core is pretty great yeah. Use it in many of my own bot projects
You'll usually be able to tell because it'll tell you something like Command "sync" is not recognized
But generally you'd also add logging to say "Extension X was loaded"
Right. I really want to get logging down. I've been using print statements for too long. I was looking at the logging library and it seems pretty self explanatory. For the different levels of logging though, would I have to setup the format and everything for each file? I know that the common logging setup is log = getLogger(__name__), but where would I define the default configuration for the logger?
Also, if I'm loading all extensions with the BotBase's load_extensions method, how would I setup debugging for that?
https://discordpy.readthedocs.io/en/stable/logging.html see here for a guide on logging
Sorry for all the questions lol, I am just so eager to learn GOOD development practices (file structure, modularizing, etc.) and I rarely get a chance to just ask away. Really appreciate it~~
Yup. People overlook that aspect of bot development all too many times and the resources are quite limited
This sort of stuff you're asking is what takes you from a mediocre developer to an advanced software engineer đ
YESSS! Good to hear
This bot has been a project for about 2 years now, and it is absolutely giving me so many skills. Project management, I'm getting somewhat good at Github, I'm learning about user feedback from my friends who use the bot, etc. Looks great on a resume.
I'm hoping to learn Docker this summer so I can stop running my bot in a minimized terminal window on my PC and so that I can streamline development from my osx laptop and my windows pc
With Docker comes a whole another field: devops
You can set up pipelines to automatically lint, test, and deploy pushes to github
I've been doing this for a few years now and it's still overwhelming at times, if that's any consolation
Definitely. Especially since I see you in here all the time helping so many different people. Still can make an impact even if you don't know everything
If I have a discord bot which makes API calls, what's the recommended way to let the functions in the different cogs in separate files access the API key?
Secrets like environment variables should be defined in an .env and loaded that way (or just exported to environment variables)
Sure I don't really see anything necessarily wrong with it
OK, it just seems a bit inefficient
You could also build a aiohttp.ClientSession subclass that automatically adds the authorization headers and base URLs and stuff for the specific API you're using, that way you don't need to worry about auth in your cogs
sure
well, in my case I'm using an API wrapper in Python, so it would be a bit different, but yeah
anyone could help with my question
this doesn't have much to do with discord bots, you'll get better and faster help regarding your question in #âď˝how-to-get-help
which function would edit any message the bot sends? if I want to put in the channel and the message id? discord.Message.edit()?
you'd need the message object and call the .edit method on it
so how would that work? lets say i pass the param message_id 1105512935746445312 with my bots message for ex. would i do something like
message = discord.Message(id=message_id) and it gets the object?
close
there's a getfetch_message method
which is a method of a channel object
so you can get a message from a specific channel by its ID
so your order of doing things would be:
- get a channel object
- get a message object from that channel object by using
getfetch_message - call the edit method on the message you just got
so i'd need to use guard clauses to figure out which channel type first for the right channel object. ok
or wait..
you could fetch a message from a user / channel / ...
!d discord.Message.channel
The TextChannel or Thread that the message was sent from. Could be a DMChannel or GroupChannel if itâs a private message.
they all have that method
Is there a method to send dm to a user through bot?
!d discord.User.send
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
looks like enabling the root logger in bot_run solves it but now my logs is filled with a bunch of other messages
from the discord api I suppose
there is a 28 day period too no?
Not sure what you mean by that
for editing or deleting a message
or was that for channel purge
28day period and then what?
like u cant delete messages more than 28 days old or something wait a sec lemme check
That wouldnât make sense tbh
Im trying to add chat gpt to my discord bot but im running into several issues, can someone take a quick look at my code ?
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 manage to get ChatGPT working outside a bot first, then Iâd move on to integrating it in your bot
hmm i think confused it with something else mb
Can i add at search_targets a description?
how do i change the style of this original help command?
define your own
Create ur own
To learn more about how to create custom help commands in discord.py by subclassing the help command, please see this tutorial by Stella#2000
so i make a new command?
look at the tutorial above its all explained
What are webhooks đ
Webhooks are a form to send messages to channels in Discord without a bot user or authentication.
from the docs ^
wait what
https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#paginator
there's a paginator
Ok, thanks a lot â¤
yeah there is
Btw is there any module or something by which I can play music just by link or searching, in premium like sound quality
yeah
use discord.py[voice] iirc
Thank u :D
python3 -m pip install -U discord.py[voice]
Thanks buddy
Much appreciated
np
is chat gpt API key free to use in a discord bot?
It's getting highlighted, I just want red font
according to that, it shouldn't highlight unless I add another value using ;
[0;31mSolid
you cant use bold looks like
when you do normal format it works
@honest shoal ^
hello, how would I send a message to a channel at a particular time everyday? I've tried a few things using @tasks.loop but I haven't found a solution yet
A cron job with a webhook
Can't you just use tasks and set a time for the next iteration and then change the interval to the next date once it get executed
E.g. initialize the task with the date and time to run set to tomorrow at 6pm
then once the task gets executed, change the interval and set the next date and time to run the day after tomorrow at 6pm
There's a free trial for 3 months ig which is like 18$ worth. After that u need to pay
im trying to make an api to interact with my discord bot, just to get how many guilds, channels & users it has, how would i start this. im using dpy
how to get guild id by server name in bot joined servers pls ?
anyhelp the everyone role can still see the channel
trying to use the embed.add_field(name='',value=self.value)
if I want the data to show
compact like this
whats the best
method...?
right now...
it sends like this :/
for key, value in insert_list:
self.value += f"> {key}\n"
If the time can be hardcoded there's even time kwarg
Does the time need to be hardcoded or bot users can set it
cant you do ```py
for key, value in insert_list:
embed.add_field(name=name, value=value, inline=True/False)
.
overwrites = {
interaction.guild.default_role: discord.PermissionOverwrite(view_channel = False),
interaction.user: discord.PermissionOverwrite(view_channel = True, send_messages = True, attach_files = True, embed_links = True),
interaction.guild.me: discord.PermissionOverwrite(view_channel = True, send_messages = True, read_message_history = True)
}
if select_item.values[0] == "support":
channel = await support.create_text_channel(name = f"{interaction.user.name}-{interaction.user.discriminator}-ticket", overwrites=overwrites, reason=f"Ticket Opened for: {interaction.user}")
``` Any one help, default role can still see new channel
Iterate over servers and compare names ig? Even if there's a builtin function for that its principle shouldn't differ much
okay
could I employ someone to take a look at this slash command and traceback please? https://discord.com/channels/267624335836053506/1105595418663981087
that's what i thinked about but i thought there is simpler method :/
hardcoded. i believe ive managed to figure something out though
Done đ
super
both methods. yours and mine currently return something like this... instead of compact results like this ...