5. Do not provide or request help on projects that may violate terms of service, or that may be deemed inappropriate, malicious, or illegal.
#discord-bots
1 messages · Page 385 of 1
depending on the discord library
uhm i wanna get a user object with a user
i meani have a user ID
and i wanna get its data
how...
!d discord.Client.fetch_user
hmmm
await fetch_user(user_id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User) based on their ID. You do not have to share any guilds with the user to get this information, however many operations do require that you do.
Note
This method is an API call. If you have [`discord.Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members) and member cache enabled, consider [`get_user()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.get_user) instead.
Changed in version 2\.0: `user_id` parameter is now positional\-only.
oh
thanks
uhm... onother thing
so we know the id of a channel now we wanna get its webhook....
i wanna make something like amoji function to it
A channel could have several webhooks
What if there are multiple?
!d discord.Client.fetch_webhook
await fetch_webhook(webhook_id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a [`Webhook`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Webhook) with the specified ID.
Changed in version 2\.0: `webhook_id` parameter is now positional\-only.
What you probably want is to make and remember one for your application specifically
Not just pull for any webhook that exists
well what if my application forget that it creates one
Then it should remember it?
well i mean am using json
You should be using a database
Then you only need to make the webhook once and store its url
my pc is a potato
ill use that ones i get better pc
i mean how can i get list of available webhook? if thats posible
i also dont know how to make one so uhm... yeah
That's something worth learning
risking?
It doesn't have to be at least. SQLite is literally just a file format + driver libraries
A bad write to a flat file will corrupt all of your data irreversibly
yeah that makes sence
ill learn that soon
is there a way to get a list of existing webhook?
that will make it super easy
It won't
Because again, a channel can have several. If you want one for your use, you should make it and remember it
i dont want my code to always create one everytime i messed with my json file 🥲
most of the time i dont know what am doing and i just run the code to se if it will work or what
"Mess with"? If you don't trust your data storage why are you storing data to begin with
Data your application relies on to function shouldn't just randomly get invalidated lol
welp i am just year on programing and python 🥲
So let's say you have the list of webhooks on a channel. How do you pick which one is the one you want, if any?
i will pick the first on the list... lol
Which might be a webhook someone else made for some other purpose?
wait the bot can delete a webhook?
i can just create webhook and delete after using....
You shouldn't be constantly spinning these up and down
What are you trying to use it for?
uhm.... i dont know tbh i just wanna play with webhooks
You could just make one manually and hardcode the url in and go nuts
It's just a different way to send messages. It really only serves a purpose if you want a spot where you don't need a connected gateway bot
If you already have a connected bot it doesn't really give you anything you couldn't do by just sending a message normally
maybe i can make it a emoji bot ._. where it will detect the user if he cant use that emoji and the bot will try to make webhook and send the same message with emoji on
If you just want to send a message, you don't need to create a webhook to just send that one message
so webhook on each channel ._.
Just send the message directly...?
how that helps
Because you don't need the overhead of creating a webhook
You just make one api call: send message
well you will have a list of all channels then
i ment is "list of webhooks for all channels"
Why do you care about webhooks still? You can just send messages normally
ig to clean the webhook menu on discord?
wdym "just send messages normally"?
The library lets you send messages directly to channels
You don't need a webhook
!d discord.TextChannel.send
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File) object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list) of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File) objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed) object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list) of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed) objects. **Specifying both parameters will lead to an exception**.
it can copy the user display_name and pfp?
If that's the goal, no
Then I strongly recommend you do what I said initially, which is make a webhook once and remember that webhook
!d discord.TextChannel.webhooks
await webhooks()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Gets the list of webhooks from this channel.
You must have [`manage_webhooks`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_webhooks) to do this.
This is the list of webhooks on a channel if you want it though
You would need a webhook on every channel you want this done on
Not sure what the limits are tbh
i want it to be clean as posible...
This is kind of a bastardization of what webhooks were made for tbh
eh whats the "bastardization"?
They were made for specific external systems to post updates into a specific place in discord
Not for one bot to make a ton of them in every channel just for the sole purpose of mimicking users
You might be able to get this to work, but again I don't know the limits on how many and how often you can make new webhooks
wait its will also get rate limited?
Maybe
. This is using webhooks in an unintended scale
well ill just dont do that then...
Try it and see I guess
its just fun to se the bot allowing me to use emoji that i cant use
Docs I'm seeing say 10 webhooks per server
Rate limit of creating webhooks is unpublished like all endpoints
Rate limit of sending messages through the webhook is well documented but I don't remember off top of head
i forgot what will happen if you got rate limited ....
welp ill go back into another coding session
If you're using the library, it just slows down and stops doing the thing until it's allowed to
Like if discord says "you can only make 5 webhooks an hour", the library will make 5 and then sleep for an hour on creating the 6th (while still operating everything else normally)
It will eventually give up right?
It doesn't keep trying
discord tells you what the limit is and when it will reset
the library just sleeps to respect that
Hi! I’m using next cord and I’m wondering if there is any way to load new slash commands in a server without having to invite the bot again?
(Ping me or dm me when responding I might be asleep)
You just have to restart the bot and Discord
WAIT
FR?
nahhhhhh I’m dumb dumb big dumb

