#discord-bots
1 messages · Page 207 of 1
maybe add print() statements after every await and all to see if the code is working or not
also ig it should just be ticket not ticket- cause - is just a visual component added by discord instead of spaces
What do you want options to be?
Ah okay now i understood what is the point of this command
You could make argument options and accept different options separated by comma or so
Then split it in code
class signup(Modal, title="Sign Up"):
username = TextInput(label="Enter Your New Username .", style=discord.TextStyle.short, required=True)
password = TextInput(label="Enter Your Password .", style=discord.TextStyle.short, required=True)
async def on_submit(self, interaction: discord.Interaction):
username = self.children[0]
print(username)
password = self.children[1]
print(password)
if username in db["userreg"]:
button1 = Button(label="Try Again.", style=discord.ButtonStyle.blurple)
async def buttonSign_callback(interaction):
if interaction.user.id!=interaction.author.id:
return
else:
res=await interaction.response.send_modal(signup())
view = View(timeout=60)
view.add_item(button1)
await interaction.response.send_message(title="Sign Up.",description=f"This Username `{self.children[0]} already exists.`",view=view)
else:
dt = {"id": str(interaction.user.id),
"password":password,
}
db["userreg"].append(username)
db[f"{username} i"]= dt
print(db[f"{username} i"])
em=discord.Embed(title="Sign Up.",description="Success.")
await interaction.response.send_message(embed=em)
#reg(dt,username)
return True```
Traceback (most recent call last): File "/home/runner/ShinyPastAssembly/venv/lib/python3.10/site-packages/discord/ui/modal.py", line 187, in _scheduled_task await self.on_submit(interaction) File "main.py", line 41, in on_submit db["userreg"].append(username) File "/nix/store/hd4cc9rh83j291r5539hkf6qd8lgiikb-python3-3.10.8/lib/python3.10/_collections_abc.py", line 1123, in append self.insert(len(self), value) File "/home/runner/ShinyPastAssembly/venv/lib/python3.10/site-packages/replit/database/database.py", line 286, in insert self.on_mutate() File "/home/runner/ShinyPastAssembly/venv/lib/python3.10/site-packages/replit/database/database.py", line 256, in on_mutate self._on_mutate_handler(self.value) File "/home/runner/ShinyPastAssembly/venv/lib/python3.10/site-packages/replit/database/database.py", line 373, in cb db[k] = val File "/home/runner/ShinyPastAssembly/venv/lib/python3.10/site-packages/replit/database/database.py", line 491, in __setitem__ self.set(key, value) File "/home/runner/ShinyPastAssembly/venv/lib/python3.10/site-packages/replit/database/database.py", line 500, in set self.set_raw(key, _dumps(value)) File "/home/runner/ShinyPastAssembly/venv/lib/python3.10/site-packages/replit/database/database.py", line 56, in dumps return json.dumps(val, separators=(",", ":"), cls=DBJSONEncoder) File "/nix/store/hd4cc9rh83j291r5539hkf6qd8lgiikb-python3-3.10.8/lib/python3.10/json/__init__.py", line 238, in dumps **kw).encode(obj) File "/nix/store/hd4cc9rh83j291r5539hkf6qd8lgiikb-python3-3.10.8/lib/python3.10/json/encoder.py", line 199, in encode chunks = self.iterencode(o, _one_shot=True) File "/nix/store/hd4cc9rh83j291r5539hkf6qd8lgiikb-python3-3.10.8/lib/python3.10/json/encoder.py", line 257, in iterencode return _iterencode(o, 0) ValueError: Circular reference detected
help pls
input()``````py
input(prompt)```
If the *prompt* argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, [`EOFError`](https://docs.python.org/3/library/exceptions.html#EOFError "EOFError") is raised. Example:
```py
>>> s = input('--> ')
--> Monty Python's Flying Circus
>>> s
"Monty Python's Flying Circus"
``` If the [`readline`](https://docs.python.org/3/library/readline.html#module-readline "readline: GNU readline support for Python. (Unix)") module was loaded, then [`input()`](https://docs.python.org/3/library/functions.html#input "input") will use it to provide elaborate line editing and history features.
Raises an [auditing event](https://docs.python.org/3/library/sys.html#auditing) `builtins.input` with argument `prompt` before reading input...
soooooooooooo
This function returns the input as string, so just convert it to int
i am i just learned the for thingy and the assignment my teacher gave me i just cant understand it
this is what she told me to do:
The Israel Trail is a long walking route divided into 44 sections. Each section has a name.
Write a program that will record the name and length of each of the 44 sections. The program will print the names
The sections that are longer than 10 km. Also, the program will calculate the total length of the Israel Trail and print
This number.
Can I make a parameter accept a file?
idk where the problem, it says indentation Error: outer level in line 39 how to fix it?
format the code
how can i create a bot that sends twitch notifications when a live starts?
best way to check errors
embed = discord.Embed(
title = "This is a title",
description = "Lorem ipsum dolor sit amet"
)
await ctx.send(
ctx.author.mention,
embed = embed
)
``` for example
I think you could do smt with that, but instead of sending it on message send it when the stream starts
https://twitchio.dev/en/latest/
help
This means that ctx.message is None
class discord.Interaction```
Represents a Discord interaction.
An interaction happens when a user does an action that needs to be notified. Current examples are slash commands and components.
New in version 2.0.
can you edit it?
Yes, but I won't
damn alr
#bot.py
import os
import discord
from discord import utils
from dotenv import load_dotenv
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
SERVER_ID = 1079627037163147294
CATEGORY_ID = 1079870065488441464
intents = discord.Intents().all()
client = discord.Client(intents=intents, partials=["CHANNEL"])
channels = {}
@client.event
async def on_ready():
print(f'{client.user} has connected to Discord')
@client.event
async def on_message(message):
server = client.get_guild(SERVER_ID)
category = server.get_channel(CATEGORY_ID)
if isinstance(message.channel, discord.DMChannel) and message.author != client.user:
print(message.content)
channel_name = f"{message.author.name}".lower().replace(" ", "-")
embed = discord.Embed(
title = f"Message from {message.author.name}({message.author.id})",
description = message.content,
timestamp = message.created_at,
color = 0x00ff00
)
existing_channel = utils.get(category.channels, name=channel_name)
if existing_channel:
print(client.get_channel(existing_channel.id))
await client.get_channel(existing_channel.id).send(embed=embed)
# f"{message.author}:{message.content}"
else:
overwrites = {
server.default_role: discord.PermissionOverwrite(read_messages=False),
server.me: discord.PermissionOverwrite(read_messages=True)
}
# Insert DM channel into channels dictionary
channels[channel_name] = message.channel
channel = await category.create_text_channel(channel_name, overwrites = overwrites)
await channel.send(embed=embed)
elif message.author.id == server.owner.id:
print(channels)
for x in channels.keys():
if message.channel.name == x:
print(message.channel)
await channels[x].send(f"{message.content}")
client.run(TOKEN, bot = False)
This is my code, whenever I run this code, I can see errors:
!code
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
we don't help with discord self bots
is music bot break laws?
hi all
quick question. I made a "local" software with python and tkinter. And I also made a discord bot.
I would like to try to add discord login to my local app, so that I can then connect it to my discord bot
so that eventually I can type something in discord, and this software does an action
is anyone here available to help?
As long as it's youtube
Or any platform that doesn't allow it, really
If you're using an official API to stream the music then it's allowed, I guess
hola
await setup(self)
TypeError: object NoneType can't be used in 'await' expression
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\grand\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "E:\My_stuff\Discord bots\everything bot prod\bot.py", line 62, in on_ready
await bot.load_extension("cogs.fun")
File "C:\Users\grand\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 1013, in load_extension
await self._load_from_module_spec(spec, name)
File "C:\Users\grand\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 952, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.fun' raised an error: TypeError: object NoneType can't be used in 'await' expression```
what did i do wrong?
can u explain the thing?
explain what i'm using cogs and I am updating my bot to 2.0 from 1.7.3 and I did this before and it worked
but now it not working
as stated in the last line of the error, TypeError: object NoneType can't be used in 'await' expression
i have all those cogs so idk where the nonetype is from
are all of them each commands?
not all of them there are some defs
without a @command.commands on it
bot.load_extension can only load commands
then why did it load my entire cog before using that
There's another way u can load
using os and asyncio
create a function
it wasn't this hard before
u cant load on_ready as it will sometime ratelimit your bot 💀
how how should i load then because i just tossed those in the bottom of the file and they got loaded
without an on_ready even
!d discord.ext.commands.Bot.load_extension
await load_extension(name, *, package=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Loads an extension.
An extension is a python module that contains commands, cogs, or listeners.
An extension must have a global function, `setup` defined as the entry point on what to do when the extension is loaded. This entry point must have a single argument, the `bot`.
Changed in version 2.0: This method is now a [coroutine](https://docs.python.org/3/glossary.html#term-coroutine "(in Python v3.11)").
what do you have in your main py
the main photo i sent
u need to make a function
by doing what
definition of bot?
anything reguarding the bot in the file instead of client
async def main():
for filename in os.listdir('./cogs'): #import os
if filename.endswith('.py'):
await bot.load_extension(f'cogs.{filename[:-3]}')
await bot.start('token')
asyncio.run(main()) #import asyncio```
that will load
send the code where you define bot varriable
i've used it before and it wasn't libable
but it does load for me
u need to send us the definition of the bot then
well it isn't bot in the cogs just the main file
this error would suggest you're still running the older version of discord.py
thats the point
trying to get it updated
we are asking for the main file
pip install --upgrade discord.py
pip install -U discord
gotta update the code to make it work on the newest version
u always need to be up-to-date
well when you havent touched it in a bit it is out of date man
sure, but that error specifically you showed earlier is the result of not updating discord.py to 2.0 when you ran the code
there's nothing we can do
!paste
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
in other words your on_ready is "suitably written" for discord.py 2.0, you're just not using 2.0
well i guess its 2.2 now
I was using 1.7.3 at one point
still getting the same nonetype error on load_extension?
might want to try reinstalling it, i.e. pip install --force-reinstall discord.py
oh hold on that error isnt* load_extension itself
oops, the actual error is that your setup() method isnt asynchronous
once you said that i knew what you ment that makes so much more sense
that would make sense why it didn't work
thanks
im using nextcord and it isnt like this there its something new in discordpy?
that setup has to be async function
iirc discord.py introduced it after they went back into development, hence why most of the forks dont do the same thing
Idk if this is answered yet or not, but why dont you just do this :
await interaction.response.send_message(content=f'Deleted **{amount}** messages with the reason: {reason}')```
and ig try removing len
I just changed and it worked but why does the bot take times to delete msgs
ig it depends on ur Bot's resources
how do I fasten it
Get better resources ?
huh
i mean honestly i never faced such issue(s), so i dont have much info about them
bulk message deletion has been slow for a while i think, even right now it still takes several seconds and a whole lot longer for it to actually be deleted (my messages below should have disappeared)
other people seem to be reporting the same issue discord/discord-api-docs#5974
what happens if you try to fetch these messages that should've been deleted? Do the Api returns a 404 or a 200?
👍
real quick question, with discord.py, does cog_unload run automatically when the bot loading it stops existing, i.e. at the end of execution?
Iirc cogs are unloaded when the Client.close() method is called so yeah
commands.Bot.close() to be precise
It was like at the same time
hi all
I'm pretty depressed lol. yesterday I was doing pretty well, today every single tutorial I watch feels like aramaic
Why does my button fail after 10 mins or so?
aah i see, thanks!
@commands.command(
name='inrole',
aliases=['members'],
usage='inrole',
description=''
)
async def inrole(self, ctx, *, role: discord.Role):
"""View the users in a role"""
await ctx.typing()
embeds = []
ret = []
num = 0
pagenum = 0
for m in ctx.guild.members:
if m in role.members:
num += 1
ret.append(f'**{num}.** {m.mention} ({m.id})')
pages = [p for p in discord.utils.as_chunks(ret, 10)]
for page in pages:
pagenum += 1
embeds.append(discord.Embed(
color=color,
title=f'Members with {role.name}',
description="\n".join(page))
.set_author(name=ctx.author.display_name, icon_url=ctx.author.display_avatar)
.set_footer(text=f'Page {pagenum}/{len(pages)}')
)
if len(embeds) == 1:
return await ctx.send(embed=embeds[0])
else:
pag = Paginator(self.bot, embeds, ctx, invoker=ctx.author.id)
pag.add_button('prev', emoji='')
pag.add_button('goto', emoji='')
pag.add_button('next', emoji='')
pag.add_button('delete', emoji='')
await pag.start()
Anyone got an idea why this wont work?
It's not putting the paginator when the embeds are more than 1
Hey @twilit veldt!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
Pleaseee Help me.. The Error, dont go away.. Here is the code, and the error:
Error:
2023-03-03 18:18:42 ERROR discord.ext.commands.bot Ignoring exception in command setchannel
Traceback (most recent call last):
File "C:\Users\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\core.py", line 229, in wrapped
ret = await coro(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "d:\Python Scripts\countingbot.py", line 111, in setchannel
data = json.load(f)
^^^^^^^^^^^^
File "C:\AppData\Local\Programs\Python\Python311\Lib\json_init_.py", line 293, in load
return loads(fp.read(),
^^^^^^^^^^^^^^^^
File "C:\Users\AppData\Local\Programs\Python\Python311\Lib\json_init_.py", line 346, in loads
return _default_decoder.decode(s)
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\AppData\Local\Programs\Python\Python311\Lib\json\decoder.py", line 340, in decode
raise JSONDecodeError("Extra data", s, end)
json.decoder.JSONDecodeError: Extra data: line 1 column 14 (char 13)
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\bot.py", line 1350, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\core.py", line 1023, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\AppData\Local\Programs\Python\Python311\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: JSONDecodeError: Extra data: line 1 column 14 (char 13)
Code (Pastebin)
JSONDecodeError: Extra data means the file had a properly formatted value, but there was more data beyond said value
in your case its most likely because you're using f.seek(0) to try overwriting the file but forgetting to truncate the existing data
id suggest just opening the file twice, once to read and once to write ```py
with open("file") as f:
data = json.load(f)
with open("file", "w") as f:
json.dump(data, f)```
does your view have a timeout? and are you adding it back to the bot when it restarts?
Where exactly, do I need to paste it into the code?
adding it back ??
Wdym
I changed the timeout to None
well i should ask first if you want your view to still work after a restart
Yeah
then on bot startup, you need to add the view instance using Client.add_view()
dont paste my example, just correct your current usages of r+ so they follow the pattern i described
Huh... whats the difference between that and ctx.send(view=view)?
In addition, wouldnt the information be lost once the bot restarts so how can you save it?
well send() sends a message, but add_view() is simply informing discord.py that there's a view that it should be receiving interactions from
Okay, I will test it.. I write again, if it not works..!
I don't understand it.. Wherever it would make sense to insert it, or to replace it, errors come -.-
Someone know how can i make my bot read another bots messages?
like as their messages are sent? assuming this is in relation to the discord.py library, you'd use the on_message event and check that the author is from that bot
https://discordpy.readthedocs.io/en/stable/quickstart.html
do you understand what your code needs to do to properly update the file?
Not really 
I mean, its like a bot sends a message, not mine, and I would like to make my bot read this message that the other bot sent is it that possible? if yes how can i make it?
if your view doesnt have any kind of dynamic data required during initialization then adding the view is fairly easy, e.g. ```py
class MyView(discord.ui.View):
@discord.ui.button(label="Hello world!", custom_id="hello-world")
async def on_click(self, interaction, button):
await interaction.response.send_message("Hello world!")
client = discord.Client(...)
client.add_view(MyView(timeout=None))
client.run(...)``` but when your view needs more information like the original user's ID, its up to you to choose how to store that data and retrieve it, for example inserting into a database and then retrieving it on startup to re-create the view instance
exactly how i described, the on_message event is fired for every message the bot can see so you just need to figure out if the author of the message is the bot you're interested in
can i send what ive coded?
!paste and make sure you dont show your token
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.
ok so basiclly i would make a helper bot for another bot that me and friends play, so this what i've wroted: https://paste.pythondiscord.com/ozoziwebug, but the problem is that my bot are not reading messages properly, it its spaming tbh
this should error
a file with "extra data" can look like this: {"channel_id": 2468, "last_count": 1234}234} ^ Extra data this is a typical issue when you forget to truncate the file before/after writing, but when you use open("file", "w") it does the truncation for you which ensures you wont have extra data when you dump your dictionary's contents into the file
Hey all, forgive me if I'm in the wrong place, but seeing a ton of questions here...
Working on a discord bot that pulls a random row out of MySQL database via connection to Python, everything works perfectly, except the random part. Does anyone have any insight on possible routes I can take to troubleshoot this? Is there a way possibly to "refresh" the MySQL connection every time the query is run, or the bot is run? New to Python, so looking for knowledge, not just a quick fix. Thanks!
can I display custom emojis in discord.py button's label?
what williboy said, that is syntactically incorrect, but given your bot is spamming i presume you have written it like this: py @client.event async def on_message(message): if message.author.id == 571027211407196161: for word in raids_keywords: await message.channel.send(f'{message.mention.author}.') else: await message.channel.send('Nothing atm') remember what i said before?
the on_message event is fired for every message the bot can see
that means any message, from any channel, from anyone, including the bot's own messages too
also sending a bunch of messages in that for loop will get your bot ratelimited
Alright so, how can i fix it to read only messages of the bot that i wanna?
this question might be more related to #databases, but surely re-executing a query with a different random number should give you a different result?
apparently its only allowed in the emoji field, not the label
if it comes from the bot, do whatever, else do nothing
dont have the .send("Nothing atm") in that else clause
@client.tree.command(name="test")
async def test(interaction: discord.Interaction, id: str, message: str):
user = client.get_user(int(id))
await user.send(message)
Hello this is my code for a slash command where you put someones id and message, and the bot will send the message to the user. Is there a way that I instead of typing someones id I can just type name like random#1234
can I increase or decrease the size of the emoji ?
no, i dont think discord's api provides that kind of fine grained adjustments
use discord.Member as the typehint instead and discord.py will take advantage of the USER option type which should give you name autocompletion for free
Thanks kindly for the reply. Will give databases a shot!
Essentially the query is stored in a dataframe, which successfully passed on to the discord bot command. Although I am unsure how to tackle the refresh process of sorts. Each time the command is used, I get a random row, but it doesn't change, same random row over and over. I'm not sure how to retrigger the query to run again once the command executes and returns something in a discord channel. Is there a way to ensure the script gets re run after a condition like the command has been used?
Sorry if this is unclear, very new haha.
well it sounds like you want the command to be making the query each time then
e.g. py @bot.command() async def my_command(ctx): async with connection_pool.acquire() as conn: row = await conn.fetchrow( "SELECT something FROM table WHERE id >= MAX(id) * RANDOM() LIMIT 1" ) await ctx.send(f"picked: {row['something']}")
How to do that? sorry if I sound dumb
This is really awesome, can't thank you enough. Will get familiar with this code and try to get this integrated!
async def my_command(interaction, user: str):
^^^^^``` that part is typehinting the `user` parameter with str, so to typehint it with discord.Member you would write: ```py
async def my_command(interaction, user: discord.Member):
^^^^^^^^^^^^^^^^```
dont follow it too literally as it's just an example based on the usage of discord.py and asyncpg (for a postgresql database) (also that query itself can have biases depending on the data), but the body of your command runs each time it gets used so you probably want to put your query in there
that works but if I in my dms with the bot and run the command it give me an error saying: discord.app_commands.errors.TransformerError: Failed to convert Petrrrrr#1030 to Member. Is there a way that would work even in dms works now instead of discord.Member i used discord.User
Yeah figured as much, just need some breadcrumbs re: possible functions to use, fetchrow being the one. I have random row logic baked into the dataframe so will try to combine the two.
Again, I really appreciate you taking the time to help me out!
oh yeah thats right, member wouldnt make sense if its outside of a guild
Traceback (most recent call last):
File "C:\Users\danie\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ui\view.py", line 414, in _scheduled_task
await item.callback(interaction)
File "c:\Users\danie\Desktop\Programação\Discord bots\Dlr-Bot 2.22\main.py", line 50, in green_button
await interaction.response.edit_message(embed=embed3, view=View())
File "C:\Users\danie\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\interactions.py", line 769, in edit_message
raise InteractionResponded(self._parent)
discord.errors.InteractionResponded: This interaction has already been responded to before
Ignoring exception in view <View timeout=None children=1> for item <Button style=<ButtonStyle.success: 3> url=None disabled=False label='Votar' emoji=<PartialEmoji animated=False name='✅' id=None> row=None>:
Traceback (most recent call last):
File "C:\Users\danie\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ui\view.py", line 414, in _scheduled_task
await item.callback(interaction)
File "c:\Users\danie\Desktop\Programação\Discord bots\Dlr-Bot 2.22\main.py", line 50, in green_button
await interaction.response.edit_message(embed=embed3, view=View())
File "C:\Users\danie\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\interactions.py", line 769, in edit_message
raise InteractionResponded(self._parent)
discord.errors.InteractionResponded: This interaction has already been responded to before
help pls
@discord.ui.button(label="Votar", style=discord.ButtonStyle.green, emoji="✅", custom_id='persistent_view:green')
async def green_button(self,interaction:discord.Interaction, button:discord.ui.Button):
# Consultar o banco de dados para obter informações sobre a mensagem e a votação atual
cursor.execute("SELECT id_user, url, author, content, votos FROM main WHERE message_id = ?", (interaction.message.id,))
result = cursor.fetchone()
if result is not None:
id_user, url, author, content, votos = result
else:
await interaction.response.defer()
await interaction.followup.send(content="A mensagem não foi encontrada no banco de dados!", ephemeral=True)
return
if id_user is not None and id_user == interaction.user.id:
# A mensagem já foi votada pelo usuário
await interaction.response.defer()
await interaction.followup.send(content="Você já votou nesta foto!", ephemeral=True)
else:
# A mensagem ainda não foi votada pelo usuário
votos += 1
sql = ("UPDATE main SET votos = ?, id_user = ? WHERE message_id = ?")
val = (votos, interaction.user.id, interaction.message.id)
cursor.execute(sql, val)
embed3 = discord.Embed(title='📸 Nova Foto Enviada 📸, Votos {}'.format(votos),
description=f'Foto de {author}\nJogo: {content}', color=3407616)
embed3.set_image(url=url)
await interaction.response.edit_message(embed=embed3, view=View())
interaction.followup.edit use this instead of interaction.response.edit
How I can delete 100 messages per second, in this code??? The messages, should still delete, until there is no more messages, Except the Pinned messages? Can anyone help me?
Code:
async def handle_incorrect_message(message):
global count
count = 0
print("-------------------------------------------")
print("Discord Reset Successful")
with open(data_file, 'r+') as f:
data = json.load(f)
data['last_count'] = count
f.seek(0)
json.dump(data, f)
print("Json Reset Successful")
await message.add_reaction("❌")
await message.channel.send(f"An incorrect number or operation has been written, channel is being reset, please wait!")
overwrites = {message.channel.guild.default_role: discord.PermissionOverwrite(send_messages=False)}
await message.channel.edit(overwrites=overwrites)
print("Reject Send Messages")
await asyncio.sleep(5)
await channel.purge(limit=None, check=lambda message: not message.pinned)
overwrites = {message.channel.guild.default_role: discord.PermissionOverwrite(send_messages=True)}
await message.channel.edit(overwrites=overwrites)
print("Allow Send Messages")
@bot.tree.command(name="add", description="Adds a user to the ticket.")
async def add(interaction, member:discord.Member):
if not interaction.channel.name.startswith('ticket-'):
await interaction.response.send_message('This is not a ticket channel.', ephemeral=True)
return
await interaction.channel.set_permission(interaction.member, view_channel=True, send_messages=True, read_messages=True)
await interaction.response.send_message(f"{interaction.member.mention} has been added from the ticket.", ephemeral=True)``` im trying to make it so if someone uses it, they can choose someone to join the ticket channel everything but adding the permissions work
no you should not delete 100 messages per second
set_permission is not a thing
!d discord.abc.GuildChannel.set_permissions
await set_permissions(target, *, overwrite=see - below, reason=None, **permissions)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sets the channel specific permission overwrites for a target in the channel.
The `target` parameter should either be a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") or a [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role") that belongs to guild.
The `overwrite` parameter, if given, must either be `None` or [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/latest/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite"). For convenience, you can pass in keyword arguments denoting [`Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions "discord.Permissions") attributes. If this is done, then you cannot mix the keyword arguments with the `overwrite` parameter.
If the `overwrite` parameter is `None`, then the permission overwrites are deleted.
You must have [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") to do this...
i have code:
async with aiohttp.ClientSession() as session:
webhook = discord.Webhook.from_url(webhook_url,
session=session)
msg = await webhook.send(embed=embed, wait=True)
await msg.add_reaction("✅")
but i have an error
AttributeError: PartialWebhookState does not support http methods.
how can i add reaction on this message?
@bot.tree.command(name="add", description="Adds a user to the ticket.")
async def add(interaction, member:discord.Member):
if not interaction.channel.name.startswith('ticket-'):
await interaction.response.send_message('This is not a ticket channel.', ephemeral=True)
return
overwrites = {
interaction.user: discord.PermissionOverwrite(view_channel=True, send_messages=True, read_messages=True)
}
await interaction.channel.set_permissions(interaction.member, view_channel=True, send_messages=True, read_messages=True, overwrites=overwrites)
await interaction.response.send_message(f"{interaction.member.mention} has been added from the ticket.", ephemeral=True)``` like this?
overwrites are PermissionOverwrite objects
nvm i think you can pass in dict too
is it right tho?
why don't you try it
a partial webhook is just a webhook with an id and token
and what i need to do?
i'm not sure hold on
(
Why?
How should I solve it then?
you don't
if you're trying to delete all messages from a channel just clone it and delete the old one
Unfortunately, this is not possible because it would be much more complicated to let the bot recognize the new channel automatically when it was created! Then please tell me one way, as I have many Delete messages at once without becoming rate limited! It's for my Counting Discord Bot!
deleting 100 messages per second is not viable either
But then please tell me one way!
i've already said how to do it
if you have a configuration for a counting channel, you can just automatically update it
Why can't I eg. how to do the mee6 bot, which can delete over 1000 messages at once with one command? Isn't there a way?
Yes, you must activate "Moderation" on the Dashboard, and you can use a command, To clear as many Messages you want!
don't compare your bot to mee6, it's a bot that got verified and unverified lmao
i mean assuming you use the bot to delete/create the channel you can modify the ID for example of the old channel and update it as you have the channel object when you create it
Noob question sorry guys, is the standard for publishing your bot to create a new instance of the bot project on the server every time the bot is added?
Otherwise, for a bot that is deployed across a wide number of servers, how do you go about giving it the ability to monitor and respond to potentially many queries and commands at once? Is multithreading enough?
discord.py handles that, you don't need to worry about that as long as you're not using blocking drivers
you can't modify IDs?
discord.py is already asynchronous
it can handle many tasks at once
Gotcha
Would you recommend standard discord.py or pycord more for someone looking to build a relatively simple bot that has a few commands and can respond to messages on certain channels?
i use discord.py
but pycord is basically hard forked; it does not keep up with the regular discord.py
in terms of db / channel storage for his bot itself
not the server
yes that's what i suggested
I've noticed discord.py has less support for things like slash commands, or at least that kind of thing is built into pycord
that's not true
where are you getting that information from
It harder to do slash commands but they are possible
From my experience but saying that I’ve been using it outdated for so long now and have realised you need to use bot not client
they're not hard, you're spreading false information
it's the exact same process as adding a message command
Oof, my experience is outdated though so it was different
Not spreading false information, calm it
I see that now
sorry
@smoky sinew Only meant that from what I've seen if you want to incorporate slash commands into discord.py you need to mess with command tree syncing, and so far I haven't needed to do that with pycord. Both are new libraries to me though, so I'm sure I've got some of this stuff wrong.
commands are synced by yourself
i usually would recommend making a message command to sync
or use jishaku which has that and other helpful tools
np
Getting the error Pylance(reportMissingImports) when trying to import discord.utils any clue how to fix this? I've tried some stuff but Google hasn't been very helpful
Can you send the full error
how do i use another bot to fetch an embed's description and print it using discordpy?
2023-03-03 19:14:26,031 - discord.client - WARNING - PyNaCl is not installed, voice will NOT be supported - __init__ - line 263
[2023-03-03 19:14:26] [WARNING ] discord.ext.commands.bot: Privileged message content intent is missing, commands may not work as expected.
2023-03-03 19:14:26,033 - discord.ext.commands.bot - WARNING - Privileged message content intent is missing, commands may not work as expected. - _async_setup_hook - line 216
[2023-03-03 19:14:26] [INFO ] discord.client: logging in using static token
2023-03-03 19:14:26,033 - discord.client - INFO - logging in using static token - login - line 571
[2023-03-03 19:14:26] [INFO ] discord.gateway: Shard ID None has connected to Gateway (Session ID: d4aedab847a346ff7a76ac52768388f6).
2023-03-03 19:14:26,863 - discord.gateway - INFO - Shard ID None has connected to Gateway (Session ID: d4aedab847a346ff7a76ac52768388f6). - received_message - line 561
Bans Bot Online
Unable to process ban (BM Error) for server Artifact Error: 'meta'
are you using a virtual environment?
for example, on poetry, you would have to do poetry shell and then code .
not entirely sure what you mean
nevermind
looking at the documentation though all of the console output i'm getting is normal
aside from
Unable to process ban (BM Error) for server Artifact Error: 'meta'
pip install PyNaCl
alternatively
python3 -m pip install -U discord.py[voice]
may work, both should fix it but hopefully you only need one or the other
that's not their issue
what is giveaway in discord, can anybody explain me?
?
is this related to discord bots
Then where do I ask it?
giveaway is also related to giveaway bot, isn't it?
this server is about coding
is there a way to make a https/liverserver in vsc?
live server for what
like this to host it using https
i know, thats why i want to manage to do it on vscode
do u have a link?
look up live server in vscode extensions
they're not the same thing
oh
you can't host your bot on vscode
#965291480992321536 i don't know anything
just self host if you can, you can buy a raspberry pi and if you don't pay electricity it's mostly free
AWS staring in the background
amazon 🤮
Anyone wanna work with me on a discord bot?
what is the new way of running on_ready in a cog?
sure
you mean loading cogs? you can do that in setup_hook
DM me
no litterly using an on_ready
i tried that but it not doing it
as I have in the cog the presence
change
and the cog is loading
.
Do I have to restart my entire bot to get new slash commands? or can I simply reload the cog?
neither you need to sync commands
make a message command that runs bot.tree.sync
NEATO
Would I replace "bot" with "client" if it's in a cog?
only use client if you’re using discord.Client
plz tell me how to add multiple clients discord.py code
Just do it
???
use 2 adding clients commands
can you plz provide example code for better understanding?
import discord
bot = discord.Client(command_prefix = '!', intents = discord.Intents.all())
client = discord.Client(command_prefix = '', intents = discord.Intents.all())
this should do
discord.Client constructor does not have command_prefix argument
is it possible to make a webserver in vscode to host a discord bot?
Can I dm you for help?
No
dont do this
not how that works
vscode is a text editor
Then tell me how to add multiple clients discord.py code
You mean like in replit? No lol
no not replit but u can do it in replit
Why do you need multiple clients to start with
That's why I said "like in replit"
why dont you just use a vps or self host
i cant really self host becasue this laptop is for school as well as personal
Cause mostly it's just xy problem
buy a raspberry pi
they start at $10
Ah yes happens
that’s the pi 4
look at raspberry pi zero
is there anything else?
like computers?
M yes on aliexpress it's 230$ ofc
Buy some old parts and build a server from them
no, to host
Like I did, but I had those parts already
neat
sheesh
at that point just buy an old laptop
or buy a shitty vps for like $5/mo
i mean
Personally I have a server built from scrap which is like pentium D 945 + 3 GB RAM and some HDD, and I rent a VPS on aeza.net for 5$/mo
The VPS has Ryzen 9 5800 and 2gb ram I think
I've got a couple c6g.4xlarge instances on aws
Hey @woeful magnet!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
@woeful magnet because bot.run is blocking
I want multiple clients connect to Discord simultaneously using their own user accounts in python but my code doesn't work, only shows "First Client has connected to Discord"
I have attached my code.
https://paste.pythondiscord.com/wefalovomo
client.run will not return until the bot has logged out
what is the solution for my code?
each bot should be running in its own thread
I have 3 clients including 1 bot and 2 users.
it is possible that this is as simple as ```py
from threading import Thread
Thread(client1.run).start()
Thread(client2.run).start()
Thread(client3.run).start()```
I cant recall if discord.py supports multithreading like this
also you may want to join the threads
this makes no sense
Where do I put tokens of clients in your expressions?
first of all self bots are against tos
second of all what is the reason for running 3 bots in the same code
i don't even think discord.py has a bot=False method anymore
yep it doesn't
Thread(client1.run, args=(token1,)).start()
Thread(client2.run, args=(token2,)).start()
Thread(client3.run, args=(token3,)).start()```
I am using discord.py version 1.7.3 for that.
I have three accounts in discord.
I want DMs those three accounts received from others to be displayed in separate categories in one server.
this server doesn't help with self bots
it's against the rules
why are you even using user accounts
just use bots
then client.run(user's token) is against rules?
yes
How can I achieve it with bots?
even the discord.py official server does not help with it
But I already implemented my idea with self bot using last version.
I redirected DMs my user account receive from other users to specific category in my server.
so basically modmail
if what I did is against rule, can you teach another way to implement my idea?
modmail?
https://github.com/kyb3rr/modmail @woeful magnet
if you're trying to automatically categorize your personal DMs, then that's simply not allowed
python discord uses this bot @novel apex
oops, great, so I can see DMs from other users in my server?
if they dm the modmail bot yes
oops, what I want is the case of when other users dm me.
that's not allowed
haha, okay
then do I have to purchase modmail bot?
Great, thanks for your help.
please do not ask with help for self bots
Thread(target=client1.run, args=(token1,), kwargs={'bot': False}).start() is it possible?
@woeful magnet
I am not good at discord bot, can I ask why I avoid self bot?
it's against discord tos and this server's rules
, but also, why are you asking me if its possible when you could easily just run the code and find out
what is tos?
Automating normal user accounts (generally called "self-bots") outside of the OAuth2/bot API is forbidden, and can result in an account termination if found.
guys so
i wanted to make a discord bot
that informs users of new roblox limited items
and when i run the code and send a dm to it (!check)
does roblox allow you to do that 🤔
how are we supposed to help you without your code
wait
import discord
import requests
DISCORD_BOT_TOKEN = 'discord token'
client = discord.Client(intents=discord.Intents.default())
@client.event
async def on_ready():
print('Bot is ready.')
@client.event
async def on_message(message):
if message.content.startswith('!check'):
response = requests.get('https://api.roblox.com/marketplace/limited-items')
data = response.json()
for item in data['data']:
if item['isNew']:
await message.channel.send(f"A new limited item is available: {item['name']}")
client.run(DISCORD_BOT_TOKEN)
data["data"] does not exist
so
!paste
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
also don't use requests with discord.py use aiohttp instead
bro just edit my code💀💀
i looked and roblox does not have a /marketplace/limited-items endpoint
so that would be your issue
How do I set the bot to only create channels under a category when executing slash cmd
what do you mean?
like a ticket system
where if people execute /open, it will open a ticket channel for them under the tickets category
!d discord.CategoryChannel.create_text_channel
await create_text_channel(name, **options)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A shortcut method to [`Guild.create_text_channel()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.create_text_channel "discord.Guild.create_text_channel") to create a [`TextChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel "discord.TextChannel") in the category.
how do I set the category
it already is set
Did you read what I says
huh
A shortcut method to Guild.create_text_channel() to create a TextChannel in the category.
I want it to create channel under a category not that category where the command is executed
same thing
get_channel(channel_id, /)```
Returns a channel with the given ID.
Note
This does *not* search for threads.
Changed in version 2.0: `channel_id` parameter is now positional-only.
get_category u meant
Doesn't exist
that's why it's called CategoryChannel
ok
hi, why i have "the app is unresponsive?
code here: https://pastebin.com/agLUAZzs
all work fine and no error in log in vs code...
i dont understand...
i think, its suppose to be ctx.send or ctx.say
anyways, does anyone know why when i use my bot to ping user based of their user ids on embeds, it just show bunch of numbers. but in mobile, it shows the bot pinging them, csan anyone help?
where?
in the channel.send
no, because channel = bot.get_channel(1234567891030731018)
idk tho i regularly use ctx
its same method...
are you sure?
probably the Bot is taking more than 3 seconds to respond to the interaction
there are also cpu bound operations in your code, I don't think they're thread safe, are they?
replaced channel.send by
await ctx.send(f"Hé {ctx.author.mention} \U0001F447")
await ctx.send(file=file)
and now, no error...
thread safe? what do you mean?
Respond using the context
You're sending the message to the channel but not responding to the interaction
how is ctx a thing in on_message lol
oh i misread sorry
not in on_message...
no problem
i need help for this
what is a "nuke bot"
I believe it is a discord bot that "nukes" the channel by banning everyone and erasing all channels.
Yeah, lol
Can someone help
with...?
lmao
Traceback (most recent call last):
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ui\view.py", line 370, in _scheduled_task
await item.callback(interaction)
File "c:\Discord\Maja Projekt\MajaSystem_Test\modules\user_moderation\view.py", line 156, in callback
await inter.response.send_message(view=view)
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\interactions.py", line 866, in send_message
await adapter.create_interaction_response(
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\webhook\async_.py", line 184, in request
raise HTTPException(response, data)
nextcord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In data.components.0.components.0: Value of field "type" must be one of (2, 3, 5, 6, 7, 8).```
This, i have no idea why
send your code. Also I have no experience with select menus so wait for somebody else to help you
Which class?
one that errored
What is SelectEditWarn
class SelectEditWarn(nc.ui.Select):
def __init__(self, target, options):
super().__init__(placeholder="Choose a case", min_values=1, max_values=1, options=options)
self.target = target
self.options = options
async def callback(self, inter: nc.Interaction):
select_value = self.values[0].split()[1]
async with aiosqlite.connect("maja.db") as db:
async with db.cursor() as cursor:
await cursor.execute('SELECT reason FROM warn_system WHERE user_id = ? AND guild_id = ? AND case_id = ?', (self.target.id, inter.guild.id, select_value))
reason = await cursor.fetchone()
formated_reason = ''.join(reason)
print(formated_reason)
view = EditWarnModal(self.target.id, select_value, formated_reason)
await inter.response.send_message(view=view)```
is it because you're setting max_values?
No
Modals cant be sent with regular messages, for that you need send_modal
!d discord.InteractionResponse.send_modal
await send_modal(modal, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Responds to this interaction by sending a modal.
how to counting owned roles? I use this but the result is increased by 1
counts = len(member.roles)```
how do i make a discord bot ( interaction ) to leave any server if the server it joined doesnt match my guild id
discord.py is back?
ask chat gpt ai
hahahaha im sorry
what library are you using?
you can listen for this event
!d discord.on_guild_join
discord.on_guild_join(guild)```
Called when a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild") is either created by the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") or when the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") joins a guild.
This requires [`Intents.guilds`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.guilds "discord.Intents.guilds") to be enabled.
went back into development a year ago, 2.0 released 6 months after, and the latest version is 2.2.2 which came out a couple days ago
wow they've already released another micro
looks like it was just to fix a few incorrect typehints
ah yeah discord's voice breaking change
udp packets are now long 74 bytes instead of 70
Working on getting a random row generator to execute in discord, was able to get some help (thanks again thegamecracks), and have been using aiomysql package to try and accomplish this. Switching over to this has now stopped the command from executing (suspecting my my_first_command variables are off), and the data is being returned strangely, it is pulling column headers and no data. Any suggestions would be most appreciated! Thanks kindly in advance!
# Core Discord bot file to product slash command functionality (WIP)
import interactions
import os
from dotenv import load_dotenv
import mysql.connector as cnx
import datetime
import pandas as pd
import sqlalchemy as sa
import pymysql
import sys
import asyncio
import aiomysql
engine = sa.create_engine('mysql://root:root@localhost:3306/dominion_data')
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
GUILD_ID = os.getenv('DISCORD_GUILD_ID')
bot = interactions.Client(token=TOKEN)
loop = asyncio.get_event_loop()
@bot.command(
name="2kplayer",
description="Work in progress",
scope=GUILD_ID,
)
async def my_first_command(ctx):
conn = await aiomysql.connect(
host='127.0.0.1',
user='root',
password='root',
db='dominion_data',
loop = loop
)
cur = await conn.cursor()
await cur.execute('SELECT first_name, last_name, team_name FROM players_2k22 AS t1 JOIN (SELECT player_id as player_id_t2 FROM players_2k22 ORDER BY RAND() LIMIT 1) as t2 ON t1.player_id=t2.player_id_t2 LIMIT 1;')
print(cur.description)
await cur.close()
conn.close()
bot.start();
ah i thought you were referring to 2.2.1 -> 2.2.2, first patch fixed that
cur.description describes the columns, but not the data itself (see https://peps.python.org/pep-0249/#description or https://aiomysql.readthedocs.io/en/latest/cursors.html#Cursor.description)
perhaps you meant to use fetchone() to retrieve the actual data as a row?
Let me dig into fetchone() again, was trying to integrate that but to no avail using the documentation. Thanks for the heads up!
oh and if you are using sqlalchemy in your bot id suggest using their asyncio extension so you're not blocking the event loop
https://docs.sqlalchemy.org/en/20/orm/extensions/asyncio.html
Hey @brave moth!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
damn it discord. why u had to make it txt
as i was saying, updated to new discordpy then this happened https://paste.pythondiscord.com/ehuzedazal. can anyone help me with it?
you can rename files to make them another extension
copy that, thanks!!
weird, can you try updating jishaku? the shims that it imported dont exist in master branch anymore
ah, it appears this was initially fixed in Gorialis/jishaku#196 before it got removed
whatever version of jishaku you have is before january 24
i did but i sorted it out. had to do pip install -U git+https://github.com/Gorialis/jishaku instead of pip install -U jishaku and it worked
they fixed a memory leak 
Got the data normalized, just need to get it stored properly so that it can be called by the command itself. Thanks a ton again for your replies & help!
i was about to say i had set my bot to restart daily because it would eventually crash from memory leaking, but coincidentally i found out it crashed a few hours ago while importing jishaku
apparently my virtualenv didnt have setuptools
right i remember breaking my head with gc and bunch of bs with weakref to trace it i traced till views but then i just decided not worth the trouble and just switched
rip 🗿
wait so jishaku depends on setuptools, but they dont have it listed as a dependecy?
i think setuptools causes trouble as dependency especially when deploying i remember adding it in my poetry when deploying and the servers pip crashed due to that
uhh you werent upgrading the system python's packages right?
i wasn't doing anything it was only listed in my dependencies the server just asked my dependency file name
hmm it sounds like a them problem
probably
from disnake.ext import commands
import disnake, os, dotenv
import aiohttp
class ChatGPT(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_ready(self):
print(f"Cog loaded: {self.qualified_name}")
@commands.command(name="ask")
async def ChatGPT(self, ctx: commands.Context, *, Prompt: str):
async with aiohttp.ClientSession() as session:
payload = {
"model": "text-davinci-003",
"prompt": Prompt,
"temperature": 0.5,
"max_tokens": 50,
"presence_penalty": 0,
"frequence_penalty": 0,
"best_of": 1,
}
headers = {"Authorization": f"Bearer {API_KEY}"}
async with session.post("https://api.openai.com/v1/completions", json=payload, headers=headers) as resp:
response = await resp.json()
ChatGPT_Embed = disnake.Embed(title=f"Chat GPT's Response:",
description=response["choices"][0]["text"])
await ctx.reply(embed=ChatGPT_Embed)
dotenv.load_dotenv()
API_KEY = os.getenv("ChatGPT")
def setup(bot):
bot.add_cog(ChatGPT(bot))
I got an error:
Ignoring exception in command ask:
Traceback (most recent call last):
File "C:\Users\alliy\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\disnake\ext\commands\core.py", line 172, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\alliy\Desktop\Programs\Neko-Nyan\Neko-Nyan\Cogs\ChatGPT.py", line 30, in ChatGPT
description=response["choices"][0]["text"])
KeyError: 'choices'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\alliy\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\disnake\ext\commands\bot_base.py", line 578, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\alliy\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\disnake\ext\commands\core.py", line 914, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\alliy\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\disnake\ext\commands\core.py", line 181, in wrapped
raise CommandInvokeError(exc) from exc
disnake.ext.commands.errors.CommandInvokeError: Command raised an exception: KeyError: 'choices'
I'm guessing this happens cuz I'm passing in the API KEY Inappropriately? Could someone help me out? 
I know that there's also a KeyError. But I think the only reason I'm getting the KeyError in the first place is because my code can't access the API. 
Correct me if I'm wrong
you can print the response and find out
did discord change how embeds work?
I keep getting the "Cannot send an empty message" error
embed = discord.Embed(titile="Coinflip", description="My coin landed on a")
await dm.send(embed=embed)
can you provide full error?
Fixed it.
!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.
ChatGPT's AI fixed it for me
Hate the feeling of having a bot fix my mistakes so I'll try understanding it at least 
Found the main cause
It was a simple typo in the code.
I wrote "frequence_penalty"
When it should've been "frequency_penalty"
Well. Thanks guys 
how do i check if a user has the active developer badge
!d discord.User.public_flags
property public_flags```
The publicly available flags the user has.
!d discord.PublicUserFlags.active_developer
Returns True if the user is an active developer.
New in version 2.1.
oh its actually added mow ty
:incoming_envelope: :ok_hand: applied mute to @slate swan until <t:1677949887:f> (10 minutes) (reason: attachments rule: sent 9 attachments in 10s).
The <@&831776746206265384> have been alerted for review.
bros gone
!unmute 874530550487060490
:incoming_envelope: :ok_hand: pardoned infraction mute for @slate swan.
!paste
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
Command "stats" is not found
pls fix above error i am getting this error when i used cogs to divide the commands , events etc but i think i am doing something wrong pls fix this
my bot code is
# Libs
import discord
from discord.ext import commands
import json
from pathlib import Path
import logging
import datetime
import os
#intents
intents = discord.Intents.default()
intents.members = True
intents = discord.Intents().all()
cwd = Path(__file__).parents[0]
cwd = str(cwd)
print(f"{cwd}\n-----")
#Defining a few things
secret_file = json.load(open(cwd+'/bot_config/secrets.json'))
bot = commands.Bot(command_prefix='-', case_insensitive=True, owner_id=271612318947868673, intents=intents)
bot.config_token = secret_file['token']
logging.basicConfig(level=logging.INFO)
bot.blacklisted_users = []
bot.cwd = cwd
bot.version = '5'
#few things to make easier the code
bot.colors = {
'WHITE': 0xFFFFFF,
'AQUA': 0x1ABC9C,
'GREEN': 0x2ECC71,
'BLUE': 0x3498DB,
'PURPLE': 0x9B59B6,
'LUMINOUS_VIVID_PINK': 0xE91E63,
'GOLD': 0xF1C40F,
'ORANGE': 0xE67E22,
'RED': 0xE74C3C,
'NAVY': 0x34495E,
'DARK_AQUA': 0x11806A,
'DARK_GREEN': 0x1F8B4C,
'DARK_BLUE': 0x206694,
'DARK_PURPLE': 0x71368A,
'DARK_VIVID_PINK': 0xAD1457,
'DARK_GOLD': 0xC27C0E,
'DARK_ORANGE': 0xA84300,
'DARK_RED': 0x992D22,
'DARK_NAVY': 0x2C3E50
}
bot.color_list = [c for c in bot.colors.values()]
@bot.event
async def on_ready():
# On ready, print some details to standard out
print(f"-----\nLogged in as: {bot.user.name} : {bot.user.id}\n-----\nMy current prefix is: -\n-----")
await bot.change_presence(activity=discord.Game(name=f"Hi, my names {bot.user.name}.\nUse - to interact with me!")) # This changes the bots 'activity'
@bot.event
async def on_message(message):
#Ignore messages sent by yourself
if message.author.id == bot.user.id:
return
#A way to blacklist users from the bot by not processing commands if the author is in the blacklisted_users list
if message.author.id in bot.blacklisted_users:
return
await bot.process_commands(message)
if __name__ == '__main__':
# When running this file, if it is the 'main' file
# I.E its not being imported from another python file run this
for file in os.listdir(cwd+"/cogs"):
if file.endswith(".py") and not file.startswith("_"):
bot.load_extension(f"cogs.{file[:-3]}")
bot.run(bot.config_token)
@visual yarrowi bymistake sent mass ss
sorry for that
** pls fix my error **
!d discord.ext.commands.Bot.load_extension
await load_extension(name, *, package=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Loads an extension.
An extension is a python module that contains commands, cogs, or listeners.
An extension must have a global function, `setup` defined as the entry point on what to do when the extension is loaded. This entry point must have a single argument, the `bot`.
Changed in version 2.0: This method is now a [coroutine](https://docs.python.org/3/glossary.html#term-coroutine "(in Python v3.11)").
you need to await it
how
how do i make it so it displays 2 badges? ive tried this:
if user.public_flags.hypesquad_bravery:
e.add_field(name=f"**Badges**", value=f" Hypesquad Bravery", inline=False)
if user.public_flags.active_developer:
e.add_field(name=f"**Badges**", value=f" Active Developer\n Hypesquad Bravery", inline=False)```
await bot.load_extension(...)
just this ?
yes but await must be inside async function
which async function ?
any but you prolly want to load extensions on startup
so i would put it inside on_ready event
i am newbie so i dont know much about discord.py
or create main function and do it there
and call it at the end with asyncio.run
can u create it for me i am not getting it
move the code that loads extensions to on_ready function
and add await before bot.load_extension
howw ?
how what
those are simple instructions
do you know which lines of your code load extensions?
if you want them in one field you could create a string like this
badges = ""
if user.public_flags.hypesquad_bravery:
badges += "bravery "
if user.public_flags.active_developer:
badges += "developer "
e.add_field(name=..., value=badges)
okay thanks
Hey @median rivet!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
!d intents
what
Using the discord api *
No thats a library, i literally mean the discord api at discord.com/api
i have made like a full commands handler and such i just need a file uploading system now
{'code': 50109, 'message': 'The request body contains invalid JSON.'}
Bad Request
Error: 400
file uploading is handled with multipart payloads, and in the requests module its done with the files= kwarg https://requests.readthedocs.io/en/latest/api/
that being said, where did you get this data information from? it doesnt match the API reference at all
ok well in elite's example the file value is fine but content doesnt seem right
given the docs, you should just be able to use the file object you opened as the value for your files dict, e.g. py with open(path, "rb") as f: requests.post(..., files={f.name: f})
are you using discord.py 2.0? if so, you need to enable the message_content intent
i have already fixed the issue
i dont see any error in this code though the docs make it clear
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.
you may also share the full command code
I used one this time and I got this in my dm
<discord.embeds.Embed object at 0x000001BD66336950>
with embed=embed ?
impossible
If you pass in just embed it thinks it's the actual content of the message
embed = discord.Embed(titile="Coinflip", description="My coin landed on a")
await dm.send(embed)
embed=embed indicates that the embed object should be rendered as an actual embed
but when I do embed=embed it doesnt work
you misspelled title
What makes you say that?
lol...
how isnt that throwing an exception 
same error
you could try passing empty character into content but still thats not how it should work
okayyyy so I tried this
embed = discord.Embed(title="Bot created successfully", description=f" bot has been created successfully", color=0x00ff00)
await dm.send(content="aaaa", embed=embed)
and It just sent me a message saying aaaa
without the embed?
no embed
try to rename the varriable embed
what dm is?
dm = await ctx.author.create_dm()
it sent you a dm because you are the one invoking the command
🤦
yeah... thats what we want but its not sending the embed
okay?
error?
umm it just sent me a message saying
Ellipsis
LOL
and theres an error now
new error?
what dm is now?
dm = await ctx.author.send(...)
code?
did you put it after declaring varriable embed
then you know what to do
embed = discord.Embed(...)
try:
await ctx.author.send(embed=embed)
except discord.Forbidden:
...
It's easy as that nothing complicated
is your discordpy version up to date?
you can try doing pip install -U discord.py
this code works now
lol tysm
its called a timestamp and you format it this way: <t:TIMESTAMP:STYLE> where TIMESTAMP is timestamp (if you dont know what timestamp is google it) and STYLE is one of the styles provided by discord list of styles can be found here https://discord.com/developers/docs/reference#message-formatting-timestamp-styles
how do i mention a command, is it still </[command_name]:0>?
!d discord.utils.format_dt
discord.utils.format_dt(dt, /, style=None)```
A helper function to format a [`datetime.datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.11)") for presentation within Discord.
This allows for a locale-independent way of presenting data using Discord specific Markdown...
thanks
wait it's possible to code a discord bot in python ?
bruh
yes, using discord.py
there's more than just discord.py
json isn't a programming language
you can't code a discord bot in JSON
you are probably thinking of javascript
Hi yall, I want to add a delete button onto my help command, how could I pass a message object? I have to call the class when I send the message.
@bot.tree.command()
async def help(interaction: discord.Interaction):
embed = discord.Embed(title="Help Panel",
description="text here",
color=0xD2042D)
embed.set_footer(text="Help was requested by: {}".format(interaction.user.display_name))
class Helpdelete(discord.ui.View):
def __init__(self, message):
super().__init__()
@discord.ui.button(label="🗑️", style=discord.ButtonStyle.red)
async def menu1(self, button: discord.ui.Button, interaction: discord.Interaction):
try:
await message.delete()
except Exception as e:
print(e)
message = None
message = await interaction.response.send_message(embed=embed, view=Helpdelete(message))
Where/how could I pass a message object to the menu1 function in order to delete it?
...or I could make it with reactions ik but this would look wayyyy nicer
I have tried that before but I get this error:
'Button' object has no attribute 'message'
As far as I know I can only call classes in the view parameter
hi, I'm migrating from 1.7.3 to 2.2 but i can't get the task loop to start
you can't call a class
not in that way at least
interaction and button are switched
that doesn't work what do i change?
I have used this exact method 3 times in my code and it works so I'm not really sure what you mean by that
interaction and button are switched is your issue
but also there's no point in putting the class inside the function
I've used interaction.message.delete() but the button is the interaction...?
yes because you switched the order
unindent your cog_load function, or alternatively .start() your loop in init directly
well if it doesn't affect the performance I'll keep it there cuz its more organized
I'm not sure what you mean by that, the order of what?
the order of arguments in your function
it only has the discord.Interaction
oooh in menu1, sorry, I thought you mean the whole help thing
what can this error mean?
RuntimeWarning: coroutine 'PartialMessage.delete' was never awaited
interaction.message.delete()
add await before
that interaction.message.delete wasn't awaited???
it was, I just didn't save it
sorry
!d discord.ui.Modal
class discord.ui.Modal(*, title=..., timeout=None, custom_id=...)```
Represents a UI modal.
This object must be inherited to create a modal popup window within discord.
New in version 2.0.
Examples...
how do i reverse the list? so mods roles can be in first list
roles = ', '.join([role.mention for role in member.roles if role != ctx.guild.default_role])```
you can reverse a list using list.reverse() method
roles = ', '.join([role.mention for role in member.roles if role != ctx.guild.default_role])
roles.reverse()
like that?
hmm
reverse the list with roles
well my bot runs with the on_ready func but doesn't respond, and im using replit
is it cause of a outage ?
cause no errors when i run any of the commands
random guess but have you enabled the message_content intent? its typically required for text commands to work correctly
you probably shouldn't show your connection URI
also don't use pymongo with discord.py
do you have an on_message
yea
read the link
Not a good idea persay to put your Mongo DB URL in a repl.it which is most likely public unless you paid for premium
is there someting like discord bot roadmap?
Not exactly but you can find everything to discord.py
Using basic python and discord.py can do many things.
are you using pycord code with discord.py
tbh im so dumb w coding idfk
xD i got given this tool from a good friend of mine.
install pycord instead of discord.py then
py -m pip uninstall discord.py
py -m pip install pycord
@smoky sinew
try running your code again
!d discord.Message.reactions
Reactions to a message. Reactions can be either custom emoji or standard unicode emoji.
I am trying to create an embed reaction role post with buttons wthin a cog but I am not sure how to approach the interactions now, so when the button is clicked, you either get the role or remove it depending if you already ahve it or not. Just wondering if anyone could advise, heres my code: https://paste.pythondiscord.com/xizifilazi cheers, and sorry for spaghetti code.
thank you
you have to add a callbakc to the button
then check if the user has the role of the button, maybe set the button id to the role id
i would create a separate class for the view and button though like this:
class ReactionRoleButton(discord.ui.Button):
def __init__(self, role):
self.name = role[0]
self.emoji = role[1]
self.id = role[2]
super().__init__(
label = self.name,
custom_id = self.id
)
async def callback(self, interaction, button):
...
class ReactionRoleView(discord.ui.View):
def __init__(self):
super().__init__(timeout = None)
for role in roles:
self.add_item(ReactionRoleButton(role))
await channel.send(
view = ReactionRoleView(),
...
)
something like this, i have no idea if it will actually work @slate swan
also make sure your reaction role view is persistent so it works after the bot has restarted
Ok, thank you very much, I'll see what I can do 🙂 thank you for the advise, etc and your time. 🙂
message = await ctx.channel.fetch_message(message.id)
reactions = message.reactions
for reaction in reactions:
async for user in reaction.users():
print(user.name)
I am getting all the users who reacted to a message. How can I choose someone randomly?
you cannot do that on the same file
@woeful magnet i have asked you numerous times to not ask for help with self bots
Hello @smoky sinew can I ask a question?
"/giveaway - Bot Response - for a normal giveaway
/greroll - Bot Response - for a giveaway reroll
/racegiveaway - Bot Response - for a race giveaway or something
/glist - Bot Response - shows all active giveaways
/rgreroll - Bot Response - for a race giveaway reroll
/addxp - Bot Response - points given to a user
/blacklistxp add @user - Bot Response - banished from getting XP
/blacklistxp remove @user - Bot Response - can get XP again
/blacklist list - Bot Response -all users who have been blacklisted
/help - Bot Response - receive a list of commands and utilities
/info - Bot Response - information (you know)
/roleinfo - Bot Response - information about your role
/rolelist - Bot Response - lists all main and sub races
Do I have to develop bots separately to implement those slash commands?
no
So it means I can implement all those slash commands in one bot?
yes
I am sorry to ask about self-bots so far.
I wanna develop a bot which has those commands above, is there anything I can refer?
in the pins, there is a good guide for slash commands
i think they are asking about the command implementation itself
not how to register a command
Fair enough, 🙂
where is it?
both of them
I have installed server captcha bot in my server, can other users in my server can see it?
category = server.get_channel(CATEGORY_ID)
^^^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'get_channel'
Who can help me with this error?
@woeful magnet
Hi
send your code
Oh I fixed my error. Then other question
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.members = True
intents.message_content = True
description = 'An example bot to showcase the discord.ext.commands extension module.'
bot = commands.Bot(command_prefix='?', description=description, intents=intents)
@bot.command()
async def repeat(ctx, times:int, content="repeating..."):
"""Repeats a message multiple times."""
for i in range(times):
await ctx.send(content)
bot.run(' ')
In this code, Where do I put my bot token and how to import that token?
at the end inside bot.run??
If it's private, then just put it in the run meth
TOKEN = os.getenv('TOKEN')
bot.run('TOKEN')
is it possible?
no
you are using the string value of "TOKEN" not the variable
!e ```py
test = "hi"
print("test")
print(test)
@smoky sinew :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | test
002 | hi
I see
TOKEN = os.getenv('TOKEN')
bot.run(TOKEN)
right?
from discord_components import nextcordComponents, Button, ButtonStyle
ModuleNotFoundError: No module named 'discord_components'```
what's discord_components?
Discord components are cool, but discord.py will support it on version 2.0. It is hard to wait, so we made a third-party library for using components such as buttons or selects!
discord.py has had components for a while now that code is pretty outdated
send it
What
send what
@molten zodiac this is not the channel for that
@bot.event
async def on_application_command(ctx: discord.Interaction):
channel = discord.guild.get_channel(1081779753578672209)
await channel.send(f"{ctx.user.id} used the {ctx.command.name} command with options {ctx.options}")```
Bot is not sending any message to the channel...
you don't see anything wrong with that
why isnt its sending the message
your issue is discord.guild.get_channel
what do I do
you need a guild instance
Learn OOP
also does that event exist?
why do you mislabel it
I should probably put it in every cmd 💀
no you shouldn't
just name it correctly
this is misleading to yourself and whoever is reading your code
@smoky sinew yup sorry man got it
i want to make a discord bot for giveaway who will choose random participants
and give some lucky points to losers so that next time their winning probability is higher
do i need database to store the lucky points?
yes
i've never heard of that though, that's an interesting system
if you gonna scale your bot and making it public then yes you do
like a bigger database
if its just a private bot for a server with your friends then you dont' really need one
it depends on the amount of people that is going to use the bot
but yea a database is usually recommended
Anyone wanna collaborate to develop a bot (It is gonna be really good i guarantee)
Yes you will need a database for storing the lucky points and dm me I gonna tell you a good logic for ur program
just use the points in ur random bias as weights no other logic required
No the logic was
When a winner gets a credit set their lucky points to 0 and increment the points of others by a number say one and when some1s lucky points reach say 10 give em the prize and set their points to 0, and if there are 1+ superlucky people then pick a random one amongst them and when the people who get their prize after getting selected randomly even after being super lucky, will get n lucky points for patience.
n will be the number of turns they waited after being super lucky
!d random.sample too much complication
random.sample(population, k, *, counts=None)```
Return a *k* length list of unique elements chosen from the population sequence. Used for random sampling without replacement.
Returns a new list containing elements from the population while leaving the original population unchanged. The resulting list is in selection order so that all sub-slices will also be valid random samples. This allows raffle winners (the sample) to be partitioned into grand prize and second place winners (the subslices).
Members of the population need not be [hashable](https://docs.python.org/3/glossary.html#term-hashable) or unique. If the population contains repeats, then each occurrence is a possible selection in the sample.
Will he allow multiple winners?
yep there are 5 winners
ok then his solution will do
await interaction.response.send_message("Hiii", ephemeral=True)
^^^^^^^^^^^^^^^^^^^^
AttributeError: 'Button' object has no attribute 'response'```
i am getting this error
code?
not sure where to go with this but could anyone know whats happening? when i try running a discord bot using a custom made library with docker, it says this, but when i run the bot without docker (using like a normal cmd), it works perfectly fine
they're on the same commit both locally and on the docker container
interaction is before button
how to fix it?
it should be self, interaction, button
worked thanks
Which colour matches with discord embed?
Except for discord.Colour.dark_theme()
you mean the color of the embed so the line is invisible ?
Could you show your Dockerfile and file structure?
this may be what you are looking for #2f3136
#2B2D31 is the embed background colour
Hey @dense jackal!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
discord.Colour.dark_embed
help me please:
I have been trying to move the emojis for a bot in a seperate server but everytime i do this certain command in this certain server it bugs out and never displays the actual emoji... In other servers the emojis are perfectly fine and in other commands it works fine... whats happening?
did you change the emoji id
yeah ive changed everything
as i said, in other servers when i use this exact command, it seems to work just fine
the bot has all the permissions it needs like external server
Alright so basically I was coding a modmail bot with discord py and the script got really messy. On top of me not really good at coding, I don't understand alot of stuff in the script. We also tried to add a close command that closes the thread when sent. that command will do so the messages sent in the threads after command is ran wont be sent in the user's dms. Feel free to dm me. I need hard assistance lol.
I just need someone to help me make order in that and possibly explain to me how to code that close, open feature
so i wanted to display user key permission, but i just want to display the important perms like 'manage' or 'ban' how?
like dyno bot whois
the same emojis are sending perfectly fine by themselves...
how do i use a hyperlink in a embed title
Normally
That's some dumb discord bug, happened to me too, don't even remember how I resolved it
ive been at this for hours and i cant seem to resolve it lol 😭
But iirc it had to do something with external emojis permission
i have enabled external emojis everywhere from the bots role, to the channel permissions etc
Not sure how certain emojis are displayed but others are not
i used the same emojis in a different command and that worked
Actually how do you use emojis in text?
Yeah that's correct way
thats what i have and i know it cant be my code because in a different server it worked
is there any way to find out a buttons custom_id from a bot users perspective
is it somewhere in the html or anything
Discord uses no html if you look at dev panel
I only know very basics of web dev so idk
I assume theres no way to get at that info client side?
No
Not sure if you can fetch that info with user token but anyways that would be ToS violation
Just use text commands if you don't want people to know
Respond to interaction ephemerally and use inter.channel.send
okay
Or followup
@dull terrace actually try reading component custom ID of message of one bot with another bot
But I think they are private, as discord clarifies they are available in interactions sent to bot https://discord.com/developers/docs/interactions/message-components#custom-id
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
ima test and see, curious
yeah you can get custom ids with another bot
just printed off message.components after fetching another bots message and got all of the info
hey, i made a script thatt takes in a list of usernames that a scraped from a server and i want to add all them from the list, ive made the request but i just seem to be getting the status code 400
You wanna store users id from a guild?
I’ve already scraped all the users I want to add from a server cus they are all my friends and it’s like 400+ please. So I made something to scrape all the names and I want to add them
I thought I could using this end point and pass the user and the # in the json but i just get the 400 status code
Are you self-botting
no
I replied to a different user and you are replying to me, I got confused. 😄
That's a self-bot library
Well that's why called discum , dis-scum , discord scum.
LOOOL my bad I honestly didn’t do to much research into it I just didn’t want to re add all the people I know again
Guess I won’t use that again
Well you can but we can't help.
I only wanna add my friends…. And thought I’d try make something for fun
Don’t wanna break tos and get banned
:/
Find other way to make fun 😄
Technically I already have the ids so I can carry on making something to add everyone no ?
Can't help
!e
import random
bob = ("tuple", "random", "test")
print(random.choice(bob))
@dull terrace :white_check_mark: Your 3.11 eval job has completed with return code 0.
test
!e
def __init__(self):
super().__init__()
@discord.ui.button(label="Create a ticket", style=discord.ButtonStyle.blurple, custom_id="ticket_button")
async def ticket(self, button: discord.ui.Button, interaction: discord.Interaction):
ticket = discord.utils.get(interaction.guild.text_channels, name=f"ticket-for-{interaction.user.name}-{interaction.user.discriminator}")
print(ticket)
if ticket is not None:
await interaction.response.send_message("Ty už máš otevřený ticket!", 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"ticket-for-{interaction.user.name}-{interaction.user.discriminator}", overwrites=overwrites, reason=f"ticket for {interaction.user}")
await channel.send(f"{interaction.user.mention} created a ticket!")
await interaction.response.send_message("cc", ephemeral=True)
client = commands.Bot(command_prefix=".", intents=discord.Intents.all())
@client.command(name="ticket", description="Launches the ticketing system")
async def ticketing(interaction: discord.Interaction):
embed = discord.Embed(title="Pokuď potřebuješ pomoc, klikni na tlačítko!", color=discord.Colour.blue())
await interaction.channel.send(embed=embed, view=ticket_launcher())```
Uhh
for slash command its @client.tree.command


