#discord-bots
1 messages · Page 326 of 1
How do you prevent this?
[2023-11-30 23:28:00] [WARNING ] discord.http: We are being rate limited. POST https://discord.com/api/v10/channels/769452100786323457/messages responded with 429. Retrying in 0.30 seconds.
What were you doing to get rate limited?
Cleaning messages and assigning roles to users upon joining
How are you cleaning messages? Deleting them one by one? If so, that's the problem
No in bulk every 60 seconds
Can you share the code?
guys how can i edit a button from another button though its custom_id?
if subclassed view use self to acess it if not view.children
you mean to use view.children to access?
yeah
thats a list, i would need to iterate and check each's id?
or index it if u already know
isn't their any other way?
no
kk, ty
Can anyone tell me how can I add multiple Items to my bot's database? Items as in stuff that can be added in 'inventory' of a game
what lib is that?
how tough is making api wrapper for discord api
yo, in my discordpy bots ive never really had to utilize Cogs
in this example, they use the .listener attirbute as decorator instead of a bot.event
do they act the same?
i assume that when you load in the cogs, this decorator gets overwritten?
so i assume that listener, takes the passed bot instance in when creating custom Cogs
also, why are they adding parenthesis with listener when we dont pass any arguments? whats the point?
Should I use a list or set() if I don't want duplicates?
if you solely dont want duplicates, use set
but remember, sets are unordered
hey guys Im having issues with my slash commands constantly disappearing, only to return later
no errors in the log
its just to maintain consistency and clarity in the code really
set
its pretty complicated considering scale of the api and features
very tough lol
its massive, you will not be able to make one solo
damn
you need a very good understanding of low-level concurrency
and since its massive, you need very clear organization
!intents
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.
There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.
Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.
intents = discord.Intents.all()
dont set Intents to all unless you really need all intents enabled
im started the code
but why doesn't it run?
question regarding yielding code until a user has interacted with a selection menu:
Is there any way to see how many times a user boosted the server?
would asynchronously yielding the sequence with asyncio.Future's be good practice?
the selection menu would set the result of the Future object
async def wait_for_button(self):
self.interaction_future = asyncio.Future()
try:
return await asyncio.wait_for(self.interaction_future, timeout=60.0)
except asyncio.TimeoutError:
return None # timeout will return None, bot will handle the rest
finally:
self.interaction_future = None
self.interaction_future.set_result(interaction_result)
this will be ran inside the button callback
hey guy how make a bot online
You need to deindent client.run
how to do so
shift tab
and have this again
thank u so much
ctrl c
wait wat is ctrl c
thankkk you so much
Question, I have a command called /sell that allows players to sell resources to other players. The other players buy the resource by reacting to a checkmark on the original bot response. But right now when I wait for reaction if a player trys to run the sell command again itll automatically thing that the first message had a reaction on it.
@slate swan are you active right now?
?
Okay so can you help me with something real quick?
Well, ive asked many times, no one has ever helped me with this issue lol
Ive even posted everything in here, an in discord.py... just no one helps me with the issue...
Thats why I pinged you, cuz maybe you were online..
!d asyncio.to_thread
coroutine asyncio.to_thread(func, /, *args, **kwargs)```
Asynchronously run function *func* in a separate thread.
Any \*args and \*\*kwargs supplied for this function are directly passed to *func*. Also, the current [`contextvars.Context`](https://docs.python.org/3/library/contextvars.html#contextvars.Context) is propagated, allowing context variables from the event loop thread to be accessed in the separate thread.
Return a coroutine that can be awaited to get the eventual result of *func*.
This coroutine function is primarily intended to be used for executing IO-bound functions/methods that would otherwise block the event loop if they were run in the main thread. For example:
its more of a problem with PIL than discord.py
im not saying to replace it
Easy PIL, and PIL both just have issues XD
im saying i dont know the answer since its the problem itself is not really related to discord bots
Yeah imma post in there too
Rude
Hey
i’m a js developer but i wanted to try py for fun
discord_slash import SlashCommand is supported or am i just bugging?
i keep on getting errors trying to use slash commands even though i installed it
You shouldn't need that library
discord.py has slash commands built in
Ok well, since you're having errors with it you don't need to use it or get it to work
import discord
client = discord.Client()
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
@client.event
async def on_message():
if message.author == client.user:
return
if message.content.startswith('$hello'):
await message.channel.send('Hello!')
client.run(my token goes here)
when i run this it says theres a problem on the line 3 “client = discord.Client()” it says “missing 1 required keyword only argument. ‘intents’”
so there’s no solution?
can someone help me solving that
We can't tell without more information
!intents
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.
There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.
Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.
you need to specify intents
How
clueless, told me to install it saying “you need to install discord_slash_command” i was confused
Where
whatd
Where did it tell you that you need to install it
console
Show what it said
no module named ‘discord_slash’
( installed discord-py-interactions and discord_slash )
That’s extremely different from it telling you to install it lmao
no it’s told me that before
Anyway, as Robin already stated discord.py has slash command support
should i uninstall it rhen?
Yes
by the way, im a javascript developer it’s my first time using discord py so thank you pep
@final iron
import discord from discord_slash import SlashCommand from discord_slash.utils.manage_commands import create_option
then continues, the error is in line 3
Okay, do you want to switch to discord.py?
what do you mean
Do you want to switch to the discord.py library the main used library. You're using something else now.
discord_slash isn't really updated anymore.
oh yes
I recommend running this script first, this will get rid of any forks or other libs and install discord.py ```py
import os
import sys
py_exec = sys.executable
uninstall_list = " -m pip uninstall nextcord py-cord interactions.py disnake dislash discord-py-slash-command discord.py-message-components enhanced-discord.py novus hata discord-interactions discord.py-self discord.py-self.embed discord2 python-discord reactionmenu discord_py_buttons discord_slash discord.py discord discord-ext-forms discord-ext-alternatives"
os.system(py_exec + uninstall_list)
os.system(py_exec + " -m pip install discord.py --no-cache-dir")
Okay one moment
That's an AI, not the console
pov: type hinting
A custom wait_for method to asynchronously yield your coroutine in discord.py - GitHub - PogoDigitalism/custom-wait-for: A custom wait_for method to asynchronously yield your coroutine in discord.py
in case you've ever struggled with waiting for user responses but you dont want ugly while loops to check for instance variable updates
The whole reason callbacks were created was to prevent the usage of mass wait_fors
You kinda made an implementation Danny saw in other libraries and wanted to avoid creating
the reason i dont have callbacks implemented is because
it works horrendously with sequential code
If for instance, I had a shop that offered like currency for my Discord server which you can pay for with crypto or whatever payment methods
that requires a large ORM based sequence
using callbacks is yuck as this would require you to hop from callback to callback
which could (but certainly will) result in chaotic code
I 100% use callbacks where i can, but for large sequences i just cant
views have the .wait() method which is basically the same solution, waiting on a future that gets set by .stop() or timeout
https://github.com/Rapptz/discord.py/blob/v2.3.2/discord/ui/view.py#L526 ```py
class MyView(discord.ui.View):
@discord.ui.button(label="Continue")
async def on_continue(self, interaction, button):
self.interaction = interaction
self.stop()
for i in range(1, 4):
view = MyView()
await _ctx.send(f"Step {i}", view=view)
timed_out = await view.wait()
if timed_out:
break
interaction = view.interaction
await interaction.response.edit_message(content=f"Step {i} completed!")```
discord/ui/view.py line 526
return await self.__stopped```
my solution is not solely for views though, i never knew .wait() was a thing in view
thats nice
tho ill keep using my own as its more universal for getting the result of a component interaction inside the view
but tell me that what im saying here is not bullshit
because i feel like im missing something
oh wait, maybe i dont even need a wait_for
what if i just have a Future.wait()?
i pass this Future to my View, and set the result of the Future inside the view
i consider wait()/stop() to be the standard for getting results from views (in fact there's an official example showing it), but for anything else that's fair enough, that just means you're taking advantage of asyncio to do concurrent work
thanks for enlightening me on that, didnt know wait stop was a feature of View
but yea, 4am here. My brain is fried from coding from 11am to 4
goodnight! if you want, please look into what i claimed here, as im still not sure what im saying is actually correct
yes, this is known as callback hell and it's what futures and async/await is intended to solve (when they are used well)
er correction, only when you nest callbacks is when it's called callback hell, and async/await in python makes it easy to write the equivalent callback code as a sequence of await steps
Still, the callbacks will cause chaos :d
you can still write clean, callback-based code, for example if you have a bunch of different buttons to show for a tictactoe game at various points, you might write something like: ```py
@bot.tree.command()
async def tictactoe(interaction):
await interaction.response.send_message("Waiting for a player to join...", view=TicTacToeLobby(...))
class TicTacToeLobby(discord.ui.View):
@discord.ui.button(label="Join")
async def on_join(self, interaction, button):
await interaction.response.edit_message(
content=f"{x} is now playing against {y}!",
view=TicTacToeGame(...),
)
class TicTacToeCell(discord.ui.Button):
async def callback(self, interaction):
self.occupied_by = ...
await self.view.update(interaction)
class TicTacToeGame(discord.ui.View):
def init(self, ...): ... # add 3x3 grid or bigger
async def update(self, interaction):
if player_won is not None:
end_message = f"{x} won! Do you want to play again?"
elif empty_slots < 1:
end_message = f"It's a tie! Do you want to play again?"
else:
return
view = TicTacToeRematch(...)
await interaction.response.edit_message(end_message, view=view)
class TicTacToeRematch(discord.ui.View):
@discord.ui.button(label="Rematch")
async def on_vote(self, interaction, button):
if both_players_agreed:
await interaction.response.edit_message(
content=f"{x} is now rematching against {y}!",
view=TicTacToeGame(...),
)``` each view represents a specific phase/state of the game which makes it easy to transition between those views rather than having a single function deciding which view to send, especially when you have a lot of states to traverse through
of course not all commands need several views, but callbacks aren't necessarily unmaintainable if you can figure out how to organize them efficiently
!
I'm getting failed to load options for my autocomplete command, even though the code is copied from a YT video
import discord
from discord import app_commands
from discord.ext import commands
import typing
class Test_Command(commands.Cog):
def __init__(self, client: commands.Bot):
self.client = client
async def drink_autocompletion(self,
interaction: discord.Interaction,
current: str
) -> typing.List[app_commands.Choice[str]]:
data = []
for drink_choice in ['beer', 'milk', 'tea', 'coffee', 'juice']:
if current.lower() in drink_choice.lower():
data.append(app_commands.Choice(
name=drink_choice, value=drink_choice))
return data
@app_commands.command()
@app_commands.autocomplete(item=drink_autocompletion)
async def drink(self, interaction: discord.Interaction,
item: str
):
await interaction.response.send_message(f"{item}", ephemeral=True)
async def setup(client: commands.Bot):
await client.add_cog(Test_Command(client))
it is not working what's wrong?
Nah it was polite conversation
The copied from YouTube video explains it all
I wouldnt recommend learning coding bots on YouTube
the thing is, Ik how it works because I already have a command with autocomplete that was working fine few days ago. But now, it doesn't work at all
so to confirm if everything is correct, I searched on yt and followed the tut, but it is also not working
Check autocomplete example here
where it is?
class Test_Command(commands.Cog):
def __init__(self, client: commands.Bot):
self.client = client
@app_commands.command(name="echo")
async def echo(self, inter: discord.Interaction, color: str):
"""
Echoes a color
Parameters
----------
inter: discord.Interaction
The interaction object
color: str
The color to echo
"""
await inter.response.send_message(color)
@echo.autocomplete("color")
async def color_autocomplete(self, interaction: discord.Interaction, current: str) -> list[app_commands.Choice[str]]:
options = ["Red", "Green", "Blue"]
return [app_commands.Choice(name=option, value=option) for option in options if option.lower().startswith(current.lower())][:25]
as I said, something's really wrong it's not a coding fault
I realised that I have a custom tree for my bot
if I'm removing it, then the autocomplete is working fine
is it possible use PCMVolumeTransformer to get user’s vc volume and when pressed button 🔊 volume +5 🔉 volume -5?
(i already added buttons , but having problem on get user’s volume)
Show it then
You cant change user volume for sure
oh yah
i discribe wrong
i want change my bot’s volume
Then idk i never worked with audio
okay
so a user can add a specific time into a databse with a command, for example they input 2 days, how can i make it then send an alert when the 2 days have passed and it counts down?
Start a task loop that periodically checks the database for expired datetime entries
how would i update the db when the time expires?
in the task loop itself
I would personally just have a cache of all active time submissions per guild and have a task that checks every minute whether certain times have past and then alert them
so a local cache and a submission in your db, so when your program crashes or needs to restart, it can get a one-time cache again from the db
code structure wise if you were to go for this: create a class that sets up both this task and can add entries to the cache
so that you can use instance variables, easy to work with
you dont want to set Future.wait() or wait_for()'s for this
@haughty dagger what are you cooking up.
That sounds expensive
what would u do then
lol
Can't you do something like keep the futures in a dictionary and when you're closing the bot you keep the elapsed time?
it is not adviced to work with Futures for long running code
like 2 days for instance here
Why is that?
potential resource constraints
hence why i was like
a single task per shard (which would be up to 1000 servers max around that)
seems better than having a Future object with a wait_for for each individual submission
Commands for managing your reminders.
i am not sure either what the best option would be, but i would go for this personally over many Futures
its open sourced sooo
they use an API
or thats just forl ogging
they also make use of a Scheduler
def schedule_reminder(self, reminder: dict) -> None:
"""A coroutine which sends the reminder once the time is reached, and cancels the running task."""
reminder_datetime = isoparse(reminder["expiration"])
self.scheduler.schedule_at(reminder_datetime, reminder["id"], self.send_reminder(reminder))
seems like this is the tool they use
async def _await_later(
self,
delay: int | float,
task_id: abc.Hashable,
coroutine: abc.Coroutine
) -> None:
"""Await ``coroutine`` after ``delay`` seconds."""
try:
self._log.trace(f"Waiting {delay} seconds before awaiting coroutine for #{task_id}.")
await asyncio.sleep(delay)
# Use asyncio.shield to prevent the coroutine from cancelling itself.
self._log.trace(f"Done waiting for #{task_id}; now awaiting the coroutine.")
await asyncio.shield(coroutine)
finally:
# Close it to prevent unawaited coroutine warnings,
# which would happen if the task was cancelled during the sleep.
# Only close it if it's not been awaited yet. This check is important because the
# coroutine may cancel this task, which would also trigger the finally block.
state = inspect.getcoroutinestate(coroutine)
if state == "CORO_CREATED":
self._log.debug(f"Explicitly closing the coroutine for #{task_id}.")
coroutine.close()
else:
self._log.debug(f"Finally block reached for #{task_id}; {state=}")
seems like they use asyncio sleep... yuck
ill look into that interesting stuff
I guess since it's private and not many people use it much anyway
wym
_await_later is the core of Scheduler's scheduler
it seems
Already saw that
then wdym with this
I mean exactly what I said
its a private method yea because youre supposed to use schedule_at which uses _await_later
Yes?
ok but then whats the point of this
I wonder
but ig for each submission, a task would be created with an asyncio sleep activation
which seems ugly to me
but must be more efficient than iterating through a large dictionairy ig
issue with mine is that it requires a minute+ and you cant schedule for 30 seconds
is there a reference online for all possible app_commands decorators that i could add
discord.py rtd doesnt seem to have any
wow, completely read over that then, tysm
yw :)
A hands-on guide to Discord.py
ive got this that works out when a message should send after the time has expired but idk how i would do that from my db
d = datetime.strftime(datetime.now(timezone(timedelta(hours=3))) + timedelta(t), '%d-%m-%Y').split("-")
date = datetime(day=int(d[0]), month=int(d[1]), year=int(d[2]), tzinfo=timezone(timedelta(hours=3))).strftime('%d/%m')```
anyone could help me with a discord.py discord bot? it really seems easy with sending embeds and deleting them
nothing more
but its been 3 days and im turning crazy
why is discord seeing htis as invalid emoji:
ZELLE = ''
i do not see what is wrong with it
.add_field(name='Supported', value=f'{Emojis.ZELLE}}')
the bot and emojis are both in the same server
u need an 'a'
thats for animated emojis
oh yh mb
i have exactly the same shit on another bot and it works fine there
im literally copy pasting it
it works for me but my bot is erroring
the emoji exists in the server?
try
.add_field(name='Supported', value=f'{ZELLE}')
?
class Emojis:
ZELLE = ''
CASHAPP = ''
BTC = ''
LTC = ''
are they in embeds
huh
?
delete the instance then
it has no reason to not work, its literally here
yes theyre in embeds, but i should be able to use emojis anywhere
this is the way we've always used emojis with bots
?
what error are u getting?
where is the error
can an embeds field value be just an emoji?
it can
you can use emojis anywhere, doesnt matter
.add_field(name='Supported', value=discord.PartialEmoji.from_str(Emojis.ZELLE))
imma print all emojis in my guild rq
if you want show me how the embed is supposed to be i'll make one for you
ill try this but, it makes no sense that mine dont work
i have many hours in discordpy. dont worry man haha
oh
No it won't work hmm
(<Emoji id=1172260354701668392 name='arrowemoji' animated=False managed=False>, <Emoji id=1173374162576879617 name='coding' animated=False managed=False>, <Emoji id=1180535608809099294 name='cashapp' animated=False managed=False>, <Emoji id=1180535612244234341 name='zelle' animated=False managed=False>, <Emoji id=1180535854100398140 name='ltc' animated=False managed=False>, <Emoji id=1180536077421920407 name='btc' animated=False managed=False>)
i use description for embeds
discord issue then ig
could help me really quick please?
@cloud dawn its a discord issue
What am I doing wrong 😭
yea sure send code
it is kinda long but i can explain to you in dms if you dont mind!
i dont accept dms
okay i'll send it here
send your terminal cd
can you show your cli
i want to see its current location and whether u activated a venv
ok
!charinfo :zelle:
\u003a : COLON - :
\u007a : LATIN SMALL LETTER Z - z
\u0065 : LATIN SMALL LETTER E - e
\u006c : LATIN SMALL LETTER L - l
\u006c : LATIN SMALL LETTER L - l
\u0065 : LATIN SMALL LETTER E - e
\u003a : COLON - :
\u003a\u007a\u0065\u006c\u006c\u0065\u003a
Wait
My current location is in the Main.py, I did not activate a venv
@unreal pilot So basically there is an embed you'll find called "Deal Amount", that's its title, I want it to be deleted after the "Correct" & "Incorrect" buttons are pressed, it works for the other embeds, other embeds are getting deleted, but only the "Deal Amount" embed doesn't get deleted
@unreal pilot Does it work on a normal message instead of an embed?
I can tell you what the code does exactly
ill have a try
@leaden flint ill help u in like 4-5 mins ok?
all good, im glad you accepted to help me!
worked for a regular message @cloud dawn
super odd behaviour
using Emojis.ZELLE
its not working in an embed field as far as ive tested
Discord doesn't render a lot in embeds.

can someone help?
Where is deal_amount_embed attemted to be deleted?
Pure chatgpt vibe 😔
A discord.py extension including useful tools for bot development and debugging.
It's not
it's not implented
Ah read it wrong
deal_amount_embed variable variable exists
ive always used emojis with no issues, so idk
but, it doesnt get deleted, i tried to make it get deleted but to no avail
self._ZELLE = discord.utils.get(interaction.guild.emojis, name="zelle")
self._CASHAPP = discord.utils.get(interaction.guild.emojis, name="cashapp")
self._BTC = discord.utils.get(interaction.guild.emojis, name="btc")
self._LTC = discord.utils.get(interaction.guild.emojis, name="ltc")
even did this, still 'invalid emoji' 💀
what the fuck is discord on man
Well I don't know the entire structure but a fast way would be to save the message object and use it in the other view.
Is it happening on a component?
yes
no
unless an Embed is considered a component (i doubt it?)
cant use emoji's in descriptions and the field's value
so it must be a discord api issue
Huh weird it shouldn't raise any error tho it should be a plain text
exactly
Could you send full traceback?
no because it contains my real name
raise HTTPException(response, data) discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body In components.0.components.0.emoji.name: Invalid emoji
Um just remove those oarts?
i got this for u haha :d
Need full 
File "C:\Users\\Desktop\Isaaa_TICKETHANDLER\cogs\tickethandler.py", line 84, in robuxAmount self._calc_robuxAmount: discord.Message = await self._ticket_channel.send(Embed(title='Estimated Costs', description=f'For gamepass, plugin or shirt purchases:\n> $ **-**\n\nFor in-game gifting:\n> $ **-** {self._ZELLE}', color=Config.CONST_EMBED_COLOR).add_field(name='Supported Payment Methods', value='hi'), view=self._ConfirmRobuxAmountView) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\\Desktop\Isaaa_TICKETHANDLER\venv\Lib\site-packages\discord\abc.py", line 1561, in send data = await state.http.send_message(channel.id, params=params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\\Desktop\Isaaa_TICKETHANDLER\venv\Lib\site-packages\discord\http.py", line 745, in request raise HTTPException(response, data) discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body In components.0.components.0.emoji.name: Invalid emoji
From this error i will just assume the component is a button
Aw man you didnt even initialize the view
? this is an instance
view=self._....()
i already have initialized it, dont worry
Put ()
Oh alr
its not a class
self._ConfirmRobuxAmountView = ConfirmRobuxAmountView(Cog=self.bot)
bit of a hacky naming convention
This is a problem about the emoji in the first button in your view
Could you share the first button decorator (and callback if u can)
Mhm
class ConfirmRobuxAmountView(discord.ui.View):
def __init__(self, Cog):
self.Cog = Cog
super().__init__(timeout=None)
@discord.ui.button(style=discord.ButtonStyle.green, label='confirm', emoji=':white_check_mark:', disabled=True)
async def Continue(self, interaction: discord.Interaction, button: discord.ui.Button):
self.Cog.interaction_future.set_result(True)
@discord.ui.button(style=discord.ButtonStyle.green, label='change', emoji=':white_check_mark:', disabled=True)
async def Continue(self, interaction: discord.Interaction, button: discord.ui.Button):
self.Cog.interaction_future.set_result(False)
Aren't you supposed to put the raw emojis
^^^
taht would make a ton of sense
Yeah whatever, doesn't work on mobile
also i noticed i got a duplcation of function names, fixed that as wel lnow
ok so outcome: im gonna harm myself
because ive just wasted an hour for something that isnt even the error
!charinfo :white_check_mark:
!charinfo ✅
\u2705 : WHITE HEAVY CHECK MARK - ✅
\❌
Bro wtf is discord's prob, thanks krypton
haha
Can just send the emoji 
skill issue
Thats why told you to share full traceback
No need to escape for the command
Agreed tbh
I didnt know i can just pass the emoji in charinfo
works now
you are totally right, completely read over the issue of 'component'
i mean it makes more sense to pass the emoji itself
Idk when i first did, it used to show the letters' unicode of the emoji name idk actually lol
a user can input a time in a db and i want it to send a message when the time is up, like they input 2 days etc, i have this so far
d = datetime.strftime(datetime.now(timezone(timedelta(hours=3))) + timedelta(t), '%d-%m-%Y').split("-")
date = datetime(day=int(d[0]), month=int(d[1]), year=int(d[2]), tzinfo=timezone(timedelta(hours=3))).strftime('%d/%m')```
Hey bro
File "/home/runner/LightMonumentalLoopfusion/.pythonlibs/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 941, in _load_from_module_spec
setup = getattr(lib, 'setup')
AttributeError: module 'cogs' has no attribute 'setup'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/runner/LightMonumentalLoopfusion/.pythonlibs/lib/python3.10/site-packages/jishaku/features/management.py", line 61, in jsk_load
await discord.utils.maybe_coroutine(method, extension)
discord.ext.commands.errors.NoEntryPointError: Extension 'cogs' has no 'setup' function.```
help?
hello are you good on discord.py
idk where to start it ykwim
so im getting confused
Does it even matter? Just ask your question
Search on Google how to setup basic cogs
i want an embed to be deleted when I click on a button
this is the code, the button is "Correct" when both people choose "Correct" for the 2nd one
im paying 10$ paypal whoever helps me
um actually its an extension

!rule 9
me when !rule pay
alr well idk how is that against the tos in general or is that supposed to be illegal?
is paying illegal now
or hiring is considered trafficking now
i know, but it doesnt make sense why when someone include money its always count as illegal?
it doesnt make any sense to complain about rules you accepted
i accepted them to complain
😎
It’s not illegal. This server is supposed to be for learning and discussion, not recruitment. If paid recruitment was allowed there would be tons of spam daily
tbh i included money because no one would help without money
why would someone offer their time for me for free
everyone is on their own after all
i imagine it wouldn't foster a good community if we had people wanting bounties for help, but perhaps the admins have other reasons for its existence
regardless, you want the confirmation to also delete your deal amount message? have you tried passing the deal message to your AmountConfirmationView?
Nobody in this server is paid. Everybody is volunteering their time
oh let me try, you mean i change its position from the try_delete_messages() function to the AmountConfirmationView class?
Can I tell you what the code does?
If you don't mind
change the position of what, sending the message? surely you still want to send the message at the same place, but im saying you can give the message object returned from interaction.channel.send() to AmountConfirmationView so it can delete it afterwards
the embed
okay here what the code basically do
I can record a video of the process
File "/home/runner/LightMonumentalLoopfusion/.pythonlibs/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 941, in _load_from_module_spec
setup = getattr(lib, 'setup')
AttributeError: module 'cogs' has no attribute 'setup'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/runner/LightMonumentalLoopfusion/.pythonlibs/lib/python3.10/site-packages/jishaku/features/management.py", line 61, in jsk_load
await discord.utils.maybe_coroutine(method, extension)
discord.ext.commands.errors.NoEntryPointError: Extension 'cogs' has no 'setup' function.```
Hey, how can I make it where if a user joined a server called "A" it sends the welcome message in guild "A"? I tried making this but it keeps on sending it to the main server.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
here is basically a video of what the code does, you dont have to read all that haha
as you can see the "Deal Amount" doesnt get deleted
anyone could help me with this?
can someone pls help?
Sup yall, I have a command /ticket setup, a hybrid_command that creates a modal with some options.
Docs reference: https://discordpy.readthedocs.io/en/stable/interactions/api.html?highlight=modal#channelselect
Tried ✅ :
- Using TextInput instead of ChannelSelect
Error:
Command 'setup' raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In data.components.1.components.0: Value of field "type" must be one of (4,).
Code for TicketSetupModal:
class TicketSetupModal(discord.ui.Modal):
"""A class that represents a ticket setup modal.
"""
def __init__(self):
"""Initializes the modal."""
super().__init__(title="Ticket system", timeout=60.0)
# Ticket options
print("Ticket options selection 1/2")
self.ticket_options = discord.ui.TextInput(
label="Ticket options",
style=discord.TextStyle.paragraph,
placeholder="type in the ticket options separated by **,**",
required=True,
)
self.add_item(self.ticket_options)
print("Ticket options selection 2/2")
# Channel selection
print("Channel selection 1/2")
self.channel_select = discord.ui.ChannelSelect(
placeholder="Select ticket channels",
channel_types=[discord.ChannelType.text],
min_values=1,
max_values=2,
)
self.add_item(self.channel_select)
print("Channel selection 2/2")
# Default embed name
print("Embed name selection 1/2")
self.default_embed = discord.ui.TextInput(
label="Main embed name",
placeholder="Type in the name of the main embed utilized here",
required=False,
style = discord.TextStyle.paragraph,
)
self.add_item(self.default_embed)
print("Embed name selection 2/2")
async def on_submit(self, interaction: discord.Interaction):
pass
You can't add selects to modals
I thought you could since it has an add_item and Item can be any of the following: https://discordpy.readthedocs.io/en/stable/interactions/api.html?highlight=modal#discord.ui.Item
that's very sad, anyways thx.
Makes sense, I hope they add selects to Modals, would be real cool, and they already have the system in for it.
I am not internet-wise enough for those terms haha
Read The Fucking Manual
Very true
how do i keep the item selected in dropdown menus after disabling it
is this even a thing?
or should i just add a field that gives visual feedback that a certain type was selected
Set the placeholder when disabling it.
To the chosen option ofc
yea, ill just set the placeholder value the same as the option label
i should commit an edit right?
yea i should
that worked nicely, thanks 
custom emojis dont work
Considering you have the custom emoji for Litecoin, should be easy to know how to fix
notice how its not disabled there
discord.SelectOption(label="Litecoin", emoji=Emojis.LTC, description="Complete the order with Litecoin `LTC`.", value="LTC"),
vs
Select.placeholder = f'{option.emoji} {option.label}'
;)
Well, you got your answer
it wasnt a question, just more of a heads up for people who are also working with Selects
you have a small spelling mistake in your article
the rest is cool tho
hey guys
what course could i use to learn about discord bot development
and how can i make a news bot?
what api and code would i use?
await user.send(embeds=embedList)
what can i do if not both of the images are sended
if im doing like this:
await user.send(embeds=[original_embed, embed])
only the first embed is sended
can somebody helps me on how i can make a bot delete a certain message he sent after something happens? really as simple as that
are you familiar to discord.py
?
i mean it works on other messages
there is a specific message tht doesnt want to be deleted
its because i didnt implent a deletion process for it, but idk how to anymore, can i show you in dms?
why is message.embeds printing as [] when the message has an embed
!d discord.Message.embeds
A list of embeds the message has. 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.
If
Intents.message_contentis not enabled this will always be an empty list unless the bot is mentioned or the message is a direct message.
No, and rule 5
What even is an unban bot
i am looking to track the "amount" or "progress" of a discord.File object being sent into a channel, is this possible?
i know that discord.File objects have a fp attribute but its method tell() doesnt update even while sending
what
wdym progress
!pip humanize
Fk wrong channel, ignore me ;-;
banned
the total amount of "bytes" that have been sent
So how many bytes the file is?
I was asking if you wanted to see how many bytes the file was
i am reading the file before hand so i know how large it is
the total amount of "bytes" that have been sent
when you say bytes that have been sent, do you mean from the bot overall?
no
What you're asking isn't very clear
discord.File objects don't have a tell() method
!d discord.File
class discord.File(fp, filename=None, *, spoiler=..., description=None)```
A parameter object used for [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send) for sending file objects.
Note
File objects are single use and are not meant to be reused in multiple [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send)s.
Well lemme say whats he asking
He asking if its possible to show the progress bar of a file being sent
Oh, like uploading the file
i know this thats why i said they have a "fp" attribute that has a "tell" method
Yup
No that's not possible
Yeah xd
i mean when i call
await channel.send(file = discord.File(buffer, "test.txt"))
i want to check how much of the file has been uploaded
well, built in it's not, but there is a hacky iffy way
How would you even see
Really?
When the API is called it's out of your hands
We can maybe just make own progress bar with current net speed and total size
all i was asking is if it was possible
But it really depends on discord servers
Yeah that's what I was thinking as well, but it would depend on a ton of factors
Wouldn't be reliable at all
Hmm
the discord.FIle object has a bytesio buffer and that has a "tell" method but it doesnt seem to update atall
When the API call is made it's out of your hands
very sure
you can only just show the rate of you uploading it to the discord server, not the server giving you the progress
!d
im not asking for the server to give me progress
Oh
i want to track it from the bots code
You should've elaborated more then
well duh i know that, im talking to that guy
Personally I wouldn't really go for it as it's not really reliable, but if you want to do it the hacky way that's up to you
lemme reset
when i am uploading a discord.File object to discord, i want to print to the console the percentage that the file is uploaded
surely there is someway to track the amount of bytes read from a io.BytesIO object
!d io.BytesIO
class io.BytesIO(initial_bytes=b'')```
A binary stream using an in-memory bytes buffer. It inherits [`BufferedIOBase`](https://docs.python.org/3/library/io.html#io.BufferedIOBase). The buffer is discarded when the [`close()`](https://docs.python.org/3/library/io.html#io.IOBase.close) method is called.
The optional argument *initial\_bytes* is a [bytes-like object](https://docs.python.org/3/glossary.html#term-bytes-like-object) that contains initial data.
[`BytesIO`](https://docs.python.org/3/library/io.html#io.BytesIO) provides or overrides these methods in addition to those from [`BufferedIOBase`](https://docs.python.org/3/library/io.html#io.BufferedIOBase) and [`IOBase`](https://docs.python.org/3/library/io.html#io.IOBase):
Just keep in mind there are upload limits
25MB by default, and it goes up to 50/100 depending on the servers boost tier
pretty hacky, you can only get to update everytime read is called, without tapping into the internal ```py
class TestIO(io.BytesIO):
def init(self, initial_bytes, length):
super().init(initial_bytes=initial_bytes)
self.length = length
def read(self, size=None):
print(f"uploading {self.tell()}/{self.length}")
return super().read(size)
_bytes = await _ctx.author.display_avatar.read()
size_of_file = len(_bytes)
a = TestIO(_bytes, size_of_file)
await _ctx.send(file=discord.File(a, filename="test.png"))
Traceback (most recent call last):
File "/home/runner/LightMonumentalLoopfusion/.pythonlibs/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 941, in _load_from_module_spec
setup = getattr(lib, 'setup')
AttributeError: module 'cogs' has no attribute 'setup'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/runner/LightMonumentalLoopfusion/.pythonlibs/lib/python3.10/site-packages/jishaku/features/management.py", line 61, in jsk_load
await discord.utils.maybe_coroutine(method, extension)
discord.ext.commands.errors.NoEntryPointError: Extension 'cogs' has no 'setup' function.
help
where is your setup function?
every cog should have a setup function, with in the module/extension itself or you can put it in init.py in the same folder
and python will look for it there first
so i put the setup function in init.oh that's inside the module folder then it should be fixed?
where are you running the bot from
repl
it's by itself not in a folder
did you write your cogs as their own class ?
yeah
at the bottom?
you need to pass the instance of the bot to the cog
first in the class attributes
you have an init function for the cog right
yeah
ok, add bot attribute self.bot = bot
it's already below the init function
now at the bottom of the cog code
""" Add the cog to the bot."""
await bot.add_cog(CogName(bot))```
class afk(commands.Cog):
def init(self, bot: commands.AutoShardedBot):
self.bot = bot
alright
so like this?
await bot.add_cog(afk(bot))```
yep
now i just add that but the class name different in all the files i have in cogs?
if that makes sense
how are you loading the cog
make a function to load your cogs in your main file
and you will need to await bot.load_extension(path_to_cog)
oh also
in the same location as the cog file
print(f"{extension}.py has been loaded")```
where you just added the setup function, create a blank __init__.py
that lets python know that it is a module to be loaded
@glossy mauve thats correct if the cogs are in a subfolder one level deeper like mybot/cogs/cog.py
as long as {extension} is called 'cog'
ohh wait this the load ?
bot.load_extension("jishaku"), print(f"odd should be on luh dude"), await bot.tree.sync()
yep if thats the name of your cog
is jishaku your cog
wym
Id recommend go through this step by step https://discordpy.readthedocs.io/en/latest/ext/commands/extensions.html
!pypi jishaku
A discord.py extension including useful tools for bot development and debugging.
await user.send(embeds=[embed, original_embed]) # Create a direct message channel with the user
why aint both embeds send
does disnake feature slash command checks?
can't seem to find any documentation for it, and commands.check appears to be only for message commands.
it does work on slash commands
yall
my bot doesnt works on servers, like when i type !hello my bot doesnt responds, but in pm it works why?, can yall help me with this problem.
!message-content-intent
The Discord gateway only dispatches events you subscribe to, which you can configure by using "intents."
The message content intent is what determines if an app will receive the actual content of newly created messages. Without this intent, discord.py won't be able to detect prefix commands, so prefix commands won't respond.
Privileged intents, such as message content, have to be explicitly enabled from the Discord Developer Portal in addition to being enabled in the code:
intents = discord.Intents.default() # create a default Intents instance
intents.message_content = True # enable message content intents
bot = commands.Bot(command_prefix="!", intents=intents) # actually pass it into the constructor
For more information on intents, see /tag intents. If prefix commands are still not working, see /tag on-message-event.
!rule 6
<@&831776746206265384> does that count as an advert?
How can you make this?
is that in bot profile?
no a bot command
you want to know how to make a slash command?
no how to show a command like that
yes
How can you get the command id
The application command’s ID.
app command has an id attribute
but if you are using a bot you can also already get full mention message
!d discord.app_commands.AppCommand.mention
property mention```
Returns a string that allows you to mention the given AppCommand.
How to make help pannel like this
!customhelp
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
#bot-commands
'''@slash1.autocomplete('iskola_neve')
async def slash1_autocomp(interaction:discord.Interaction,courent:str)->list[app_commands.Choice[str]]:
await interaction.response.defer()
options=[]
global KLIK_OPTIONS
if 'kliks' not in globals():
KLIK_OPTIONS=get_kliks()
for name, value in KLIK_OPTIONS.items():
if courent.lower() in name.lower():
options.append(app_commands.Choice(name=name,value=value))
if len(options)>=7:
break
print(options)
return options'''
why does this not work randomly for some str 's?
Whats the best library. Discord.py is really outdated according to a number of people.
#discord-bots message
discord.py is being maintained by the same author again so the library isn't "outdated" at this point in time
you can also look at the repository https://github.com/Rapptz/discord.py to see what activity is going on
any library is good the only differences are in structures meaning - preferences
See thats what i thought. Looking at almost any other lib means losing a lot of feaures. Like i dont believe modals are even supported on most things at this stage.
err the popular dpy forks like disnake, nextcord, and py-cord all support it
i would expect this to not work at all given that autocomplete interactions shouldn't be deferred, but other than that you'll need to debug your code and see what options it's trying to filter through
if is good for szil but not for szilá, szilág ... all the way to szilágyi e and even returns valid list[Choice] objs i know it bc i print it in terminal but discord says failed loading options also no errors in console
you don't really mean that
sadly thats the truth
ofc there are worse ones like py-cord
but yeah
no😈
okay okay i didnt want to say it but yeah
nextcord is a really good one and the best
so it does print the correct options but the interaction fails? have you tried removing the defer() call?
lmao
no
best py version to create discord bots?
discord.py has the largest community which helps if ur a beginner if u have some experience you can make a bot with just about any library
I am trying to check if a message is sent but I forgot what the code was. I remember it had to with with wait_for
Are you trying to wait for a message?
Yes
You would use .wait_for("message") then
def check(m):
return m.content == m.content and m.channel == whitelist_ch
discord_name = await bot.wait_for('message', check=check)``` is this ok?
whitelist_ch is the channel the code is running
m.content == m.contentwill always be true. The content of the message will always be equal to the content of the message- What is the type of
whitelist_ch?
text channel
Should be fine then
asyncio.sleep was working with ms or seconds?
It takes in seconds just like time.sleep
Is there any Library that is still being actively maintained ?
or is discord.py still maintained ?
Resumed and maintained by the same repository maintainer
i did and without the defer i added the defer bc i thought the problem is the code times out altho it prints the thing in like less than a sec
https://i.imgur.com/xwJvf2m.png is this correct?
It's not correct, nor incorrect
You're syncing globally, that takes up to an hour.
For dev purposes you'd sync it to one debug guild. Then it's instant but only available for that guild.
If you waited for an hour or so yeah or they already existed.
Why not?
I recommend checking this out -> https://fallendeity.github.io/discord.py-masterclass/slash-commands/
Here is a more detailed guide as well on syncing - > https://fallendeity.github.io/discord.py-masterclass/hybrid-commands/#syncing-commands
!d discord.app_commands.CommandTree.command
@command(*, name=..., description=..., nsfw=False, guild=..., guilds=..., auto_locale_strings=True, extras=...)```
A decorator that creates an application command from a regular function directly under this tree.
I have a need to run discord_client.run("my_token") inside my async main function, but doing so seems to cause it to try and spin up it's own event loop to run inside.
Is there a way to tell discord.py/disnake to use the currently running event loop, or to specify which loop it should run in?
! discord.Client.start oops
!d discord.Client.start
await start(token, *, reconnect=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A shorthand coroutine for [`login()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.login) + [`connect()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.connect).
yeah I just found this, my bad
This is a Python discord server
Give me bot Instagram ban unban
Bro you’ve literally asked like 5 times nobody is going to give you one, or even know what you’re talking about
https://paste.pythondiscord.com/IOMQ
The issue with code is there, Anybody please help!
Yes
Python really
what is the issue/error?
What issue?
In the markdown file...
after I catch the pokemon it still says it fled
Very specific
The markdown file didnt upload Idk why
Uhhh
The main.py file. When I use the catch command, To catch the pokemon. It should not say it has fled, While it does for some reason
@vocal snow @naive briar ^
You're checking self.spawned_pokemon in your tasks loop
But you are writing the spawned Pokemon to a json file
And updating the json file in the catch command
I wouldn't really recommend loading the entire json file each time the command is used, not sure why the spawned Pokemon would need to be saved to disk either
I think it would be better if you just used the self.spawned_pokemon dict throughout
# this is checking if the pokemon is in self.spawned_pokemon[server_id]
if {'name': pokemon_name, 'message_id': message.id} in self.spawned_pokemon[server_id]:
# but your catch command only changes the JSON file, not the self.spawned_pokemon dict
spawned_pokemons[server_id] = [pokemon for pokemon in spawned_pokemons[server_id] if pokemon['name'].lower() != pokemon_name.lower()]
with open('spawned_pokemons.json', 'w') as file:
json.dump(spawned_pokemons, file, indent=4)
Holy moly, put learning databases as a next learning curve point
Did they change how adding slash commands to servers works?
Every method I've tried under the sun does not work
All functions just silently fail, and they only get added to whatever internal representation of state the bot is keeping track off
I can see in my Integrations the bot doesn't have a slash commands icon next to it like the other bots with one, but the bot was invited with the permission to create them?
What library and what code
Also make sure you have applications.commands scope
disnake
Yeah, the bot has the scope
Disnake should sync automatically. Please show your code and version of disnake you are using
Contribute to Starz0r/livenow-discord development by creating an account on GitHub.
you can see my latest attempts here
Too many CONSTANTS so hard to read 😞
way to many
From what I can see you are just not ensuring you respond to interaction
do I have to respond in all code paths in a interaction?
If twitch_user is not None, you never respond to interaction
Yeah, and you have to do that within 3 seconds or defer
Also there's shortcut for responding in disnake, just inter.send instead of inter.response.send_message
made these changes and it still can't use the commands in the server
So the commands are not displayed?
Make sure you have permissions and try restarting your client
i've also tried manually passing in the guild_id on test_guilds and this also hasn't made a difference
tried restarting it multiple times already
are there specific permissions or intents it needs for slash commands to be registered?
class disnake.Intents(value=None, **kwargs)```
Wraps up a Discord gateway intent flag.
Similar to [`Permissions`](https://docs.disnake.dev/en/latest/api/permissions.html#disnake.Permissions), the properties provided are two way. You can set and retrieve individual bits using the properties as if they were regular bools.
To construct an object you can pass keyword arguments denoting the flags to enable or disable. Arguments are applied in order, similar to [`Permissions`](https://docs.disnake.dev/en/latest/api/permissions.html#disnake.Permissions).
This is used to disable certain gateway features that are unnecessary to run your bot. To make use of this, it is passed to the `intents` keyword argument of [`Client`](https://docs.disnake.dev/en/latest/api/clients.html#disnake.Client).
New in version 1.5.
Nvm you don't need any intents for interactions
i'm going to be real
never had this much problem registering slash commands on a different bot i built in rust
compared to that, this is completely opaque, and i can't believe there's no way to get better logging feed back in the terminal or something
setting the sync_commands_debug flag promises to actually display more logging when trying to sync slash commands, but it appears to do actually nothing at all
You have some weird constructions there and it might be cause of the way you are starting the bot
Try enabling advanced logging as they say in docs
Hey! I'm new, alright that's obvious and I really wanna do my own Discord bot, what is the best way to learn Phyton for beginner? Not even sure if I'm right here 😂 I googled Python and ended up here in this server 😅
pipenv run .\src\main.py 2>&1 | rg "slash"
0 results
kinda crazy
You haven't enabled logging
i did
Have you
I turned it all the way up to debug
DEBUG:disnake.http:A rate limit bucket has been exhausted (bucket: None:None:/users/@me, retry: 0.001).```
only possible relevant lines
everything else is about the heartbeat after that
Oh, you are ratelimited?
There's limit to daily connections but it's 1000 iirc
WARNING:disnake.gateway:Shard ID None heartbeat blocked for more than 60 seconds.```
this keeps happening to where it disconnects me from the gateway, so i have to just auto-reconnect instead
everything is async, and the twitch specific stuff is ran on it's own thread, on it's own event loop
which isn't even having it's code paths executed anyway, because i can't access them without the slash command
the fact that the slash command isn't even showing up in the LOGS, sorta tells me something is wrong with disnake's sync process
what I can see if I iterate through the bot's slash command state
for cmd in DISCORD_BOT.slash_commands:
LOGGER.info(cmd.name)
I can see that it's added internally, but no way to query it's sync status
similarly, it's not even getting outputted to logs as if it were attempting to anyway, because it probably isn't
Still your way of running it is kinda weird
The wrapping the coroutine in a task, or something else?
For example
t = create_task(start(...))
await t
You can just await start(...)
Running it in my own event loop should be supported, according to how the .start() method exists.
Since you don't need the task anywhere further
the what, iirc there's a loop argument if you want to pass it
!d disnake.ext.commands.Bot
class disnake.ext.commands.Bot(command_prefix=None, help_command=<default-help-command>, description=None, *, strip_after_prefix=False, **options)```
Represents a discord bot.
This class is a subclass of [`disnake.Client`](https://docs.disnake.dev/en/latest/api/clients.html#disnake.Client) and as a result anything that you can do with a [`disnake.Client`](https://docs.disnake.dev/en/latest/api/clients.html#disnake.Client) you can do with this bot.
This class also subclasses [`GroupMixin`](https://docs.disnake.dev/en/latest/ext/commands/api/prefix_commands.html#disnake.ext.commands.GroupMixin) to provide the functionality to manage commands.
I rarely work with parallel stuff in asyncio but I once made a thing like async chess player
And I remember structuring it very differently
yes you can
disnake.Client is accepting it and Bot is a subclass of Client
unwrapping the task doesn't even seem to solve the heartbeat issue
I could just chalk this up to being on a VPN, but running this on a production VPS, it has the same issue and would eventually just permanently disconnect.
what I'd like to know is why none of the logging even seems to mention slash commands in the slightest?
I can deal with the gateway being flakey by just restarting it every 45 seconds, not a great solution, but it works around the garbage
why doesn't disnake even try syncing my commands
Disnake things?
if I have to tracemalloc, I'm sorry but I'll just go back to prefix commands
this isn't even a complex setup, if it can't handle this, then i guess i built the project on the wrong foundations
also, like, what's blocking?
nothing in my code is blocking, so are you referring to some portion of disnake has blocking code?
or are you referring to something else
Average disnake slash command experience
it doesn't
removing twitch calls from the code does not fix anything either
which is what you're saying is implying
Ok I will get home and see this on PC
Cause this is more complex than I thought at first
Nah bro that's average two async libs combining, happens every time
@faint stone What's the problem?
slash commands don't register, gateway heartbeats are ignored
Are you using a specific CommandSyncFlags object or permissions?
I don't apply any permissions since the command should be usable by anyone
If you want to do some review for yourself, the repository is here #discord-bots message
Made some more changes, but I haven't pushed them since they don't change the outcome currently
@faint stone you tried snipy's solution?
Passing EVLOOP to loop kwarg of InteractionBot and then starting via await bot.start(...) in main
huh, this does appear to fix heartbeats getting ignored by the gateway
slash commands still broke tho
Also ik I already mentioned it, but your naming convention of constants makes it harder to read. You'd typically name variables in UPPER_SNAKE_CASE if they are primitives, ie don't have any non-static methods. Maybe not correct formulation but uh
MY_SERVER_ID = 12345678901234567 # constant
bot = InteractionBot(...) # not a constant
Could you show full logs
From disnake
im reading documentation on slash commands for disnake, and this looks correct doesn't it.
or is their something I'm missing or could do better.
@bot.slash_command(description="get a userr's avatar")
async def avatar(inter: disnake.AppCommandInteraction, user: disnake.User) -> None:
avatar_url = user.display_avatar.url
await inter.response.send_message(f"{user.name}'s avatar: {avatar_url}")
Yeah, there's shortcut to inter.response.send_message which is basically inter.send
interesting, any differences or just a simple shortcut
Your code is correct though and if you like this way of sending messages you can keep it this way
send does response.send_message if interaction hasn't been responded to, if it has, then followup.send
!d disnake.Interaction.send
await send(content=None, *, embed=..., embeds=..., file=..., files=..., allowed_mentions=..., view=..., components=..., tts=False, ephemeral=..., suppress_embeds=..., flags=..., delete_after=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message using either [`response.send_message`](https://docs.disnake.dev/en/latest/api/interactions.html#disnake.InteractionResponse.send_message) or [`followup.send`](https://docs.disnake.dev/en/latest/api/webhooks.html#disnake.Webhook.send).
If the interaction hasn’t been responded to yet, this method will call [`response.send_message`](https://docs.disnake.dev/en/latest/api/interactions.html#disnake.InteractionResponse.send_message). Otherwise, it will call [`followup.send`](https://docs.disnake.dev/en/latest/api/webhooks.html#disnake.Webhook.send).
Note
This method does not return a [`Message`](https://docs.disnake.dev/en/latest/api/messages.html#disnake.Message) object. If you need a message object, use [`original_response()`](https://docs.disnake.dev/en/latest/api/interactions.html#disnake.Interaction.original_response) to fetch it, or use [`followup.send`](https://docs.disnake.dev/en/latest/api/webhooks.html#disnake.Webhook.send) directly instead of this method if you’re sending a followup message.
i don't even think pasting the entire thing is necessary
Better do
after assigning an event loop, the error i was looking for appeared at the top
That will give me clear understanding
paste.rs is a simple, no-frills,
command-line driven pastebin service powered by the Rocket web
framework.
oh so
await inter.send(avatar_url)
ah i see, so inter.send just sends the avatar itself without the link to it.
i think despite setting a loop, the stuff setting up the command is being put in a separate event loop for some reason
if i could get it on the same loop, then it looks like it should be fine?
Disnake should be using the loop given to client throughout all interactions, it's more likely that it conflicts with twitch
I actually think you should not create loop manually at all
Just asyncio.run the main
Libraries typically get the active loop and work with it
there's alot of libs to use, I'd suggest looking them up and see what you prefer.
soo tel me some please
looking them up and see what you prefer.
did u miss this part.
How create a simple discord button, me need this for button2role, how to reate it?
what have u tried, and what lib are you using?
I tried use disnake with class, but this is hard system
Sigma face
# ИМПОРТЫ
import discord
from discord.ext import commands
from settigns import session, select_server
from discord.ui import View, Button
# НАСТРОЙКИ
intn = None #discord.Intents.all()
suntale = commands.Bot(command_prefix=session['prefix'], intents=intn)
@suntale.event
async def on_ready():
# Успешный запуск!
print('')
print(f' ✅ SunTale Bot succesfuly connected with:')
print()
print(f" | ID: {suntale.user.id}")
print(f" | Name: {suntale.user.name}#0")
print("")
# Задаем боту статус
#await suntale.change_presence(activity=discord.Streaming(name="SunTale Network", url=url))
async def button_callback(interaction: discord.Interaction):
await interaction.message.edit(content=f'Последним на кнопку нажал: {interaction.user.name}')
@suntale.command()
async def button(ctx):
try:
view = View(timeout=None)
button = Button(label='Кнопка', style=discord.ButtonStyle.red, emoji="🥑")
button.callback = button_callback
view.add_item(button)
await ctx.send(view=view)
except Exception as e:
print(e)
suntale.run(session['token'])
@blazing condor error
without error
i see no error provided. what is the error.
without error
🤦🏽♂️
?
you still have yet to show me an error.
what's happening vs what're you trying to do exactly.
can you help me?
@blazing condor
@blazing condor
How to dynamically change the name of a button? Seems like button.label aint doing a thing
class InformationView(discord.ui.View):
def __init__(self, lang: str = ''):
super().__init__(timeout=None)
self.lang = lang
@discord.ui.button(
label='Optimize', style=discord.ButtonStyle.blurple,
custom_id='persistent_view:optimize'
)
async def optimization(self, button: discord.ui.Button, interaction: discord.Interaction):
button.label = messages[self.lang]['buttons']['optimize']
await interaction.response.edit_message(embed=create_embed(messages[self.lang]['info']['optimize_title'],
messages[self.lang]['info']['optimize_desc']),
view=BackInformationView(self.lang))
@discord.ui.button(
label='Time', style=discord.ButtonStyle.blurple,
custom_id='persistent_view:time'
)
async def time(self, button: discord.ui.Button, interaction: discord.Interaction):
button.label = messages[self.lang]['buttons']['time']
await interaction.response.edit_message(embed=create_embed(messages[self.lang]['info']['time_title'],
messages[self.lang]['info']['time_desc']),
view=BackInformationView(self.lang))
Set view in edit_message to the current instance of InformationView instead of creating a new one
told you, twitch does no sort of thing
it literally runs in it's own thread and event loop
you can check the source code to see it doing that
also why bring this up when the gateway issue is fixed now
You have another error don't you
if you're talking about the pastebin, that's the only error I have
but this error doesn't stop the bot from running properly, just stops the application from setting slash commands
I've never worked with disnake and i just read over the documentation, setup something real quick and no issue.
removing all the twitch related bits and reducing my main function down to client.run() still causes that exception to be raised at the start of the program
provide me the code at this current point.
there's a repo if you scroll up
hold on
And that’s not the current one is it
it pretty much is, i haven't done anything major
okay, i figured something out
I did this in a blank project with the same token, but used it to create my slash commands with client.run()
once I was done, I could just turn my actual bot back on and it would respond to the commands as if it registered them
which is enough for me
it turns out, creating a event loop of any kind causes disnake startup futures to get bound to the wrong event loop, regardless of if you pass the right one in
going to report this because it pretty much seems like a bug
Does anybody know a good vps for hosting your own bots
!d discord.app_commands.has_permissions
No documentation found for the requested symbol.
@discord.app_commands.checks.has_permissions(**perms)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check) that is added that checks if the member has all of the permissions necessary.
Note that this check operates on the permissions given by [`discord.Interaction.permissions`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction.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).
This check raises a special exception, [`MissingPermissions`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.MissingPermissions) that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CheckFailure).
New in version 2.0...
It’ll raise a MissingPermissions error which you can handle
I’m heading to sleep but there’s an example somewhere in the GitHub on how to create a command specific error handler
It’ll raise an error as well
Anyone here wanna collaborate?
yeah
Ok take a look at this and give me your thoughts or questions.
... Minus the grammatical errors lol I'm designing this on a smartphone
we still discussing discordbots?
am i in the correct discord?
How does one go from level 1 to level 2?
and from level 2 to 3 etc?
also it requires arrows to dictate the flow.
between migrant and citizen, you definitely need something to indicate that they applied, and if they succeed go to citizen if fail, go back to migrant.
is it possible to get a user about me?
No
How can I save a channels overwrites and apply them to a new channel? Any well known methods about it?
can anyone help me with this im getting this error everytime i try to install discord library on my new pc it ran without any issue in my old pc
what python version is that
latest 3.12
ok imma try installing 3.11 then
i have this code:
class MyView(discord.ui.View): # Create a class called MyView that subclasses discord.ui.View
@discord.ui.button(label="Click me!", style=discord.ButtonStyle.primary, emoji=":sunglasses:") # Create a button with the label ":sunglasses: Click me!" with color Blurple
async def button_callback(self, button, interaction):
await interaction.response.send_message("You clicked the button!") # Send a message when the button is clicked
@suntale.command() # Create a slash command
async def button(ctx):
await ctx.send("This is a button!", view=MyView()) # Send a message with our View class that contains the button
And him return this (when i click on button):
discord.ui.view: Ignoring exception in view <MyView timeout=180.0 children=1> for item <Button style=<ButtonStyle.primary: 1> url=None disabled=False label='Click me!' emoji=<PartialEmoji animated=False name='😎' id=None> row=None>
Traceback (most recent call last):
File "C:\Users\Frusi\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ui\view.py", line 427, in _scheduled_task
await item.callback(interaction)
File "mine_bot.py", line 28, in button_callback
await interaction.response.send_message("You clicked the button!") # Send a message when the button is clicked
AttributeError: 'Button' object has no attribute 'response'
Traceback (most recent call last):
File "C:\Users\Frusi\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ui\view.py", line 427, in _scheduled_task
await item.callback(interaction)
File "mine_bot.py", line 28, in button_callback
await interaction.response.send_message("You clicked the button!") # Send a message when the button is clicked
AttributeError: 'Button' object has no attribute 'response'
Interaction comes before button in args
hi
ne 3, in <module>
from discord_slash import SlashCommand
ModuleNotFoundError: No module named 'discord_slash'```
what's up with this ? i can't find the library name
anyone pls help ?
see #discord-bots message , discord_slash is deprecated by both discord.py 2.0's addition of slash commands and the library authors which rewrote it as a standalone library, interactions.py
thanks, ChatGPT needs to keep uplol
eh, even if it had the latest information, there aren't a lot of online resources explaining this anyway
okayyy ;) thxx
I am using autocomplete for my help command and I am passing name of the command and class of the command as a value. But it seems like d.py is forcing me to use str type for my app_command argument.
Is there any way to access the value of app_commands.Choice in autocomplete?
You’re just returning a list of Choices no?
value is a kwarg
no
str
when using autocomplete we cannot set parameter type as app_commands.Choice
'
'
'
'