how i can print server all emoji with their id id:name in this format? i think i got it
is there an api function to screenshare?
no
how fast could yo update a message with a new image
without getting rate limited?
Sad
Can bots Screenshare?
I have seen before
Bot accounts do not have access to stream video, only audio
from discord.ext import commands
class `General(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_ready(self):
print(f'Cog {self.__class__.__name__} is ready')
async def setup(bot):
await bot.add_cog(General(bot))
Why doesn't it print that the cog is ready but it does load correctly?
if someone rejoins when the bot is offline, it would not know and still tag them as NOT rejoined?
Member flags are stored by discord, not your bot
hmm, its saying has not rejoined for everyone 😭
lemme force a rejoin
aight nvm it works
hello peeps
how do i sync slash commands to a single guild instead of all of discord with discord.ext?
because it takes forever when im trying to test
It doesn't, it's instant
What's probably happening is you need to refresh your client
is that ` in the code?
no
I have a question, what is the correct place to load cogs, in the setup_hook?
load_extensions? either setup_hook or your own runner function
except on_ready
because?
!d discord.on_ready
discord.on_ready()```
Called when the client is done preparing the data received from Discord. Usually after login is successful and the [`Client.guilds`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.guilds) and co. are filled up.
Warning
This function is not guaranteed to be the first event called. Likewise, this function is **not** guaranteed to only be called once. This library implements reconnection logic and thus will end up calling this event whenever a RESUME request fails.
there's a warning
okey
if not os.path.exists('src/cogs'):
print('Cog folder does not exist')
return
for filename in os.listdir('src/cogs'):
if filename.endswith('.py') and filename != '__init__.py':
try:
cog_name = f'src.cogs.{filename[:-3]}'
await bot.load_extension(cog_name)
print(f'Loaded cog: {cog_name}')
except Exception:
print(f'Failed to load cog: {filename[:-3]}')
traceback.print_exc()
async def main():
await setup_hook()
await bot.start(os.getenv('BOT_TOKEN'))
if __name__ == "__main__":
asyncio.run(main())
``` this is correct?
You calling the method setup_hook in that scenario doesn't do anything
Also consider using pkgutil to look for modules rather than looping over a directory's files yourself
if not os.path.exists('src/cogs'):
print(f'Cog folder does not exist')
return
for filename in os.listdir('src/cogs'):
if filename.endswith('.py') and filename != '__init__.py':
try:
await bot.load_extension(f'src.cogs.{filename[:-3]}')
print(f'Loaded cog: {filename[:-3]}')
except Exception:
print(f'Failed cog: {filename[:-3]}')
traceback.print_exc()
async def main():
await load_cogs()
await bot.start(os.getenv('BOT_TOKEN'))
if __name__ == "__main__":
asyncio.run(main())```?
This currently turns off logging from the library (and doesn't fix the other things I said) but otherwise sure
import pkgutil
async def load_cogs():
if not os.path.exists(os.path.join('src', 'cogs')):
print(f'Cog folder does not exist')
return
for _, filename, _ in pkgutil.iter_modules([os.path.join('src', 'cogs')]):
if filename == '__init__':
pass
try:
await bot.load_extension(f'src.cogs.{filename}')
print(f'Loaded cog: {filename}')
except Exception:
print(f'Failed cog: {filename}')
traceback.print_exc()
async def main():
await load_cogs()
await bot.start(os.getenv('BOT_TOKEN'))
if __name__ == '__main__':
asyncio.run(main())```
Why would it be convenient to use the setup_hook?
If used properly, it sets up logging for you by default and you don't need to spin up an event loop yourself
for example this:? ```py
async def load_cogs():
if not os.path.exists('src/cogs'):
print('Cog folder does not exist')
return
for _, filename, _ in iter_modules(['src/cogs']):
if filename == '__init__':
pass
try:
await bot.load_extension(f'src.cogs.{filename}')
print(f'Loaded cog: {filename}')
except Exception:
print(f'Failed cog: {filename}')
traceback.print_exc()
async def setup_hook():
await load_cogs()
if name == 'main':
bot.setup_hook = setup_hook
bot.run(os.getenv('BOT_TOKEN'))
You shouldn't be stapling methods onto objects directly. This is what subclassing is for
It's also a bit odd that you have one line in your setup_hook which is just calling another method, it's an unnecessary layer of indirection. But otherwise the approach is sound
ok thx
^
IndentationError: expected an indented block after function definition on line 219``` anyone know what it means?
embed = discord.Embed(
title="LOA request",
description=f"{interaction.user} requested a LOA. Supervisor+, ping them and tell them if it's accepted or rejected."
)```
try this
k
worked?
Ye
yay
cold
async def on_ready():
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Traceback (most recent call last):
File "/home/container/bot.py", line 566, in <module>
@bot.command(name='av', help='Get the avatar of a user.')
^^^^^^^^^^^
AttributeError: 'Command' object has no attribute 'command'```
anyone help?
You have a command named bot that overshadowed your bot's var
I have a question, why since I implemented cogs to my bot now it no longer throws errors in the console and only "NoneType: none" appears, could it be because of using bot.start?
I tried with the traceback library and logging exc_info=True and nothing
discord.utils.setup_logging(*, handler=..., formatter=..., level=..., root=True)```
A helper function to setup logging.
This is superficially similar to [`logging.basicConfig()`](https://docs.python.org/3/library/logging.html#logging.basicConfig) but uses different defaults and a colour formatter if the stream can display colour.
This is used by the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client) to set up logging if `log_handler` is not `None`.
New in version 2\.0\.
is there a similar method to commands.command but for events? so that i can add the events to the bot later
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File) object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list) of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File) objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed) object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list) of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed) objects. **Specifying both parameters will lead to an exception**.
What the docs says. Sends a message to the destination (that member)
Why I don't understand it 😭
So it will send a content to wha?
To that member. In a dm
To first channel posible???
You can also just declare a normal ass function and add it as a listener directly without needing a cog
I personally prefer having a separate cog just for listeners
Yeah to each their own, just putting the options out there. There are cases where you'd want either
Me too, I put all the events in an cog events.py
I suggest you group things by functional groupings, i.e. all the things required for a particular feature or module
There's really not a case where you'd want to load/unload all listeners across all features (but not the other things related to those features), which is the whole purpose of cogs to have atomic loading/unloading
hey guys
who know make a discord bot that can auto message a disocrd user
in channels
"auto message a user in channels"?
Yeah you'll have to describe what it is you want to do, and when you want to do it
guys i need some coding help ill pay robux just dm me its not a scam or anything
!rule 9
.
What should be included in a on command error handler for a multipurpose bot
"Multipurpose" isn't particularly descriptive tbf
The error handler is for centralizing logic you want to happen when different errors occur, so I guess catalogue what kinds of errors you expect to happen and what you want to do when they happen
At minimum this should include putting as much detail about the error somewhere (reliably) that you can review it
how do I make a command that will enlarges emojis like 🔥 (normal emojis) and
(custom emojis) both
not asking to be spoonfeed btw ;3
You could use pillow for it but I'm pretty sure you'd have to do a separate process for custom emojis and default emojis
For default emojis you could place it as a text and size up it's font maybe
And you can get the image of custom emoji and scale it up
Those discord just sends you the Unicode. You will need to store/look up an image for them
yes tryna do dis
You can download a font package which have emojis in iy
or how they would do that
i see
You can download the tff from here
The one discord and twitter use
@bot.command(name='activate')async def activate(ctx):
await ctv.send('activated dev badge')
why no work
This should cause an error

i dont pay much attention to errors mb 😭
Should be the first thing you look for
I seem to still be failing at interactions even though I'm following the documentation that was recommended to me earlier this week
Not exactly sure what I'm missing here as this is inside a cog instead of on the main file
@commands.command()
async def memorylist(self, ctx:commands.Context) -> None:
# print(dir(ctx))
view = BaseView("User")
view.add_item(discord.ui.Button(label="Test", style=discord.ButtonStyle.blurple))
view.message = await ctx.send("Testing", view=view)
this is the view that I created
class BaseView(discord.ui.View):
interaction: discord.Interaction | None = None
message: discord.Message | None = None
def __init__(self, user: discord.User | discord.Member, timeout: float = 60.0):
super().__init__(timeout=timeout)
self.user = user
async def interaction_check(self, interaction: discord.Interaction) -> bool:
# if interaction.user.id != self.user.id:
# await interaction.response.send_message(
# "You cannot interact with this view.", ephemeral=True
# )
# return False
await interaction.response.send_message("Hi", ephemeral=True)
self.interaction = interaction
return True
basically just copy pasted from the docs
but you are not passing a Member or User object to the View object
view = BaseView("User")
and is it already working?
no 😦
What library do you use?
from __future__ import annotations
import typing
import traceback
import discord
import os
from discord.ext import commands
from discord.ext.commands import BucketType, cog, BadArgument, command, cooldown
from embedconfig import EmbedClass
# from pagination import BaseView
from discord.ui.select import BaseSelect
discord.py or py-cord?
they are similar in many ways, but pycord handles some things differently, and both use the discord module
In the documentation it says that the interaction_check() event must return a boolean, True or False. If it returns False, the on_error() event is called
You must handle that in the on_error() event.
I'm not really sure how the interactions work in discord.py. Why don't you use a callback?
this is also inside the view class
async def on_error(self, interaction: discord.Interaction, error: Exception, item: discord.ui.Item[BaseView]) -> None:
tb = "".join(traceback.format_exception(type(error), error, error.__traceback__))
message = f"An error occurred while processing the interaction for {str(item)}:\n
py\n{tb}\n"
self._disable_all()
await self._edit(content=message, view=self)
self.stop()
https://fallendeity.github.io/discord.py-masterclass/views/#basic-view this is for discord.py right?
A hands-on guide to Discord.py
I think it is better to add the button to its own class
would I need to call interaction.response.send_message directly?
smth like this
def calller():
await interaction.response.send_message()
return True
You can follow this example, but you must adapt it to your needs:
from discord.ui import Button, View
from discord import Interaction
class MyButtton(Button):
def __init__(self, ...):
super().__init__(...)
async def callback(self, interaction: Interaction):
# ...
pass
class MyView(View):
def __init__(self):
super().__init__(...)
async def interaction_check(self, interaction: Interaction)
# ...
pass
view = MyView()
view.add_item(MyButtton(...))
ok thanks
if interaction check returns false the interaction just fails, if u don't send a response back before the false
you did not add a callback for the button here
so while the interaction check passes it has nothing to do
Oh, ok, I wasn't sure how it worked because I didn't use discord.py, in the library I use there is another event that is executed when it returns False.
i see
I did try to follow one of Rappitz's examples though and I still got an interactions error even with a callback
This is the code I used
so I'm not sure if I missed a config setting on my bot or smth
Can you show your bot's configuration?
No, I mean how you have created the bot instance in your code
should be in the pastebin
bot = TicTacToeBot()
@bot.command()
async def tic(ctx: commands.Context):
"""Starts a tic-tac-toe game with yourself."""
await ctx.send('Tic Tac Toe: X goes first', view=TicTacToe())
bot.run(TOKEN)
or here
class TicTacToeBot(commands.Bot):
def __init__(self):
intents = discord.Intents.default()
intents.message_content = True
super().__init__(command_prefix=commands.when_mentioned_or('$'), intents=intents)
async def on_ready(self):
print(f'Logged in as {self.user} (ID: {self.user.id})')
print('------')
another possibility if ur network latency is too bad
Yeah
you should respond to all interactions within 3s
alright one sec
if u are not able to make interaction.response.defer() your first instruction and then at the end do interaction.edit_original_response()
ok let me restart my discord client
no vpn or proxy
just normal network connection
put the defer to my callback like this?
async def callback(self, interaction: discord.Interaction):
await interaction.response.defer()
Yes
hmm strange
class TicTacToeButton(discord.ui.Button['TicTacToe']):
def __init__(self, x: int, y: int):
super().__init__(style=discord.ButtonStyle.secondary, label='\u200b', row=y)
self.x = x
self.y = y
async def callback(self, interaction: discord.Interaction):
await interaction.response.defer()
assert self.view is not None
view: TicTacToe = self.view
state = view.board[self.y][self.x]
if state in (view.X, view.O):
return
if view.current_player == view.X:
self.style = discord.ButtonStyle.danger
self.label = 'X'
self.disabled = True
view.board[self.y][self.x] = view.X
view.current_player = view.O
content = "It is now O's turn"
else:
self.style = discord.ButtonStyle.success
self.label = 'O'
self.disabled = True
view.board[self.y][self.x] = view.O
view.current_player = view.X
content = "It is now X's turn"
winner = view.check_board_winner()
if winner is not None:
if winner == view.X:
content = 'X won!'
elif winner == view.O:
content = 'O won!'
else:
content = "It's a tie!"
for child in view.children:
child.disabled = True
view.stop()
await interaction.response.edit_message(content=content, view=view)
I put the defer function call at the very top
Use interaction.followup.edit_message
At the bottom?
You use followup when you defer the interaction or when u need to send a second interaction
Weird
sigh no dice
async def callback(self, interaction: discord.Interaction):
await interaction.response.defer(ephemeral=True)
assert self.view is not None
view: TicTacToe = self.view
state = view.board[self.y][self.x]
if state in (view.X, view.O):
return
if view.current_player == view.X:
self.style = discord.ButtonStyle.danger
self.label = 'X'
self.disabled = True
view.board[self.y][self.x] = view.X
view.current_player = view.O
content = "It is now O's turn"
else:
self.style = discord.ButtonStyle.success
self.label = 'O'
self.disabled = True
view.board[self.y][self.x] = view.O
view.current_player = view.X
content = "It is now X's turn"
winner = view.check_board_winner()
if winner is not None:
if winner == view.X:
content = 'X won!'
elif winner == view.O:
content = 'O won!'
else:
content = "It's a tie!"
for child in view.children:
child.disabled = True
view.stop()
await interaction.followup.edit_message(content=content, view=view)
this is all I see on my CLI
$ python main.py
2024-08-17 17:10:25 INFO discord.client logging in using static token
2024-08-17 17:10:27 INFO discord.gateway Shard ID None has connected to Gateway (Session ID: 8b5dfb9b76dcb7ea5f5b4133b9b97b65).
Logged in as Test Bot#5987 (ID: 517689574579896341)
------
Do you have logging enabled
Like this?
import logging
logger = logging.getLogger(__name__)
...
@bot.command()
async def tic(ctx: commands.Context):
logging.basicConfig(filename='myapp.log', level=logging.DEBUG)
logger.info('Started')
"""Starts a tic-tac-toe game with yourself."""
await ctx.send('Tic Tac Toe: X goes first', view=TicTacToe())
bot.run(TOKEN)
why are you defering in the first place?
is it a latency issue then?
i dont know
!d discord.InteractionResponse.defer
await defer(*, ephemeral=False, thinking=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Defers the interaction response.
This is typically used when the interaction is acknowledged and a secondary action will be done later.
This is only supported with the following interaction types...
print your bot latency
!d discord.ext.commands.Bot.latency
property latency```
Measures latency between a HEARTBEAT and a HEARTBEAT\_ACK in seconds.
This could be referred to as the Discord WebSocket protocol latency.
@bot.command()
async def ping(ctx):
await ctx.reply(f"Bot latency: {bot.latency}")
@bot.command()
async def ping(ctx):
message = f'⏱|** {round(bot.latency * 1000)} ms** Latency!'
title = "Ping"
embed = EmbedClass(message, title)
await ctx.send(embed=embed.embed)
I used this
full code
I can’t drop it here bro too big
this part
Ok wait
ok i do rn
here too
yep
good rn ?
response_data['txId']
if you use double quotes for the key, then form a string using single quotes

or reverse
im sorry if i dont undestand well im frensh so my english is a lil bad
i will try rn
can u edit this part and told me what to paste
\nhttps://live.blockcypher.com/ltc/tx/ { response_data["txId"] }"
the same, but even the error hints at it to you

\nhttps://live.blockcypher.com/ltc/tx/ { response_data['txId'] }"
yea
Hello, can anyone explain me async def {command_name}(ctx) ? i mean we type ctx for context but we can use others things, but when ?
i think it's easy but i don't know about it
i removed all the ()
return them back
you should learn the basic python syntax before writing anything in it.
NO
i know im not into python normally its new for me
edit(content="")
await message.editcontent=f":Spider_arrow: Successfully Sent {value}$ To {addy}\nhttps://live.blockcypher.com/ltc/tx/ {response_data['txId'] }"
delete this brackets ()
yeah i did
await message.edit(content=f"Spider_arrow: Successfully Sent {value}$ To {addy}\n //live.blockcypher.com/ltc/tx/ {response_data['txId'] }")
I don't want to write the link, but you understand
@slate swannobody will write code for you here, it's better to study the syntax
yep
im 100 percent agree with i dont even want to do that rn but im forced to do it cause of smtg
rn should work ?
@grizzled onyx
CHECK
@buoyant quail ты же русский? Может знаешь почему так?
response_data['cause']
i tried like that await message.edit(content=f"Spider_arrow: Successfully Sent {value}$ To {addy}\nhttps://live.blockcypher.com/ltc/tx/ {response_data['txId'] }")
it say me this
788 line
@slate swancomparer les deux variables et leurs clés response_data
yep replaced
try start bot
Yeah you're trying to run a self bot here. This is against TOS
Bro, you've got a error on a error
ahaha, this is real self-bot
Because discord said don't do it
.ltc
If you want to do automation, put it behind a bot account
i cant modify all code g
Any code you write must act on a bot account, not a personal user one

ok i understand
but at least can i know why i had error inside error ? @grizzled onyx
This is not a error inside error
so whats this exactly
It doesn't like the token you gave it
error on error, I meant that there are a lot of errors, at least that's what they say in Russian
its just an alt account token
Yeah don't do that
error after error*
idk
yep
Make a real bot, and get a real bot token
!rule 5
5. Do not provide or request help on projects that may violate terms of service, or that may be deemed inappropriate, malicious, or illegal.
I managed to get the logging
DEBUG:discord.http:POST https://discord.com/api/v10/channels/512594875284455424/messages with {"content":"Tic Tac Toe: X goes first","components":[{"type":1,"components":[{"type":2,"style":2,"disabled":false,"label":"\u200b","custom_id":"95611f1b3aceed0159da7a1be2e2c21c"},{"type":2,"style":2,"disabled":false,"label":"\u200b","custom_id":"71bae4157972b4f387aa31f798937881"},{"type":2,"style":2,"disabled":false,"label":"\u200b","custom_id":"8d11bdbb055dc770c4053fbf69631170"}]},{"type":1,"components":[{"type":2,"style":2,"disabled":false,"label":"\u200b","custom_id":"4bf9e70c520ebc88641f4b1c39db1a8f"},{"type":2,"style":2,"disabled":false,"label":"\u200b","custom_id":"7a8037802917c46b27f435bad505e61e"},{"type":2,"style":2,"disabled":false,"label":"\u200b","custom_id":"dced0d3cddbd759cd49ef2982ee455fc"}]},{"type":1,"components":[{"type":2,"style":2,"disabled":false,"label":"\u200b","custom_id":"262f9e58c530b36d6d8029cd039c40d3"},{"type":2,"style":2,"disabled":false,"label":"\u200b","custom_id":"a1f24e4ea61fd33065afd4f5b0b1dac3"},{"type":2,"style":2,"disabled":false,"label":"\u200b","custom_id":"d69bc2f7ef0a359f9cc4b24e50ff9e1e"}]}],"tts":false} has returned 200
200 is a success
hmm
I'm still getting this though
I've been having issues with my interactions
I just spun up a VPS in canada because my local PC is in Australia and I think all of the discord servers are hosted over there
now my ping is at 36ms but I can't quite figure out what's going on with this
the people that attempted to help were unsure as to why i was getting interaction failures even though my code was fine
There's not an issue with sending the message
There's an issue with responding to the interaction
Either you are trying to respond and there's an error, or you never try to respond. You should do some debugging to narrow down between the two
I just took one of the examples from the discord.py repo
async def callback(self, interaction: discord.Interaction):
# await interaction.response.defer(ephemeral=True)
assert self.view is not None
view: TicTacToe = self.view
state = view.board[self.y][self.x]
if state in (view.X, view.O):
return
...
await interaction.followup.edit_message(content=content, view=view)
this is the callback function from that
Do you know if that's being called at all?
let's see...
ok so no it isn't
I added a print statement just to test
i do not know why it's not being called
Well what's the full context here? Just there existing a method named callback doesn't mean the library is going to try to call it
one moment
from typing import List
from discord.ext import commands
import discord
import os
import logging
logger = logging.getLogger(__name__)
from dotenv import load_dotenv
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
from embedconfig import EmbedClass
handler = logging.FileHandler(filename='discord.log', encoding='utf-8', mode='w')
class TicTacToeButton(discord.ui.Button['TicTacToe']):
def __init__(self, x: int, y: int):
super().__init__(style=discord.ButtonStyle.secondary, label='\u200b', row=y)
self.x = x
self.y = y
async def callback(self, interaction: discord.Interaction):
# await interaction.response.defer(ephemeral=True)
print("Calling callback function")
assert self.view is not None
view: TicTacToe = self.view
state = view.board[self.y][self.x]
if state in (view.X, view.O):
return
if view.current_player == view.X:
self.style = discord.ButtonStyle.danger
self.label = 'X'
self.disabled = True
view.board[self.y][self.x] = view.X
view.current_player = view.O
content = "It is now O's turn"
else:
self.style = discord.ButtonStyle.success
self.label = 'O'
self.disabled = True
view.board[self.y][self.x] = view.O
view.current_player = view.X
content = "It is now X's turn"
winner = view.check_board_winner()
if winner is not None:
if winner == view.X:
content = 'X won!'
elif winner == view.O:
content = 'O won!'
else:
content = "It's a tie!"
for child in view.children:
child.disabled = True
view.stop()
await interaction.followup.edit_message(content=content, view=view)
class TicTacToe(discord.ui.View):
# This tells the IDE or linter that all our children will be TicTacToeButtons
# This is not required
children: List[TicTacToeButton]
X = -1
O = 1
Tie = 2
def __init__(self):
super().__init__()
...
for x in range(3):
for y in range(3):
self.add_item(TicTacToeButton(x, y))
# This method checks for the board winner -- it is used by the TicTacToeButton
def check_board_winner(self):
...
return self.Tie
return None
class TicTacToeBot(commands.Bot):
def __init__(self):
intents = discord.Intents.default()
intents.message_content = True
super().__init__(command_prefix=commands.when_mentioned_or('$'), intents=intents)
async def on_ready(self):
print(f'Logged in as {self.user} (ID: {self.user.id})')
print('------')
bot = TicTacToeBot()
@bot.command()
async def tic(ctx: commands.Context):
logging.basicConfig(filename='discord.log', level=logging.DEBUG)
logger.info('Started')
"""Starts a tic-tac-toe game with yourself."""
await ctx.send('Tic Tac Toe: X goes first', view=TicTacToe())
@bot.command()
async def ping(ctx):
message = f'⏱|** {round(bot.latency * 1000)} ms** Latency!'
title = "Ping"
embed = EmbedClass(message, title)
await ctx.send(embed=embed.embed)
bot.run(TOKEN, log_handler=handler, log_level=logging.DEBUG)
sorry that it's long but this is what I'm trying to run
this was mostly from the example on Rappitz's repo for discord.py
Can you implement an on_interaction event and log from there, then see if that fires when you click the button?
what's the prefix to check docs here?
!d
!d discord.on_interaction
discord.on_interaction(interaction)```
Called when an interaction happened.
This currently happens due to slash command invocations or components being used.
Warning
This is a low level function that is not generally meant to be used. If you are working with components, consider using the callbacks associated with the [`View`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View) instead as it provides a nicer user experience.
New in version 2\.0\.
do I call the on_interaction function like this?
async def callback(self, interaction: discord.Interaction):
discord.on_interaction(interaction)
Or does this need to be in the command function block?
@listen(name=None)```
A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready)
The functions being listened to must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Example...
Yes, but on_interaction. Checking to see if your bot is getting this interaction at all since the code looks fine
@bot.listen()
async def on_interaction():
print('Heard')
Like this?
Looks right
@bot.command()
async def tic(ctx: commands.Context):
logging.basicConfig(filename='discord.log', level=logging.DEBUG)
logger.info('Started')
"""Starts a tic-tac-toe game with yourself."""
await ctx.send('Tic Tac Toe: X goes first', view=TicTacToe())
@bot.command()
async def ping(ctx):
message = f'⏱|** {round(bot.latency * 1000)} ms** Latency!'
title = "Ping"
embed = EmbedClass(message, title)
await ctx.send(embed=embed.embed)
@bot.listen()
async def on_interaction():
print('Heard')
bot.run(TOKEN, log_handler=handler, log_level=logging.DEBUG)
Just to add context
Cool let us know if that log fires when you hit the button
Nope
[2024-08-17 14:27:12] [DEBUG ] discord.client: Dispatching event command_completion
es has received {'type': 0, 'content': 'Tic Tac Toe: X goes first', 'mentions': [], 'mention_roles': [], 'attachments': [], 'embeds': [], 'timestamp': '2024-08-17T14:27:12.792000+00:00', 'edited_timestamp': None, 'flags': 0, 'components': [{'type': 1, 'id': 1, 'components': [{'type': 2, 'id': 2, 'custom_id': 'b559d6616bd64a61490407f83f53a8ad', 'style': 2, 'label': '\u200b'}, {'type': 2, 'id': 3, 'custom_id': 'd1453a6ebf3af111d118a34ceaef523b', 'style': 2, 'label': '\u200b'}, {'type': 2, 'id': 4, 'custom_id': 'c92cea923bb119c6d76dace0f765eeea', 'style': 2, 'label': '\u200b'}]}, {'type': 1, 'id': 5, 'components': [{'type': 2, 'id': 6, 'custom_id': '14b3f330cb7cc41ecb75ad9b0724ea91', 'style': 2, 'label': '\u200b'}, {'type': 2, 'id': 7, 'custom_id': '4373babfe047e4e786147820f7f4e92f', 'style': 2, 'label': '\u200b'}, {'type': 2, 'id': 8, 'custom_id': 'a051265dbe3131aa5e0b772c7fc3799c', 'style': 2, 'label': '\u200b'}]}, {'type': 1, 'id': 9, 'components': [{'type': 2, 'id': 10, 'custom_id': '44a903519b0867676f8a7e6301c2608b', 'style': 2, 'label': '\u200b'}, {'type': 2, 'id': 11, 'custom_id': 'f29e58e09d7e1e95a6aa73abeef26c4b', 'style': 2, 'label': '\u200b'}, {'type': 2, 'id': 12, 'custom_id': 'a649d1f4d5d56b1237b71b2c1a149764', 'style': 2, 'label': '\u200b'}]}], 'resolved': {'users': {}, 'members': {}, 'channels': {}, 'roles': {}}, 'id': '1274373976797216800', 'channel_id': '512594875284455424', 'author': {'id': '517689574579896341', 'username': 'Test Bot', 'avatar': None, 'discriminator': '5987', 'public_flags': 524288, 'flags': 524288, 'bot': True, 'banner': None, 'accent_color': None, 'global_name': None, 'avatar_decoration_data': None, 'banner_color': None, 'clan': None}, 'pinned': False, 'mention_everyone': False, 'tts': False}
DEBUG:discord.client:Dispatching event command_completion
I don't think this is relevant
But that's the last message that got sent
And the interaction wasn't detected 😔
In the developer panel for your app, there should be a setting like interaction url. Is that filled?
I think I tried something before when I was testing before
Like when I created the bot at first
Ah. That is sending all of your interactions to that url, rather than through the websocket that your bot is connected on
Ok no wonder it didn't go through
Logged in as Test Bot#5987 (ID: 517689574579896341)
------
Calling callback function
Ok that's the first problem solved
But the issue is still present
Then you're hitting an error
You also have at least one code path that never responds
Some more debugging to see how far in you get would be useful
Many thanks for pointing that part out on my bot configuration with the interactions URL
how to make a transcribe command without using openai-whisper?
What does a transcribe command do?
Hi I have this bot structure
inhousequeue
│ ├── cogs
│ │ └── utils
│ ├── constants
│ ├── core
│ │ ├── actions
│ │ └── utils
│ │ ├── readyup
│ │ └── start
│ ├── database
│ ├── enums
│ ├── helpers
│ └── utils
├── migrations
├── scripts
and for example i'm doing imports in this way from inhousequeue.utils.etc..... import Something now why this is raising an error saying ModuleNotFoundError: No module named 'utils' i tried loading the extensions by passing package="inhousequeue" but it's not working
turns out i forgot to refactor some imports
@fast ospreyDo you know why that is?
gets audio of a video or voice note and puts it into text
We'll need more code then
speech to text ain't a discord problem
. You need to either run a model locally, or get instruction from your users that they're okay sharing data with whatever third party you choose (and that they aren't training AI on it)
@tasks.loop(seconds=50)
async def mod_stats(self):
await self.bot.wait_until_ready()
nowdatetime = str(datetime.now().time().strftime("%H:%M"))
nowdate = (datetime.today()).strftime("%d.%m.%Y")
nowweekday = datetime.today().weekday()
if nowdate not in self.staff:
self.staff.add(nowdate)
guild = await self.bot.fetch_guild(GUILD_ID)
staff = guild.get_role(HELPER_ID)
manager = guild.get_role(MANAGER_ID)
async with aiosqlite.connect(f"{FOLDER}/data/leafcity.db") as cur:
members = staff.members + manager.members
print(staff.members, manager.members)```
could this be due to the fact that I'm fetching a guild and getting roles for it?
@fast osprey many many many thanks
you found the root cause of my issue
it was that setting on the discord portal
I can't express how happy I am to have finally found what the issue was
Fetched items don't have their internal caches populated, you should just get the role from the cache itself
If you have a connected bot, there's very, very few reasons you'd legimitately need to use fetch
Basically only a) you need info on another shard b) you need a user's banner (which isn't sent with the user object by default) or c) you need a message that isn't in the cache
Glad to hear it, that's a sneaky setting that trips a lot of people up
like this?
I forgot too
but I think that if you are importing whatever you want to import from outside the inhousequeque folder, you use: py from inhousequeque.utils.etc
And if you're inside if the folder you just use a dot, like this
from .utils import Something```
@fast osprey it really works, thx 
Cool cool, yeah in general you should avoid fetching anyways unless you have a specific reason why the cache won't work
I reject to mix import styles, i use everywhere absolute imports, btw i forgot to refactor some imports so they were wrong
okay
hi, im trying to create a new bot for discord and im having problems with this command. im not sure if its the right one or what. ill send exception
`PS C:\Users\Solaris\Desktop\flirtykins> \venv\flirtykins\Activate.ps1
\venv\flirtykins\Activate.ps1 : The term '\venv\flirtykins\Activate.ps1' is not recognized as the name of a cmdlet, function, script file, or
operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
- \venv\flirtykins\Activate.ps1
-
+ CategoryInfo : ObjectNotFound: (\venv\flirtykins\Activate.ps1:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException`
.ps1's are powershell?
I really couldn't tell you, I am very new to this
i assume the command isn't right
but im just not sure which i should be using
Well, what is leading you to think this is what you should be doing? What is your objective?
trying to make a venv, ive already created it, trying to activate it now
What is telling you that this is what you should be doing?
You just came up with that line entirely on your own?
I'm doing what I was told, so I have no idea, a friend is helping me however they are using a mac
so they arent familiar with windows cmd or powershell
I'd recommend starting with this, no idea why powershell is in the picture
bcuz its the default terminal im using ig idk
ive also already tried the command there and it didnt work, though i probably entered it wrong
You could specify that you want to use powershell to run this file, whatever you're running in doesn't seem to know that .ps1's are run using it
I think you're underestimating how new I am to this, because this is still quite alien to me. If you are unable to simplify it, I'll look elsewhere. I understand you're trying to help, but I feel like I've gotten nowhere. Thanks.
Part of helping is specifying what it is you don't understand
I can't mind read what you don't know, this isn't hostile lol
This also has nothing to do with discord bots so is probably out of the purview of this channel, at face value this is an issue just running powershell
Any easier way to do this?
now = datetime.datetime.now()
# Calculate the next quarter hour
next_quarter = (now.minute // 15 + 1) * 15
if next_quarter == 60:
next_quarter = 0
hour = now.hour + 1
else:
hour = now.hour
next_run_time = now.replace(minute=next_quarter, second=0, microsecond=0)
if next_quarter == 0:
next_run_time = next_run_time.replace(hour=hour)
delay = (next_run_time - now).total_seconds()
await asyncio.sleep(delay)
Could just use a timedelta + discord.utils.sleep_until
As far as finding the next interval, could probably evenly divide the minutes by 15 and then add 15
now = datetime.datetime.now()
# Calculate the next quarter hour
next_quarter = (now.minute // 15 + 1) * 15 % 60
next_run_time = now.replace(minute=next_quarter, second=0, microsecond=0)
if next_quarter == 0:
next_run_time += datetime.timedelta(hours=1)
# Use sleep_until to wait until the next quarter-hour
await sleep_until(next_run_time)
My bot keeps responding with duplicate messages but I only have 1 instance open
Pasting large amounts of code
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
there is nothing in this code that can be the cause, do you maybe have a bot.process_commands inside a listener in of your cogs?
Don't use replit
It's most probably cuz of that
How can I make it so that after a bot restart all of the buttons and stuff will still work
With persistent views
It's different for each library, if you use discord.py I think it has an example in its repository
Look for an example on google, I don't use that library 
Alright
tysm
views(*, persistent=True)
An error occurred: Command raised an exception: TypeError: View.init() got an unexpected keyword argument 'persistent' :(
You probably want the add_view
"Persistent" isn't a property of the view itself
It's just a method of you adding a view to the bot directly without sending it
Okie
Guys do y'all know what bot I can use that can help me with python?
What help do you need?
anyone help me pls
i install 100000times discord.py + discord.py-self
but still vs said no module named discord
BURN IN HELL VS
HELP ME I HAVE GOT NERVOUS FOR NOW
discord.py-self breaks ToS
Unfortunately if you don't provide more information, we can't help
You can send messages over exaggerating your attempts, sending in full caps, etc. it won't help us knowing what doesn't work
You need to describe a) exactly how you're trying to install it and b) exactly how you're trying to run your code
I’m not
I do, sorry for the late response I was sleeping.
here’s the cog: https://paste.pythondiscord.com/JLSQ
What is the duplicate message? Do you have debugging statements figuring out the code path that's sending them?
All the commands are duplicating
Then you almost certainly are calling process_commands somewhere
Is anything else besides commands duplicating?
don’t think so
Is that the issue? Having a bot.process_commands
You only really ever need to do that in an on_message override, and even then 90% of the time people should be using listeners instead
Thanks
whats an instance where an override is better than a listener? or is there none?
oof- sorry for the ping
If there are specific cases where you don't want commands to be processed
IMO if you have an event override that has a process commands not underneath an if clause, that should just be a listener
How do i add a command into a cog separately?
.
├── ping.py
├── kick.py
├── cog1.py
└── bot.py
Example i have a structure like this, i want to add ping and kick command from ping.py and kick.py into cog1.py and run the bot, how would i do this?
Why wouldn’t you just put the command inside of cog1
well thats just not my style
That's not how cogs work
😔
You should group the things in a file that are deployable together and/or are conceptually linked. You should not dogmatically split things because "that's how I do it" or "the file is too long". Those are anti patterns that you can and should reprogram yourself of
Hi I'm back again to ask for more help
I'm trying to get my dropdown view working but I keep getting errors
@commands.command()
async def build(self, ctx: commands.Context) -> None:
data = [
"Test 1",
"Test 2",
"Test 3"
]
view = DropdownView(ctx.author, data)
print(type(view))
content=""
embed = self.create_embed()
await ctx.send("Menu", view=view)
from __future__ import annotations
import logging
import discord
import typing
import traceback
import json
class DropdownView(discord.ui.View):
message: discord.Message | None = None
sep : int = 5
current_page = 1
def __init__(self, user: discord.User | discord.Member, timeout: float = 60.0, data = []) -> None:
super().__init__(timeout=timeout)
self.user = user
self.data = data
# self.menu = discord.ui.Select[DropdownView](
# custom_id="persistent_menu",
# placeholder="Select a build",
# min_values=1,
# max_values=1,
# options=[discord.SelectOption(label=f"{i}") for i in data],
# )
# self.menu.callback = self.callback
# self.add_item(self.menu)
async def callback(self, interaction: discord.Interaction) -> None:
await interaction.response.defer()
async def interaction_check(self, interaction: discord.Interaction) -> bool:
if interaction.user == self.user:
content = "Test"
await self.update_message()
return True
False
await interaction.response.send_message(f"The command was initiated by {self.user.mention}", ephemeral=True)
return False
Is this correct?
As for the error I'm getting
[2024-08-19 20:25:34,489] ERROR: Ignoring exception in command build
Traceback (most recent call last):
File "C:\Users\bkwok\AppData\Roaming\Python\Python312\site-packages\discord\ext\commands\core.py", line 235, in wrapped
ret = await coro(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\bkwok\OneDrive\Documents\Development Files\Discord Bots\Python\Discord Bot Test\cogs\builds.py", line 87, in build
await ctx.send("Menu", view=view)
File "C:\Users\bkwok\AppData\Roaming\Python\Python312\site-packages\discord\ext\commands\context.py", line 1039, in send
return await super().send(
^^^^^^^^^^^^^^^^^^^
File "C:\Users\bkwok\AppData\Roaming\Python\Python312\site-packages\discord\abc.py", line 1622, in send
state.store_view(view, ret.id)
File "C:\Users\bkwok\AppData\Roaming\Python\Python312\site-packages\discord\state.py", line 410, in store_view
self._view_store.add_view(view, message_id)
File "C:\Users\bkwok\AppData\Roaming\Python\Python312\site-packages\discord\ui\view.py", line 567, in add_view
view._start_listening_from_store(self)
File "C:\Users\bkwok\AppData\Roaming\Python\Python312\site-packages\discord\ui\view.py", line 440, in _start_listening_from_store
self.__timeout_expiry = time.monotonic() + self.timeout
~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~
TypeError: unsupported operand type(s) for +: 'float' and 'list'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\bkwok\AppData\Roaming\Python\Python312\site-packages\discord\ext\commands\bot.py", line 1366, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\bkwok\AppData\Roaming\Python\Python312\site-packages\discord\ext\commands\core.py", line 1029, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\bkwok\AppData\Roaming\Python\Python312\site-packages\discord\ext\commands\core.py", line 244, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: unsupported operand type(s) for +: 'float' and 'list'
I'm basically trying to pass an array of strings into the view to be used as the option strings
What are you passing in as the timeout of your view?
it's defaulting to 60s
It's not
you're passing something into that parameter
(You probably want to use keyword arguments here)
def __init__(self, user: discord.User | discord.Member, timeout: float = 60.0, data = [])
Is that 60.0 not a default value?
data: list
def func(a:Whatever = None, b:WhateverElse = None):
...
x: WhateverElse = ...
func(x)
python doesn't know what you want, and the typehinting is irrelevant. It will still pass x into a because you're calling it with positional arguments
i guess
nothing to do with typehinting
Oh
I see. How would I define the 3rd argument in this case?
**kwargs?
x: WhateverElse = ...
func(b=x)
So it would have to be like this?
def __init__(self, user: discord.User | discord.Member, timeout: float = 60.0, **kwargs)
View(data=data)
You don't need **kwargs
you can list out the arguments normally in the function declaration, then just use keyword arguments when you're calling it
def __init__(self, user: discord.User | discord.Member, timeout: float = 60.0, data: list)
View(user=<PASTE_VALUE_HERE>, timeout=<PASTE_VALUE_HERE>, data=<PASTE_VALUE_HERE>)
More like this
Ohh ok
Default args cannot come before positional args
I think
!eval
def a(b=1, c): ...
:x: Your 3.12 eval job has completed with return code 1.
001 | File "/home/main.py", line 1
002 | def a(b=1, c): ...
003 | ^
004 | SyntaxError: parameter without a default follows parameter with a default
Yea
So put the data argument first?
Yes
i've just added a hybrid command into my cog but it doesnt appear, is this because i didnt sync?
Im curious about one thing: is it possible to make a discord bot recognise its previous posts after a reboot? So if I make an embed and that embed has buttons attached to it, they will not work if we restart the bot. How do you make it recognise and remember these buttons?
Might have found something actually, pause
All slash commands need to be synced to show up as such, at least with discord.py
Persistent views is what you'd want
Hello
Hi
is there a server for asking voicelink questions?
async def word(ctx):
file1_path = 'fflags.txt'
file2_path = 'ms.txt'
def count_words_from_file(file_path):
try:
with open(file_path, 'r') as file:
# Read file and split into words
words = file.read().lower().split()
total_words = len(words)
return total_words
except Exception as e:
return None, f"An error occurred: {e}"
total_words_file1 = count_words_from_file(file1_path)
total_words_file2 = count_words_from_file(file2_path)
embed = discord.Embed(
title="Word Statistics from Files",
description="Here are the word statistics from the text files:",
color=discord.Color.blue()
)
embed.add_field(name="File 1 Statistics", value=f"Total words: {total_words_file1}", inline=False)
embed.add_field(name="File 2 Statistics", value=f"Total words: {total_words_file2}", inline=False)
await ctx.send(embed=embed)```
**this is my code it works 50% when i run the command it tells me how many words are in my fflags.txt file correctly, but not the ms.txt file correctly. Does anyone know how to fix this?**
how is it incorrect?
wsp bitch im back
hmm?
noob you're not in the top 10
(we're friends pls don't ban me)
see you all in the valhalla ig
it says i have 200 words in my ms.txt file even though i dont.
Maybe try printing out the contents to see if it is what you think it is
hi
I created an embed message and put a button named test under it, but the button stops working after a while, how can I solve this because it times out?
class discord.ui.View(*, timeout=180.0)```
Represents a UI view.
This object must be inherited to create a UI within Discord.
New in version 2\.0\.
Yes, in the View object that has the button you can set the timeout attribute to None so that it continues to respond.
Note: If you restart the Bot the button will stop working, if you want the button to continue working after a restart you have to create a persistent view.
If you just say it doesn't work, no one can help you. Share the error or code so someone can help you.
I did timeout = none, but after a while the button stopped working again, but this time it doesn't give an error, it just clicks blankly.
I will write sample code
def __init__(self, user_id):
super().__init__(timeout=None)
self.user_id = user_id
@nextcord.ui.button(label="test", style=ButtonStyle.green, custom_id="test")
async def test(self, button: Button, interaction: Interaction):
await interaction.response.send_message("test", ephemeral=True, delete_after=10)
class Oyun(commands.Cog):
def __init__(self, bot):
self.bot = bot
@nextcord.slash_command(description="Oyunu Başlatır")
async def başlat(self, interaction: nextcord.Interaction):
await interaction.response.send_message("test123",view=OyunView(interaction.user.id))```
Should it be like this?
@scarlet tiger
sorry for the tag
So it worked when I did it this way, but as I said, the button stops responding after a while.
Try removing the custom_id and use defer()
It is not recommended to put a custom_id because it can cause conflicts, they are only used when creating persistent views (at least in the library I use it is that way)
Why would defer help in this case?
I use custom_id to close the button if the required condition is not met.
what
Well I don't see an error in the code, do you see anything in particular?
😅
I don't, lol
timeout = none but as I said, it does not respond after a while
I asked chatgpt but he also gave wrong solutions
By the way, I'm a newbie, I don't feel confident about the code I wrote, I'm just trying to improve myself. But I need to solve this problem
You can try putting a print() in each function of each button and see if it returns a response in the terminal
at the start of each function of each button put await interaction.response.defer()
But in this case send_message() will not work, you must use followup.
oh i get it
btw
The problem was solved in a way I did not understand
Now, even if I close and reopen the bot, I can run it again by pressing the previous message buttons.
._.
It's really weird
In simple terms sometimes your connection speed or the discord servers have a high latency or you have a function that takes a long time to complete. An interaction must receive a response within 3 seconds, otherwise it doesn't work.
With defer() you tell discord to wait (I think the time increases to 15 minutes).
Now the time is unlimited ._.
Even the button on the message I sent yesterday worked.
Setting the timeout to none on its own doesn't make python magically regenerate view objects that don't exist
That means something else is going on
I close and reopen the bot, the buttons in the previous messages do not work, but when I use any slash command, they start working too.
The library on its own won't make view objects for you
something in your code is making those views
umm
def __init__(self, user_id):
super().__init__(timeout=None)
self.user_id = user_id
@nextcord.ui.button(label="/oyna", style=ButtonStyle.green, custom_id="oyna")
async def oyna(self, button: Button, interaction: Interaction):
if interaction.guild is None:
await interaction.response.send_message("Seni Akıllı İnsan Bu Komut Sadece Sunucuda Çalışır Hadi Sunucuda Dene.", ephemeral=True, delete_after=10)
return
await interaction.response.send_message(embed=embed, file=file, view=OyunView(interaction.user.id))
class Oyun(commands.Cog):
def __init__(self, bot):
self.bot = bot
@nextcord.slash_command(description="Oyunu Panelini Açar")
async def oyna(self, interaction: nextcord.Interaction):
if interaction.guild is None:
await interaction.response.send_message("Seni Akıllı İnsan Bu Komut Sadece Sunucuda Çalışır Hadi Sunucuda Dene.", ephemeral=True, delete_after=10)
return
await interaction.response.send_message(embed=embed, file=file, view=OyunView(interaction.user.id))```
Couldn't tell you if nextcord doesn't key the view by message id, in which case yeah you'd get overlapping views sharing state if they had the same custom ids 
Wouldn't it work if I didn't use custom_id?
I would assume nextcord would also give you a random custom id in that case
hmm
There's not a sane world where sending a view on Message A suddenly makes something start listening on Message B that wasn't before, so either you still have something going on or this library is doing something a bit silly
This stupidity works for me
Sure hope your views never rely on having consistent internal state 
is hosting a discord bot on gcp on the forever free tier actually free? i get mixed reviews on the internet about how it renews every month or you have to pay
Dude, you can host your bot forever by buying a cheap development card.
like orange pi
umm
How can I add cooldown to slah commands?
If you're going to reply to me, please tag me. I need to sleep. I'll check tomorrow.
There are far fewer cases where you need to
Why do you want a cooldown?
They can't
There is a command, I made it to be used only every 10 minutes, but I need to add a cooldown.
App commands already impose a limit natively in discord. It's fine if your actual application logic needs this cooldown functionally but if it's just fear of "spam" or rate limits there are better alternatives
Forever free tier is kind of misleading from what I have read, to even qualify for the free tier you need to either, have a free trial going currently, or have your account be a paid type. Other than that, if you stay within the free tier usage limits that are described by google, you will not be charged. However if you do exceed those said limits, you will be charged for that usage
recursive view is crazy
How would you use application emojis via the emoji tab? tried fetching the emoji using the provided id but it didn't work? Maybe there's an different way?
I'm just doing
@bot.command()
async def send_emoji(ctx, id:int):
emoji = bot.get_emoji(id)
if emoji:
await ctx.send(f"The Emoji: {emoji}")
else:
await ctx.send(f"{id} isn't an emoji")
and its returning the else statement? Honestly this isn't a big problem, I could just upload the emojis to a private server but yk why not try the tab
I've tried going through bot.application but it only provides the general information page
if you want to use of one your app's emojis you just need to follow the regular emoji format <:name:id>
Alright ty
i was making a discord bot and i got into situation where i want the bot to send a message whenits added but idont know how to get a first available channel on that server
uhm how?
guys how long it takes to learn discord bot creating using discord.py
There's no guarantee you'll have any access, and even then sending a message in a random ass channel isn't particularly productive. You should just publish documentation and have a support server, pull mechanisms, rather than pushing unwanted messages on your users
This entirely depends on how much expertise you're coming in with and how fast you learn, plus what you're trying to accomplish
You can get a hello world bot up in like 20 minutes with no prior experience just following the quickstarts
can confirm, never used python or discord api wrappers before
why i cant download discord.py please help #1275460267802624041
-# the above was resolved in the thread
i want to learn high i know python basics and learning django i want to connect discord bots to other games/websites xd
i don't want chatbot only
also i should start mysql
mysql is a pretty objectively bad db tbh
What would you recommend instead?
^ Postgres if you are planning on storing more data
Sqlite if you are not storing as much and need to set it up quick and easily
Also make sure you use an async wrapper. (asyncpg for Postgres.)
Thank you 
99% sure you'll never run into a problem where you're storing "too much" data for SQLite
but there are a few other reasons also to use postgres tho like extensions, diverse column or data types, triggers/functions, pg notify for a bit of limited realtime comm all of which might be useful provided you leverage it properly
i was making a slash command for my bot and wanted it to have cooldown, so i used py @app_commands.checks.cooldown(1, 1200, key=lambda i: (i.guild.id, i.user.id))
but i wanted to make it so if you have such and such role, the cooldown doesnt apply to you
is this in anyway possible?
dynamic_cooldown probably
In pycord slash commands, what @ thing do I use to check if user has certain role?
I think it's this decorator:
https://docs.pycord.dev/en/stable/ext/commands/api.html#discord.ext.commands.has_role
Pycord
The following section outlines the API of Pycord’s prefixed command extension module. Bots: Bot: Attributes activity, allowed_mentions, application_flags, application_id, cached_messages, case_inse...
Yea I found it the moment you responded lmao. thanks tho
In most cases you should now use default permissions and let the admins of the server configure role permissions in the discord UI.
Just for reference
@commands.has_permissions(manage_messages = True)
async def clear(ctx, amount: int):
await ctx.channel.purge(limit=amount)
async def message_on(message):
await message.channel.send("Les messages ont bien été supprimer", delete_after=5)```
the end message is not displayed
You're making a function called message_on. What calls this?
Well I mean just making a function doesn't do anything
How should we do it?
Do what?
Because there is already the function of purge
Purge and say : purge good ( delete 5s)
You can do whatever you want in the body of the command
you don't need to make another function
Now the bot purge and after purge : crash
Where ?
In the command function?
@bot.tree.command()
async def my_command(...):
you_can_do()
multiple_things()
in_a_row()
you_dont_need_another_function()
Sorry I starting in the code and in the English language
But "message" is note define
It's not, because that's a variable you made up
you have the things in your command to work with though
In my land it’s 3h am, you can just help me for right that please ???
If you're making an app command, you don't get a context. Naming that parameter ctx is very misleading. You get an Interaction. That Interaction has all of the information of things you'd want to do here
@bot.tree.command()
async def my_command(interaction):
#you can do things with the interaction, like access interaction.channel
You don't get a context
don't make a parameter named ctx
you get an interaction, and that is always the first parameter
And
Async….
Async…
Is an error too
You don't get two interactions
They run the command. That's an interaction. That is the user interacting with your bot. They interacted with your bot once.
Oh okey but the bot Have to do two things
And you can do two things. You can do however many things you want
One things define, other not
You don't get a message. Again, you get an Interaction. And that has what you need
What you say in python ?
Just...have multiple lines?
^?
For the same command ?
But it’s an error
Which is?
Then only make one
you're making another function
why are you making another function
You can have one function that does multiple lines, one after another
that's just how python works
Because if i make not : error = function note define
because you're referencing something that doesn't exist
the answer isn't to make another function. It's to use the variable you have
which should be interaction in the first place
@bot.tree.command()
async def my_command(interaction):
interaction.x()
interaction.y()
interaction.z()
You don't get a context
do not have a variable called ctx
do not treat anything like a context. You don't get one
That's not what your error says
You don't have a context. You don't need one
It's best you don't copy paste code you don't understand
And start from scratch. You're making an app command. Forget ctx as a concept exists, because it's not relevant and should not show up in your code
You have your interaction and that's what you use. The error above has nothing to do with a ctx
I understand i don’t see the difference with object and context
Context, often shortened to ctx, is an object given to prefix text commands. You are not making that, so it does not apply
For tonight I would just like to finalize this order can you help me?
I don't write code for people. If that's what you'd like, you're welcome to wait for someone who might
This code is almost correct. The error happens for a specific reason. It has nothing to do with a contest
Not right but just Say me or put it on, I've almost done everything
I know
But it’s 4h am and i don’t want sleep if the commande is not finished
I’m French because it’s too difficult for communicate with you and with python language
The difficulty is x2
So what is the error with that code from that screenshot?
Clear unknown the interaction.channel.purge doesn’t existe
That isn't what the error says. I'm looking right at it
It’s an exeption
Type error
Unsuport type annotation
That's also not what is in that screenshot
I'm reading it dude, I can see it with my eyes
"Unknown intera(cuts off)"
Interaction
What is that full error
Interaction uncknow
Traceback (most recent call last):
File "C:\Users\david\PycharmProjects\pythonProject\bot discord\venv\Lib\site-packages\discord\app_commands\commands.py", line 828, in _do_call
return await self._callback(interaction, **params) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\david\PycharmProjects\pythonProject\bot discord\main bot discord.py", line 66, in clear
await interaction.response.send_message("Les messages ont bien été supprimer", delete_after=5)
File "C:\Users\david\PycharmProjects\pythonProject\bot discord\venv\Lib\site-packages\discord\interactions.py", line 801, in send_message
await adapter.create_interaction_response(
File "C:\Users\david\PycharmProjects\pythonProject\bot discord\venv\Lib\site-packages\discord\webhook\async_.py", line 219, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\david\PycharmProjects\pythonProject\bot discord\venv\Lib\site-packages\discord\app_commands\tree.py", line 1248, in _call
await command._invoke_with_namespace(interaction, namespace)
File "C:\Users\david\PycharmProjects\pythonProject\bot discord\venv\Lib\site-packages\discord\app_commands\commands.py", line 853, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\david\PycharmProjects\pythonProject\bot discord\venv\Lib\site-packages\discord\app_commands\commands.py", line 846, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'clear' raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction```
its after i realize the command
This happens because interaction.response.send_message has to be done within 3 seconds. Your purge is probably taking longer than that
I recommend doing await interaction.response.defer(ephemeral=True) before you purge, then await interaction.followup.send("whatever you want") after
You have to respond within 3 seconds. response.defer is one way of responding which means "the bot is doing something that will take time", it gives the "bot is thinking" message
followup.send is how you send a message after a response. In this case, signaling the bot is no longer "thinking"
Oh okay it’s just time problems ?
Yes. Your interaction.response must be fast
But here the delete 5s doesn’t work good
The "whatever you want", delete _after=5
Night
where should i sync commands in my bot?
in discord.py it is in the setup_hook() event, in other libraries they are synchronized automatically
i am getting
TypeError: 'Bot' object does not support the context manager protocol
trying to run
with Bot(command_prefix=prefix, intents=intents) as bot:
bot.run(dotenv.dotenv_values('.env')['BOT_TOKEN'])
how do i fix this?
Select can have take url and instead of emoji and put like thumbnails?
Remove with and do bot=
And also remove as bot
Is there a way to hide private threads from thread list ,i want only certain individuals should be able to see the thread
Not all
If they are not added
from discord import Intents
from discord import app_commands
from discord.ext import commands
class SlashCog(commands.Cog):
def _init_(self, bot : commands.Bot) -> None :
self.bot = bot
intents = discord.Intents().all()
bot = commands.Bot(command_prefix="+", intents=intents)
intents.message_content = True
intents.members = True
class MyBot(commands.Bot):
def _init_(self) -> None:
super()._init_(command_prefix="+", intents=discord.Itents.all())
intents = Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
tree = app_commands.CommandTree(client)
bot = commands.Bot(command_prefix= "+", intents=discord.Intents.all())
@bot.event
async def on_ready():
print("Le bot est prêt.")
try:
synced = await bot.tree.sync()
print(f"Synced {len(synced)} commands")
except Exception as e:
print(e)
@bot.event
async def on_message(message):
if message.content.lower() == "ping":
await message.channel.send("pong", delete_after=5)
if message.content.startswith('hello'):
await message.channel.send('Hello!')
def is_owner():
def predicate(interaction: discord.Interaction):
if interaction.user.id == 1125518202835841044:
return True
return app_commands.check(predicate)
@bot.command()
@commands.has_permissions(manage_messages=True)
async def say(ctx, *, message):
await ctx.send(message)
await ctx.message.delete()
@app_commands.command(name="cog_command")
async def command(self, interaction : discord.Interaction):
return interaction.response.send_message("Message dans un Cog")
@bot.tree.command(name="test", description="Cette commande est un test !")
async def test_slash(interaction: discord.Interaction):
await interaction.response.send_message('test')
@bot.tree.command(name="owner", description="Cette commande est réservé a mon développeur")
async def owner_slash(interaction: discord.Interaction):
await interaction.response.send_message(f"Salut, {interaction.user.mention} !", ephemeral=True)
@bot.tree.command(name="clear", description="Supprimer des messages")
@commands.has_permissions(manage_messages = True)
async def clear(interaction: discord.Interaction, amount: int):
await interaction.response.defer(ephemeral=True)
await interaction.channel.purge(limit=amount)
await interaction.followup.send("Les messages ont bien été supprimer")```
Since I put my smash orders, my prefix commands no longer work
Why ?
Don't use an on_message event, use a listener. And don't sync or really do anything in on_ready
Also you should not have a client and a bot
Ping function
My events function but not my prefix command
The tree command doesn’t function With bot instead of customer
Ok i know
I delete client
Don't use an on_message event
This is overriding the bot processing text commands, you should use a listener instead
!d discord.ext.commands.Bot.listen
@listen(name=None)```
A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready)
The functions being listened to must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Example...
^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'Intents' object has no attribute 'message_content'
[Done] exited with code=1 in 0.672 seconds```
bro
what version are you on
Show your pip list
2.0.0
import discord
from discord.ext import commands
import random
import os
from dotenv import load_dotenv
pip freeze
async def avatar(self, interaction: nextcord.Interaction, kişi: nextcord.User = nextcord.SlashOption(description="Avatarını görmek istediğiniz kişiyi etiketleyin", required=False), gizli: bool = nextcord.SlashOption(description="Avatar komutunu gizler", required=False)):
if interaction.guild is None:
await interaction.response.send_message("Bu Komut Sadece Sunucuda Kullanılabilir.", ephemeral=True,delete_after=10)
return
if kişi is None:
kişi = interaction.user
avatar_url = kişi.avatar.url
avatar = f"[Avatar Link]({avatar_url})"
embed = nextcord.Embed(
title="",
description="**["+f"{avatar}"+"]**",
color=nextcord.Color.green()
)
embed.set_author(icon_url=avatar_url, name=f"{kişi.name}")
embed.set_image(url=avatar_url)
embed.timestamp = current_time
embed.set_footer(icon_url=self.bot.user.avatar.url, text=self.bot.user.name)
if gizli is None or False:
await interaction.response.send_message(embed=embed)
else:
await interaction.response.send_message(embed=embed, ephemeral=True)```
kişi is none but bot not response
does it respond if you do pick a user in the slash command when you use it?
yes
but user only use /avatar and bot not response
Are you getting any errors in the console? Interaction.user could be None, in which case I'd expect it to raise an exception at avatar_url = kişi.avatar.url looking something like "NoneType has no attribute 'avatar'"
I don't see why Discord wouldn't be providing a user but according to the api schema it's possible, and I'm not sure why else you'd get no response at all
The problem is, I don't get any errors in this job.
You're debugging this without access to the terminal/console output? That seems like a task from hell
I guess you could try adding another check to guard in case there is an error, something to the effect of
if kişi is None:
if not interaction.user:
await interaction.response.send_message("An error occurred, no user was found")
kişi = interaction.user
avatar_url = kişi.avatar.url
If there was an error, it would already give the error to the terminal like crazy, but it doesn't give an error.
I'm guessing that translates to something like "Command/interaction timed out"?
hmmm, ok there's no path in your code I can see that should cause that to happen, no matter what you should be getting either a response or an exception raised - are you 100% certain that the bot is running on the most recent code, it couldn't be running an older version where it might not respond? ik it sounds obvious but it happens to everyone at some point and it's easy to overlook
Look, the nonsense is that it only gives an error when I type /avatar, but it works when I set /avatar gizli=false or true.
And when I set gizli=false or true, I still don't select user.
but when I just type /avatar it doesn't give an answer
Ok so - as long as you set gizli to anything other than leaving it empty, it works, regardless of whether you set kişi?
Normally when I type /avatar it should work
kişi or gizli also required = false
async def avatar(self, interaction: nextcord.Interaction, kişi: nextcord.User = nextcord.SlashOption(description="Avatarını görmek istediğiniz kişiyi etiketleyin", required=False), gizli: bool = nextcord.SlashOption(description="Avatar komutunu gizler", required=False)):
if interaction.guild is None:
await interaction.response.send_message("Bu Komut Sadece Sunucuda Kullanılabilir.", ephemeral=True,delete_after=10)
return
if kişi is None:
if not interaction.user:
await interaction.response.send_message("An error occurred, no user was found")
kişi = interaction.user
if kişi.avatar.url is None:
await interaction.response.send_message("Kullanıcının avatarı yok")
return
avatar_url = kişi.avatar.url
avatar = f"[Avatar Link]({avatar_url})"
embed = nextcord.Embed(
title="",
description="**["+f"{avatar}"+"]**",
color=nextcord.Color.green()
)
embed.set_author(icon_url=avatar_url, name=f"{kişi.name}")
embed.set_image(url=avatar_url)
embed.timestamp = current_time
embed.set_footer(icon_url=self.bot.user.avatar.url, text=self.bot.user.name)
if gizli is None or False:
await interaction.response.send_message(embed=embed)
else:
await interaction.response.send_message(embed=embed, ephemeral=True)```




