#discord-bots
1 messages · Page 366 of 1
??
Where i find that?
in the settings. lemme find the plugin name rq
quit the yapping bro
I've better alternates

927257448568467516 user id
One message I'd 1239541748909342892
I'm the roast pro tbh stop it...
No documentation found for the requested symbol.
!d discord.utils.setup_logging
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.
Ty
I have passed out of
University Of Swears and Slurs
And this is my rank
#02
And my results
Slurs Minor - A+
Slurs Major - A+
Swears Minor- A-
Swears Major - A+
its the valid ids plug in
ohh ok i see
I'm also in mobile
ight pipe down you getting cringe
@latent pier another thing I want to ask if I just use the logging lib it will automatically will be colored like d.py logs or I need to use client instance?
like money
should be coloured
Aight cool
No need to use instance
open #discord-bots
look inside
axo again
Guys whoever thinks replit sucks
React with 🤓
2024-05-13 17:58:35 INFO discord.client logging in using static token
INFO:discord.client:logging in using static token
2024-05-13 17:58:45 INFO discord.gateway Shard ID None has connected to Gateway (Session ID: 64b7df91e7d44ae30ac36be4ad941a50).
INFO:discord.gateway:Shard ID None has connected to Gateway (Session ID: 64b7df91e7d44ae30ac36be4ad941a50).
Logged in as Test#4384 (ID: 1237358593230241792)
i imported logging and this happening now instead of 1 now its 2 logs
another thing is now its not showing which cogs is getting loaded
Guys is there any api which makes a image with author avatar and username with title Winner
earlier i was getting just 1 logs
how are you loading them
Any good api for that?
then something had to be wrong
def load_cog(self, file_path):
module = importlib.import_module(file_path)
for name, obj in inspect.getmembers(module):
if inspect.isclass(obj) and issubclass(obj, commands.Cog):
asyncio.run(self.add_cog(obj(self)))
logging.info(f'Loaded {name} Cog')
use pillow or smth like that for image manipulation
just learn pillow for that
I WAS JUST THERE MAN
alr bro
just use the setup_hook 💀
cope
@viscid hornet
im seething rn
Aye did a mosquito bite your balls?
!d discord.Client.setup_hook
await setup_hook()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A coroutine to be called to setup the bot, by default this is blank.
To perform asynchronous setup after the bot is logged in but before it has connected to the Websocket, overwrite this coroutine.
This is only called once, in [`login()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.login), and will be called before any events are dispatched, making it a better solution than doing such setup in the [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready) event.
Warning
Since this is called *before* the websocket connection is made therefore anything that waits for the websocket will deadlock, this includes things like [`wait_for()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.wait_for) and [`wait_until_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.wait_until_ready)...
cogs getting loaded but logs are getting suppressed somewhere
use this to load cogs
cogs are getting loaded i am only not getting logs
Aye did reject say anything? Dm me

how did u setup logging
also did u set a log_level which may cause other or lower log levels to be surpressed
i am trying to use d.py logging , and i am using logging.info only it should show cuz info is getting printed in terminal from d.py, dont know why mine is getting suppressed
the default dpy logging is prolly warning or errors
Oh
where ur using info
!d discord.utils.setup_logging
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.
^^
2024-05-13 18:04:29 INFO discord.client logging in using static token
i thought this line bcz of this line
how do u start the bot using run or start?
Run prob
run
aight
axo probably lurking and waiting to send a documentation link 
already sent
axo needs to take a mental health break 🙏
this one
im currently raging at matplotlib cuz it keeps breaking and i need to graph some data 😭
in a moment

ray pls help in general

2024-05-13 18:49:50,647 INFO Shard ID None has connected to Gateway (Session ID: 7c255f658799526dea0d56402930f454).
2024-05-13 18:49:50,647 INFO Shard ID None has connected to Gateway (Session ID: 7c255f658799526dea0d56402930f454).
2024-05-13 18:49:52,682 INFO 2024-05-13 18:49:52 logger.py Logged in as Test#4384 (ID: 1237358593230241792)
2024-05-13 18:49:52,682 INFO 2024-05-13 18:49:52 logger.py Logged in as Test#4384 (ID: 1237358593230241792)
getting double logs for some reason
i just wanted 1

turns out giving it 6000 rows is a bad idea
6000
yes, 6000
anyone?

im tryna analysis my connect 4 algorithm because its currently for some reason incredibly unoptimised
just look at this
(this is running the benchmark on a better pc - mine had a longest time of 950 seconds 💀)
!res - you'll find your answer in these
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
anything about python
jk jk i was trolling lol sorry
Racism
Weird way of thinking
"what is racism
"
im thinking hard
Colonizers know it better 🗣️
Yeah looks really hard
thats because it is really hard
What is different between
users = await collection.find().to_list(length=None)
for user in users:
and
async for user_data in collection.find():
You should measure how hard is it
Thinking
Tf is collection.find I'm seeing for the first time 😭😭
collection = db["profiles"]
what type does collection hold?
Users from the guild
Casual MongoDB
Probably better served in the db channel, nothing discord related here
Isn't it dictionary
one is an async generator the other is converting the generator to a list by getting all its elements at once
How is that related to my question anyhow?
Which one is more appropriate to use?
We should know the context like what are you passing into for loops
Checking users basically
it's revan
?? whos that
Even though this is highly offtopic for the current channel (which was already mentioned)
The async iterator will let you exit early if you have a condition you need to be met. E.g. async for x in y: if x.id == ....: return or similar
The former operation is colloquially known as "flattening" will give you all results at once, which if the collection is large, is an expensive operation.
I doubt you're in that territory yet, but there you go.
Please move to #databases for any future questions on the matter, or open a dedicated help thread
u shouldnt really see too much of a difference in either tbh the 2nd one allows for more fine grained control if ur doing break or continue etc
async for should be used to traverse an asynchronous iterator within a coroutine
usually if ur iterating and performing some operation or calculation on the result set and u dont really need all of them
it's just asynchronous version of for loop 🤣
In simple words
Other than that no difference
class UsefulEmbeds(commands.Cog):
def __init__(self,bot:commands.bot) -> None:
self.bot = bot
def failure_embed(self,title: str = None, desc: str = None):
embed = Embed()
embed.color = Color.red()
embed.description = desc
embed.title = title
embed.timestamp = datetime.now()
return embed
def success_embed(self,title: str = None, desc: str = None):
embed = Embed()
embed.colour = Color.green()
embed.description = desc
embed.title = title
embed.timestamp = datetime.now()
return embed
async def send_logs(self,channel_id):
i dont want to make it cog is it possible to get the bot instance without inhering command.bot? i want to fetch one channel for that i need bot instance
Please don't give misinformation in a channel usually reserved for people pretty new to Python
@spice warren misinformation?
You could just make a non-Cog class you can create as needed and pass the bot into it
Alternatively you could just make these free functions that you also pass the bot, or the already gotten/fetched cahnnels into
That is clearly not the message I was referring to since I directly replied to it
will that work in the constructor?
You're in charge of defining the constructor so I don't see why not
it will be attached to same bot instance right?
So long as you pass it to it, yes
ok let me try
That message was clearly related to above message which said "it's just asynchronous version of for loop"
The "no difference" is misinformation since it is pretty different.
Ok i understand my bad not to write everything in single message
class UsefulEmbeds:
def __init__(self,bot:commands.bot) -> None:
self.bot = bot
this seems correct?
sure
Try it :)
oki : )
i would make them static methods tbh
I meant other than that there's no difference in both
and pass bot as param
will do
this seems good but only issue is then i need to pass bot everytime
which will be repetative
hmm u can have the user embeds class as an attribute for the bot then i suppose
yeah i made them methods of usefulEmbed class
otherwise u would either need some global instance of the useful embed class or u would need to initialize it everytime either ways
You're missing the point entirely to defend yourself out of ego.
Please do not give misinformation to people in the channel.
There is a very clear different between an async iterator and a non-async iterator.
Do not tell people there isn't, which is just wrong.
Instead, don't mention it at all, and if someone asks the difference, explain it, and if you don't know that difference then defer to someone who does, rather than say the incorrect thing and lead people astray.
umm you are right either way looks like i need to do one or the other
Normalize admitting when you don't know something, or when you know it's a guess 
Do they need to be part of the class? What about a free function that takes relevant parameters?
time for staticmethods just coz i like it grouped lol
and the useful embed class itself dosent need to maintain any state
i am clubbing them together in a class for easier management
Staticmethods it is :)
i will convert them once i setup this logging method : )
I'll keep that in mind
TypeError: can't subtract offset-naive and offset-aware datetimes
await unverified_collection.insert_one(
{"user_id": member.id, "timestamp": member.joined_at})
if (member.joined_at - user_data['timestamp']).total_seconds() > 300:
Why can't I compare member.joined_at with member.joined_at > 300
🤔
I mean they should be the same format
for loop iterates through a collection in a synchronous way which means this waits for each iteration to complete before moving on to the next task
And on other hand async for should be used to transverse an asynchronous iterator within coroutine, It enables concurrent execution of tasks by processing items concurrently, potentially yielding results as soon as they become available without waiting for each iteration to complete
What about if (member.joined_at.replace(tzinfo=None) - user_data['timestamp']).total_seconds() > 300:
They are both giving me the same timestamp
Why are print(member.joined_at.replace(tzinfo=None)) and print(user_data['timestamp']) giving me the same timestamp?
Are you trying to substract joined_at of same member?
Why are you stripping the timezone?
Yes
What do you mean?
Shouldn't it be zero because you're substracting same value?
Should be the time when they joined
await unverified_collection.insert_one( {"user_id": member.id, "timestamp": member.joined_at})
on_member_join
Then I run a task to compare
.replace(tzinfo=None) is stripping the timezone, why?
TypeError: can't subtract offset-naive and offset-aware datetimes
Because of MongoDB
The solution here is to make the other timezone aware, not the other way around
Right, I see, and mongo strips timezones? All the more reason it's not great
Yes
Okay so the alternative solution is to instead store the timestamp as the int, not the datetime itself
You'll have an integer to work with rather than potentially messing up your datetime
OOHHH my bad
Then when you want to use this for comparison you can use datetime.datetime.fromtimestamp(..., tzinfo=datetime.UTC) and you'll have an aware datetime to do your dt math with too
member.joined_at will always be the same
Exactly that's the first thing i said
It's value won't change
Brah
Unless left and joined then it'll be assigned new value
Can you show me an example?
dt = datetime.datetime.fromtimestamp(12738912739812, tzinfo=datetime.UTC)
then you can do like
dt > other_datetime and whatnot
That was my original solution, yes
Why is it bad if I save it as
await unverified_collection.insert_one( {"user_id": member.id, "timestamp": member.joined_at})
And then compare it as
if (discord.utils.utcnow().replace(tzinfo=None) - user_data['timestamp']).total_seconds() > 60:
stripping the timezone from a datetime can give inaccurate results, e.g. a time/date that doesn't actually match what you has
that's why the preference is to add the timezone rather than subtract it
What if I change VPS to a different location
And the timezone would change
datetime.timestamp() is locally
No datetime.datetime.timestamp() is relative to that datetime
Can you give me an example how these two lines would look like:
await unverified_collection.insert_one(
{"user_id": member.id, "timestamp": member.joined_at})
if (discord.utils.utcnow().replace(tzinfo=None) - user_data['timestamp']).total_seconds() > 300:
Cause I'm confused
...insert_one({..., "timestamp": member.joined_at.timestamp()})
joined_at = datetime.datetime.fromtimestamp(user_data["timestamp"], tz=datetime.UTC)
if (discord.utils.utcnow() - joined_at) > 300:
...
Thank you so much. So member.joined_at and member.joined_at.timestamp is not the same?
Member.joined_at is a datetime.datetime
.timestamp() is a method of that datetime that returns a float representing the time in seconds since Jan 1st 1970 for that datetime
Ah I see. Is there any other way to do it without having to store it in seconds?
Not with mongo, otherwise we wouldn't be having this issue haha
True
But why does he need to save member.joined_at when it'll always be same and it is a direct attribute of a discord.Member 🗣️
Unknown
class UsefulEmbeds:
def __init__(self, bot: commands.Bot) -> None:
self.bot = bot
def failure_embed(self, title: str = None, desc: str = None):
embed = Embed()
embed.color = Color.red()
embed.description = desc
embed.title = title
embed.timestamp = datetime.now()
return embed
def success_embed(self, title: str = None, desc: str = None):
embed = Embed()
embed.colour = Color.green()
embed.description = desc
embed.title = title
embed.timestamp = datetime.now()
return embed
async def send_logs(self, channel_id):
print(channel_id)
_channel = self.bot.get_channel(channel_id)
print(_channel)
await _channel.send("check check")
@app_commands.command(name="command-1")
async def my_command(self, interaction: discord.Interaction) -> None:
""" /command-1 """
await UsefulEmbeds.send_logs(1239551237704122368)
await interaction.response.send_message("Hello from command 1!", embed=UsefulEmbeds.failure_embed("check", "check"), ephemeral=True)
what i am doing wrong why channel obj i am not getting
for some reason even print also not working
You are using them like staticmethods but did not define them as such

corrected
dont know why i didnt got any error
If you overrode your CommandTree.on_error you may have done so incorrectly
Try self.bot.get_channel(id) or self.bot.fetch_channel(id)
forgot to make an instance of the class
They want staticmethods not a stateful class
^^
So there's a lot of reworking to be done here
i am using eevie example
She made a CommandTree example?
import discord
import traceback
import sys
from discord.ext import commands
class CommandErrorHandler(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_command_error(self, ctx, error):
"""The event triggered when an error is raised while invoking a command.
Parameters
------------
ctx: commands.Context
The context used for command invocation.
error: commands.CommandError
The Exception raised.
"""
if hasattr(ctx.command, 'on_error'):
return
cog = ctx.cog
if cog:
if cog._get_overridden_method(cog.cog_command_error) is not None:
return
ignored = (commands.CommandNotFound, )
error = getattr(error, 'original', error)
if isinstance(error, ignored):
return
if isinstance(error, commands.DisabledCommand):
await ctx.send(f'{ctx.command} has been disabled.')
elif isinstance(error, commands.NoPrivateMessage):
try:
await ctx.author.send(f'{ctx.command} can not be used in Private Messages.')
except discord.HTTPException:
pass
elif isinstance(error, commands.BadArgument):
if ctx.command.qualified_name == 'tag list':
await ctx.send('I could not find that member. Please try again.')
else:
print('Ignoring exception in command {}:'.format(
ctx.command), file=sys.stderr)
traceback.print_exception(
type(error), error, error.__traceback__, file=sys.stderr)
This does not handle slash command errors
i just need to add slash right?
No
This is handled in CommandTree.on_error, so if you have not overriden it yourself then you're not using the library's logging
on_error is there in the code
Not on the CommandTree class
Hence prefixing it with CommandTree.
!d g discord.app_commands.CommandTree.on_error
await on_error(interaction, error, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A callback that is called when any command raises an [`AppCommandError`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.AppCommandError).
The default implementation logs the exception using the library logger if the command does not have any error handlers attached to it.
To get the command that failed, [`discord.Interaction.command`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction.command) should be used.
The default implementation is sufficient so long as you use the library's logging
ctx does not matter, your above codeblock is irrelevant
That is for ext.commands NOT application commands
@spice warren so i now is there any different method of on_command_error?
This enables logging by default, do you change any of the logging parameters?
yes i implemented my own logging
I have found why you are having issues then, please show me your Bot.run() line and remove any tokens that may be present
from loguru import logger
from datetime import datetime
logger.add("logfile.log", level="INFO",
format="{time} {level} {message}", rotation="500 MB")
discord_logger = logger.bind(source='discord')
discord_http_logger = logger.bind(source='discord.http')
def get_timestamp():
return datetime.now().strftime("%Y-%m-%d %H:%M:%S")
def log_message(log_level, message):
timestamp = get_timestamp()
formatted_message = f"{timestamp} {message}"
logger.opt(depth=1).log(log_level, formatted_message)
dont worry i use .env
you may wanna call discord.utils.setup_logging() and then look at the source of the method to adapt your logging situation correctly
You're not getting key items in logs
class MyBot(commands.Bot):
def __init__(self, *, intents: discord.Intents):
super().__init__(command_prefix='!', help_command=None, intents=intents)
async def setup_hook(self):
self.tree.copy_global_to(guild=MY_GUILD)
await self.tree.sync(guild=MY_GUILD)
async def on_ready(self):
log_message('DEBUG', f'Logged in as {self.user}(ID: {self.user.id})')
print('------')
def load_cog(self, file_path):
module = importlib.import_module(file_path)
for name, obj in inspect.getmembers(module):
if inspect.isclass(obj) and issubclass(obj, commands.Cog):
asyncio.run(self.add_cog(obj(self)))
log_message("INFO", f'Loaded {name} Cog')
def load_all_extensions(self):
directory = Path('bot/ext')
for item in directory.glob('*.py'):
if item.stem.startswith('_'):
continue
self.load_cog(f"afw_bot.ext.{item.stem}")
def run(self, *args, **kwargs):
self.load_all_extensions()
try:
super().run(*args, **kwargs)
except Exception as e:
log_message('CRITICAL', f"Login Failed\nReason: {e}")
def main():
intents = discord.Intents.default()
intents.members = True
intents.message_content = True
bot = MyBot(intents=intents)
bot.run(BOT_TOKEN, log_handler=None)
log_handler=None is why you're not getting any errors showing, lol
You'll need to override the error handling methods to use your handler stuff
i am getting double logging for some reason when i log_handler
is it present in docs or i need to look at source?
Because the library will do logging but so will your setup
this is for slash commands
ok
big error popped finally, i am happy now 😭
import discord
from discord import Interaction
from discord.ext import commands
class CommandErrorHandler(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_command_error(self, ctx, error):
"""The event triggered when an error is raised while invoking a command.
Parameters
------------
ctx: commands.Context
The context used for command invocation.
error: commands.CommandError
The Exception raised.
"""
if hasattr(Interaction.command, 'CommandTree.on_error'):
return
cog = ctx.cog
if cog:
if cog._get_overridden_method(cog.cog_command_error) is not None:
return
ignored = (commands.CommandNotFound, )
error = getattr(error, 'original', error)
if isinstance(error, ignored):
return
if isinstance(error, commands.DisabledCommand):
await ctx.send(f'{ctx.command} has been disabled.')
elif isinstance(error, commands.NoPrivateMessage):
try:
await ctx.author.send(f'{ctx.command} can not be used in Private Messages.')
except discord.HTTPException:
pass
elif isinstance(error, commands.BadArgument):
if ctx.command.qualified_name == 'tag list':
await ctx.send('I could not find that member. Please try again.')
else:
print('Ignoring exception in command {}:'.format(
ctx.command), file=sys.stderr)
traceback.print_exception(
type(error), error, error.__traceback__, file=sys.stderr)
can i pass Interaction to on_command_error?
This is not how you do this at all
Let me explain:
In your Bot constructor there's a parameter for tree_cls, you pass in a type (a Class) of a CommandTree subclass for your bot to use.
Since you want to override Logging for it, you need to make a CommandTree subclass, which overrides the on_error method to handle your logging and whatnot
You then pass this class to the aforemention tree_cls parameter
You don't patch it like you're trying above
can i read this tree_cls somewhere
i am sorry if i m using stupid question , am i suppose to subclass commandTree inside cog right?
oh so without cog it will get triggered?
No?
Sorry I'm not following your thought process here
Cogs have nothing to do with CommandTree
actually i am being lost here , you are trying your best to make me understand : ) dont be sorry
@spice warren i have to pass this on_command_error to tree cls right? and on_command error will be cog listner too?
There is no "passing" here. You implement on_error in the CommandTree subclass
That should all be declared inside that subclass, and then you would tell the bot the new CommandTree subclass you want it to use
oh so i just need to implenet on_error and then pass it to tree_cls and bot will keep listening right?
I don't think the word "pass" means what you think it means here
The on_error doesn't go anywhere. It's just implemented inside the subclass you make
from discord.ext.commands import Bot
custom_tree = CustomCommandTree()
bot = Bot(command_prefix="!", tree_cls=custom_tree)
this is what i meant
that customCommandTree is error handler
ok
from discord.ext.commands import CommandTree
class CustomCommandTree(CommandTree):
async def on_error(self, event_method, *args, **kwargs):
pass
and this will be custom tree
on_error has a very specific signature
you can't ask for other parameters that the library isn't going to give it
ok btw i am implementing in right way right other than this?
- on_error only receives (self, interaction, error)
- you're passing an instance of a commandtree, not a class that inherits it
- really depends on the implementation you make
also commands.CommandTree 
class RadioDropdown(nextcord.ui.View):
def __init__(self, options):
super().__init__()
self.options = options
self.page_number = 1
self.options_per_page = 25
self.button_back = self.children[0]
self.button_next = self.children[1]
self.SelectRadio = SelectRadio([], self.button_back, self.button_next)
self.add_item(self.SelectRadio)
self.update_select()
def update_select(self):
start_index = (self.page_number - 1) * self.options_per_page
end_index = start_index + self.options_per_page
options_page = self.options[start_index:end_index]
self.SelectRadio.options = options_page
def update_select_radio_options(self, options):
self.options = options
self.update_select()
@nextcord.ui.button(label="<< Prev", style=nextcord.ButtonStyle.secondary, disabled=True)
async def r_previous_page(self, button: nextcord.Button, inter: nextcord.Interaction):
if self.page_number > 1:
self.page_number -= 1
self.update_select()
self.button_back.disabled = self.page_number == 1
self.button_next.disabled = False
await inter.response.edit_message(view=self)
@nextcord.ui.button(label="Next >>", style=nextcord.ButtonStyle.secondary)
async def r_next_page(self, button: nextcord.ui.Button, inter: nextcord.Interaction):
total_pages = (len(self.options) - 1) // self.options_per_page + 1
if self.page_number < total_pages:
self.page_number += 1
self.update_select()
self.button_back.disabled = False
self.button_next.disabled = self.page_number == total_pages
await inter.response.edit_message(view=self)```
class SelectRadio(nextcord.ui.Select):
def __init__(self, options, button_back, button_next):
super().__init__(placeholder="Choose a radio", min_values=1, max_values=1, options=options)
self.options = options
self.button_back = button_back
self.button_next = button_next
async def callback(self, inter: nextcord.Interaction):
return print("YAY")```
Error
Traceback (most recent call last):
File "C:\VSCode\Python\Lib\site-packages\nextcord\ui\view.py", line 386, in _scheduled_task
await item.callback(interaction)
File "c:\VSCode\Antonio-Beta\modules\voice\view.py", line 49, in next_page
await inter.response.edit_message(view=self)
File "C:\VSCode\Python\Lib\site-packages\nextcord\interactions.py", line 1065, in edit_message
await adapter.create_interaction_response(
File "C:\VSCode\Python\Lib\site-packages\nextcord\webhook\async_.py", line 200, in request
raise HTTPException(response, data)
nextcord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In data.components.1.components.0.options.8: The specified option value is already used```
from discord.app_commands import CommandTree
from discord import app_commands
class CustomCommandTree(CommandTree):
async def on_error(self, interaction, error):
ignored = (app_commands.CommandNotFound, )
error = getattr(error, 'original', error)
if isinstance(error, ignored):
return
elif isinstance(error, app_commands.NoPrivateMessage):
try:
await interaction.author.send(f'{interaction.command.name} can not be used in Private Messages.')
except discord.HTTPException:
pass
elif isinstance(error, app_commands.BadArgument):
if interaction.command.qualified_name == 'tag list':
await interaction.response.send_message('I could not find that member. Please try again.')
else:
print('Ignoring exception in command {}:'.format(
interaction.command.name), file=sys.stderr)
traceback.print_exception(
type(error), error, error.__traceback__, file=sys.stderr)
this seems correct?
First step here would be to debug out the options you're putting on your select. One of them is duplicated (at least)
I checked them already
There are no duplicates
How?
Debug and copilot
I mean the error and discord aren't lying to you
Want to check yourself?
This client already has an associated command tree. this error i am getting when i try
async def setup_hook(self):
CommandErrorHandler(self)
self.tree.copy_global_to(guild=MY_GUILD)
await self.tree.sync(guild=MY_GUILD)
Bot already has a command tree. this is why I told you to use the tree_cls kwarg in the Bot constructor, remember?
yes
I cheked it again and there a no duplicates
can you visualise the file tree for me?
use this: https://tree.nathanfriend.io
and then give us some
!code
class MyBot(commands.Bot):
def __init__(self, *, intents: discord.Intents):
super().__init__(command_prefix='!', help_command=None,
intents=intents, tree_cls=CommandErrorHandler)
i have passed it to contructor have u checked my code above i sent of commanderrorhandler?
You have some errors, yes, like interaction.author
other than that format looks good?
Without seeing how you're checking it, I have no idea if you're checking it correctly
You appear to have just copy pasted your ext.commands handler which isn't very good
Since that handler does weirdly specific things in an elif that just aren't relevant
Try running the code, you'll see the errors
my commands are guild specific it wont trigger error : (
how should i handle it though?
Remove the irrelevant code...?
Please run it, I don't want to pick apart every little issue. You shouldn't have copy pasted the ext.commands one, so you'll just need to debug on your own a bit
i am already running it and not getting any error, asked you just for the insight and dont know why that code is wrong above
You mean the options right?
Yup, and you'll want to log it out every time it gets changed (which seems to be the issue, not when it's sent initially)
No, i have over 25 options. There should be 2 pages. First Page with the first 25 options. Secound Page the rest amount of options
Every time you are modifying the active options on a select and then resending it
You have some path where you are winding up with duplicate options
Where
Thats the problem. I dont fif any duplicate
How are you checking?
Printing
Code?
class RadioDropdown(nextcord.ui.View):
def __init__(self, options):
super().__init__()
self.options = options
self.page_number = 1
self.options_per_page = 25
self.button_back = self.children[0]
self.button_next = self.children[1]
self.SelectRadio = SelectRadio([], self.button_back, self.button_next)
self.add_item(self.SelectRadio)
self.update_select()
def update_select(self):
start_index = (self.page_number - 1) * self.options_per_page
end_index = start_index + self.options_per_page
options_page = self.options[start_index:end_index]
self.SelectRadio.options = options_page
def update_select_radio_options(self, options):
self.options = options
self.update_select()
@nextcord.ui.button(label="<< Prev", style=nextcord.ButtonStyle.secondary, disabled=True, row=1)
async def r_previous_page(self, button: nextcord.Button, inter: nextcord.Interaction):
if self.page_number > 1:
self.page_number -= 1
self.update_select()
self.button_back.disabled = True
self.button_next.disabled = False
await inter.response.edit_message(view=self)
@nextcord.ui.button(label="Next >>", style=nextcord.ButtonStyle.secondary, row=1)
async def r_next_page(self, button: nextcord.ui.Button, inter: nextcord.Interaction):
total_pages = (len(self.options) - 1) // self.options_per_page + 1
if self.page_number < total_pages:
self.page_number += 1
self.update_select()
self.button_back.disabled = False
self.button_next.disabled = True
await inter.response.edit_message(view=self)```
Where is the print?
Ah wait
@fast osprey
def update_select(self):
start_index = (self.page_number - 1) * self.options_per_page
end_index = start_index + self.options_per_page
options_page = self.options[start_index:end_index]
self.SelectRadio.options = options_page
print(options_page)``` here
import discord
from discord.ext import commands, tasks
from discord import app_commands
import os, mysql.connector, random, aiohttp
color_lace = discord.Color.from_rgb(60, 161, 224)
class Autopfp(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.database = mysql.connector.connect(host=os.getenv("MYSQL_HOST"), port=os.getenv("MYSQL_PORT"), user=os.getenv("MYSQL_USER"), password=os.getenv("MYSQL_PASSWORD"), database=os.getenv("MYSQL_DATABASE"))
self.send_pfp.start()
@tasks.loop(minutes=1)
async def send_pfp(self):
return # programing....```
elif isinstance(error, app_commands.MissingAnyRole):
await interaction.response.send_message(f'{error} missing role')
You are missing at least one of the required roles: 'Library Devs'
how can i get the role name? from my error handler? its working correctly just need the role name
{role.name}``` ?
i am inside error handler buddy
just parse it from the error string
i need to extract it? doesnt it have any property or something which shows?
But 99 times out of 100 you shouldn't be using this check to begin with, when the integrations UI exists to role lock commands
@fast osprey error: py Cog error: autopfp: Extension 'src.cogs.autopfp' raised an error: AttributeError: 'Autopfp' object has no attribute 'send_pfp'
You nested that inside your init
me?
yes
i purposefully triggered the error as link pointed i am doing something wrong which i am not supposed to , he didnt pointed where i am doing wrong just said i have copied pasted the code, till now my code works fine, i am just trying to figure out is there any property or something which tells the role or particular error part?
The loop function needs to be outside your init
Having a weird issue with my self-hosted bots (VirtualBox, Windows 10 VM) and I don't know if anyone here has any ideas.
I only started experiencing this issue the last few months. My bots will go through the regular
discord.errors.ConnectionClosed: Shard ID None WebSocket closed with 1000
INFO discord.gateway Shard ID None has successfully RESUMED session```
cycle and they used to be fine about waking back up themselves but lately they just die and I have to manually interact with the command line running them to get them back up.
I've done everything I can think of to make sure the VMs are staying fully awake but they keep going to sleep. Happy to provide code but its happening on all my bots, several of which have entirely different codebases.
Any advice would be appreciated.
I linked you that property, then explained you probably shouldn't be using this check to begin with
why not either:
- move the headers to be a bot attribute so you can use it in whatever cog you're using
- move the headers into
command1.py
tnx works like a charm
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.
But 99 times out of 100 you shouldn't be using this check to begin with, when the integrations UI exists to role lock commands can u explain a bit more @fast osprey on this if u dont mind : )
There's a duplicate in there
the values have to be unique
You can control which roles can run which commands in-app. Server settings -> integrations -> your command. This prevents people from running the command or even seeing it in the first place, so you don't have to locally check and error in your code
Where
Your second list. The value https://streams.ilovemusic.de/iloveradio15.mp3 is in there twice
i really forgot about that ty i will keep this in mind
Oh my debug does not show that
Also my fried was tired
whats the error you were getting?

wait so you're importing command1 into bot.py
but expecting it to work the other way around?
@viscid hornet
what
He wants autograph
code: ```py
import discord
from discord.ext import commands, tasks
from discord import app_commands
import os, mysql.connector, random, aiohttp
color_lace = discord.Color.from_rgb(60, 161, 224)
class Autopfp(commands.Cog):
def init(self, bot):
self.bot = bot
self.database = mysql.connector.connect(host=os.getenv("MYSQL_HOST"), port=os.getenv("MYSQL_PORT"), user=os.getenv("MYSQL_USER"), password=os.getenv("MYSQL_PASSWORD"), database=os.getenv("MYSQL_DATABASE"))
self.send_pfp.start()
@tasks.loop(minutes=1)
async def send_pfp(self):
print("Funcionando...")``` error: ```Cog error: autopfp: Extension 'src.cogs.autopfp' raised an error: AttributeError: 'Autopfp' object has no attribute 'send_pfp'``` how can fix?

It's a task 🗣️

how fix
Move it outside the __init__
Indentation
what move?
or remove self from it and start it like send_pfp.start()
The task
send_pfp function is inside __init__ function
Cog error: autopfp: Extension 'src.cogs.autopfp' raised an error: UnboundLocalError: local variable 'send_pfp' referenced before assignment```
move the @tasks.loop stuff one indent (4 spaces) backwards
and everything else in the loop - move that an indent backwards
# outside the class
def foo(...):
...
class Foo:
def bar(self):
# inside a method <- you, bad
def foo():
...
# in the class <- good
def foo(self):
...

gg

import discord
from discord.ext import commands, tasks
from discord import app_commands
import os, mysql.connector, random, aiohttp
color_lace = discord.Color.from_rgb(60, 161, 224)
@tasks.loop(minutes=1)
async def send_pfp():
print("Funcionando...")
class Autopfp(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.database = mysql.connector.connect(host=os.getenv("MYSQL_HOST"), port=os.getenv("MYSQL_PORT"), user=os.getenv("MYSQL_USER"), password=os.getenv("MYSQL_PASSWORD"), database=os.getenv("MYSQL_DATABASE"))
send_pfp.start()```
@viscid hornet Is it still okay?
try it and see?
that wasnt what i meant
@timber dragon does it look... decent at the very least?
code work :v
fair enough

That works too if you don't need it to be part of the class 

@viscid hornet
im stupid
now work
import discord
from discord.ext import commands, tasks
from discord import app_commands
import os, mysql.connector
color_lace = discord.Color.from_rgb(60, 161, 224)
class Autopfp(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.database = mysql.connector.connect(host=os.getenv("MYSQL_HOST"), port=os.getenv("MYSQL_PORT"), user=os.getenv("MYSQL_USER"), password=os.getenv("MYSQL_PASSWORD"), database=os.getenv("MYSQL_DATABASE"))
@self.bot.event
async def on_ready():
self.send_pfp.start()
@tasks.loop(minutes=1)
async def send_pfp(self):
print("Funcionando...")
try:
cursor = self.database.cursor()
cursor.execute("SELECT guild_id, channel_id FROM autopfp")
results = cursor.fetchall()
for guild_id, channel_id in results:
guild = self.bot.get_guild(guild_id)
if guild:
channel = guild.get_channel(channel_id)
if channel:
webhooks = await channel.webhooks()
if not webhooks:
webhook = await channel.create_webhook(name=self.bot.user.name)
else:
webhook = webhooks[0]
await webhook.send("skibidi", username=self.bot.user.name, avatar_url=self.bot.user.avatar.url)```
Should I implement aiohttp so that it sends the webhook with aiohttp or should I leave it like that?
@slate swan
why would you need aiohttp for that?

I do not know :v


|| (you can start the loop in the __init__) ||
For what purpose?
I don't know, yesterday when I was asking questions about the code and etc. they told me to use task, aiohttp and webhook

Why would you add it if you have no reason to use it
Or you need it in your code?
well I think it's better not to use it
-bot
|
|----bot.py
|----cogs
|-----autopfp.py
|----init.py
?
webhook.send skibidi

@viscid hornet
code: ```py
random_member = random.choice(guild.members)
avatar_url = random_member.avatar.url
embed = discord.Embed(color=color_lace)
embed.set_image(url=avatar_url)
await webhook.send(embed=embed, username=self.bot.user.name, avatar_url=str(self.bot.user.avatar_url))``` error: ```Error: 'ClientUser' object has no attribute 'avatar_url'```
avatar.url not avatar_url
Consider using..display_avatar
soheeeeeeeeeeeeb
sohe
soheap 
sostack
sostackoverflow
because?
it will never be None
thx
ihave a error with banner
import discord
from discord.ext import commands
from discord import app_commands
color_lace = discord.Color.from_rgb(60, 161, 224)
class Banner(commands.Cog):
def __init__(self, bot):
self.bot = bot
@app_commands.command(name="banner", description="Muestra el banner de una persona")
@app_commands.describe(user="el usuario a mostrar")
async def banner(self, interaction: discord.Interaction, user: discord.Member = None):
try:
user = user or interaction.user
embed = discord.Embed(color=color_lace)
embed.set_image(url=user.banner.url)
await interaction.response.send_message(embed=embed)
except Exception as e:
await interaction.response.send_message(f"Error: {e}", ephemeral=True)
async def setup(bot):
await bot.add_cog(Banner(bot))```
has no atributte .url
has no atributte .url
code?
import discord
from discord.ext import commands
from discord import app_commands
color_lace = discord.Color.from_rgb(60, 161, 224)
class Banner(commands.Cog):
def __init__(self, bot):
self.bot = bot
@app_commands.command(name="banner", description="Muestra el banner de una persona")
@app_commands.describe(user="el usuario a mostrar")
async def banner(self, interaction: discord.Interaction, user: discord.Member = None):
try:
user = user or interaction.user
embed = discord.Embed(color=color_lace)
embed.set_image(url=user.banner.url)
await interaction.response.send_message(embed=embed)
except Exception as e:
await interaction.response.send_message(f"Error: {e}", ephemeral=True)
async def setup(bot):
await bot.add_cog(Banner(bot))```
wait
did u read this at all
no
there's your problem
@viscid hornet pls
Traceback (most recent call last):
File "/mnt/games-auto/PythonProjects/UniBot-Rev/.venv/lib/python3.11/site-packages/discord/ext/commands/hybrid.py", line 438, in _invoke_with_namespace
value = await self._do_call(ctx, ctx.kwargs) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/mnt/games-auto/PythonProjects/UniBot-Rev/.venv/lib/python3.11/site-packages/discord/app_commands/commands.py", line 846, in _do_call
raise CommandInvokeError(self, e) from e
discord.ext.commands.errors.HybridCommandError: Hybrid command raised an error: Command 'nickedit' raised an exception: Forbidden: 403 Forbidden (error code: 50013): Missing Permissions```
```py
elif isinstance(error, commands.CommandInvokeError):
if isinstance(error.original, discord.Forbidden):
member = ctx.message.mentions[0] if ctx.message.mentions else None
if member:
if ctx.author.top_role < member.top_role:
error_embed = ErrorEmbed(
title="Error",
description="You cannot perform this action due to role hierarchy.",
)
await ctx.send(embed=error_embed, ephemeral=True)
elif ctx.guild.me.top_role <= member.top_role:
error_embed = ErrorEmbed(
title="Error",
description="I cannot perform this action due to role hierarchy.",
)
await ctx.send(embed=error_embed, ephemeral=True)
else:
error_embed = ErrorEmbed(
title="Error",
description="I don't have the necessary permissions to perform this action.",
)
await ctx.send(embed=error_embed, ephemeral=True)```
This part of my error handling should handle that error if im not wrong..?
did you try comparing error codes? the discord.Forbidden error is quite general imo
!paste it for me so i can see syntax on phone
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.
what
property banner```
Returns the user’s banner asset, if available.
New in version 2.0.
Note
This information is only available via [`Client.fetch_user()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.fetch_user).
Yes but if im not wrong, I have an else at the end, which would just send if the other 2 do not fit.
wait why are you sending an ephemeral w ctx?
That was done by jiggly 
Actually, I know why he did it I think, because we are using Hybrid
ohh ok i see
!d discord.ext.commands.CommandInvokeError.original
The original exception that was raised. You can also get this via the __cause__ attribute.
I am just trying to understand why the error handling is not working properly..? Cuz It used to work I thought lmao
Unless jiggly fucked it up, cuz I haven't touched it since jiggly did whatever he did 😭
what level does it stop working at?
does it miss the command invoke error completely?
also i think discord.Forb is its own separate error to CIE
I was testing the last level, the else part
to see if it would just give an error for when I tried to change my nick name with my bot, which should return last level
ah ok i see
i meant for the error
@viscid hornet
import discord
from discord.ext import commands, tasks
from discord import app_commands
import os, mysql.connector, random, time
color_lace = discord.Color.from_rgb(60, 161, 224)
class Autopfp(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.database = mysql.connector.connect(host=os.getenv("MYSQL_HOST"), port=os.getenv("MYSQL_PORT"), user=os.getenv("MYSQL_USER"), password=os.getenv("MYSQL_PASSWORD"), database=os.getenv("MYSQL_DATABASE"))
time.sleep(1)
self.send_pfp.start()
@tasks.loop(minutes=1)
async def send_pfp(self):```

alr
.
hi
how do i sync bot.tree.command
like
globally not guild specific
await bot.tree.sync()
got it thanks
i have this code here where im trying to make it evaluate code if the code block starts with ``` or ```py. so far doing ``` works but ```py doesnt and its giving this error:
NameError: name 'py' is not defined
Traceback (most recent call last):
File "/Users/st1xkz/bobert/bobert/plugins/admin/eval.py", line 189, in mention_eval
await fn()
File "<ast>", line 2, in __bobert_eval
NameError: name 'py' is not defined
heres the code: https://pastes.dev/xAoiG9RKzn
wait nvm i fixed it
How do I catctch fish in python
import random
def fish():
# Fish types and their probabilities
fish_types = ["salmon", "trout", "bass", "catfish"]
probabilities = [0.4, 0.3, 0.2, 0.1]
# Catch a fish based on probabilities
fish_index = random.choices(range(len(fish_types)), weights=probabilities)[0]
return fish_types[fish_index]
def main():
print("Let's go fishing!")
while True:
input("Press Enter to cast the line...")
caught_fish = fish()
print(f"You caught a {caught_fish}!")
if input("Do you want to keep fishing? (yes/no): ").lower() != "yes":
print("Thanks for fishing with us!")
break
if __name__ == "__main__":
main()
provided by chat gpt 💯
!rule 10 
Sure, I can guide you through creating a simple fishing game in Python.
First, you'll need to decide on the rules and mechanics of your game. Here's a basic outline:
Setting up the game: Define the environment, such as the lake or river where the fishing will take place.
Casting the line: Allow the player to cast their fishing line into the water.
Catching fish: Simulate the process of catching fish. You can have different types of fish with varying probabilities of being caught.
Displaying the catch: Show the player what fish they caught.
Repeat or end the game: Ask the player if they want to keep fishing or end the game.
Here's a simplified version of how you could implement this in Python:

i wouldn't be surprised if i got ban for this
python is full of serious bussnies men/women
dont do that again. you've been told copy pasting answers from chatgpt violates our rules
Out of curiosity, why?
In general, ai cannot be trusted always for helping with programming, they can be wrong at times
There are chances it can spread misinformation
It was trained on the internet. If anybody is to blame its us lol
i suck at math but i wouldn't blame it on the book
You don’t understand lol.
If you’re taught in school that Ireland is a fake country, you will spread that information. It’s not your fault, it’s what you were taught. You may eventually learn it’s real but that’s beyond the point, you were taught wrong. That’s the same with ai. It is taught wrong information because we are feeding it wrong information, it’s not its fault.
It can only spread what it knows and what it might know is misinformation put on the internet by us
Your lack of understanding and of math is only due to your inability to learn, not the books fault. But if the book told you that 1+1 is 5 you might learn that. You might eventually teach it to others. But it isn’t your fault it’s the books
There's a thing called hallucination in LLMs
They can just make stuff up, in simple terms
Probably because doing that doesn't teach you anything and chatgpt can generate even more bugs
i have to check for some stuff everytime before bot starts should i keep those stuff under on_ready or some other event?
setup_hook event would be recommended as its called only once
I dont really know, I think both events are called when bot is ready, not before
oh i have setup_hook and on_ready both should i remove one?
Or, another thing is that they're not perfect (yet?)
setup_hook is called before making a connection to Discord, if I remember correctly
!d discord.Client.setup_hook
await setup_hook()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A coroutine to be called to setup the bot, by default this is blank.
To perform asynchronous setup after the bot is logged in but before it has connected to the Websocket, overwrite this coroutine.
This is only called once, in [`login()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.login), and will be called before any events are dispatched, making it a better solution than doing such setup in the [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready) event.
Warning
Since this is called *before* the websocket connection is made therefore anything that waits for the websocket will deadlock, this includes things like [`wait_for()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.wait_for) and [`wait_until_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.wait_until_ready)...

hmmm
looks like on_ready should be the one i should look into
i want to setup the persistent view for 2 embeds without triggering the command
both will have buttons for interaction
yeah then you should use setup hook
another thing i want to ask since bot will fetch data of channel, it will require websocket connection right?
Can someone help as to why isnt discord.errors.Forbidden getting caught in the error handler? This only arises when someone uses a slash command of my bot and it requires to edit a message it sent
class ErrorHandler(commands.Cog):
def __init__(self, bot: Bot):
self.bot = bot
@discord.Cog.listener()
async def on_ready(self):
print(f"{Path(__file__).name} cog is ready.")
@commands.Cog.listener()
async def on_application_command_error(
self, ctx: discord.ApplicationContext, error: discord.DiscordException
):
print(error)
print(error.args)
print()
if isinstance(error, discord.errors.Forbidden):
print("forbidden", error.code)
print(error.response)
print(error.status)
print(error.text)
if error.code == 50001:
try:
await ctx.author.send(
embed=QuickEmbed(
f"I'm missing access to the channel {ctx.channel.mention}.",
error=True,
)
)
except (discord.Forbidden, discord.HTTPException):
pass
and this is the error
Task exception was never retrieved
future: <Task finished name='discord-ui-view-timeout-1ae31f094207752942515d267d455739' coro=<View.on_timeout() done, defined at C:\Users\...\Documents\Python\DISCORD BOTS\RainDot-V3\venv\Lib\site-packages\discord\ui\view.py:364> exception=Forbidden('403 Forbidden (error code: 50001): Missing Access')>
Traceback (most recent call last):
File "C:\Users\...\Documents\Python\DISCORD BOTS\RainDot-V3\venv\Lib\site-packages\discord\ui\view.py", line 378, in on_timeout
m = await message.edit(view=self)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\...\Documents\Python\DISCORD BOTS\RainDot-V3\venv\Lib\site-packages\discord\message.py", line 1528, in edit
data = await self._state.http.edit_message(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\...\Documents\Python\DISCORD BOTS\RainDot-V3\venv\Lib\site-packages\discord\http.py", line 367, in request
raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access
im trying to dm the author that it doesnt have the required perms
but for some reason on_application_command_error isnt even being called
im using pycord btw
do those prints work?
u sure that cog is loaded?
its actually from a drop down not from the slash command actually, the drop down's callback edits the orignal message but fails to do so
@commands.Cog.listener()
async def on_application_command_error(
self, ctx: discord.ApplicationContext, error: discord.DiscordException
):
print("I am in") # <--- can u add something like this to check if it works?
print(error)
print(error.args)
print()
oh ok that makes sense now
views error handling is different
oh
it dosent come under application command handler
views themselves have an on_error https://docs.pycord.dev/en/stable/api/ui_kit.html#discord.ui.View.on_error
The library has helpers to help create component-based UIs. Shortcut decorators: Objects: Attributes children, disable_on_timeout, message, parent, timeout. Methods cls View.from_message, def add_i...
u need to check inside that
np
suppose i am taking data from modal and then sending it to a api incase api takes long time for response after how many minute interaction will fail?
3 seconds if undefered. 15 minutes if defered
ok
!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...
What is the Redirect URi and how do I set it up?
!d discord.TextChannel.create_thread
await create_thread(*, name, message=None, auto_archive_duration=..., type=None, reason=None, invitable=True, slowmode_delay=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a thread in this text channel.
To create a public thread, you must have [`create_public_threads`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.create_public_threads). For a private thread, [`create_private_threads`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.create_private_threads) is needed instead.
New in version 2.0.
if i use the message kwargs it will be automatically be converted to public thread?
is there a way so i can add role to a private thread?
or u can pass type=discord.ChannelType.public_thread
Omg. I just got what Kwargs means! It’s key word arguments!
noice
🎉 🎉
i dont want to make it public
i want to add roles to it
pass private_thread then
without type also private thread is automatically created if i dont pass message kwargs , mainly i am trying to add roles
Yep. Just came to me while I was scoffing down a toasted sammich
hmm dont see anything related to adding roles in threads, doubt thats allowed
roles are not allowed to get pinged?
u can ping
then might be allowed to add role or i am coping 😭
but no way to explicitly allow only a particular role from what i see
when you ping a role it acts as a multi ping
means?
just test it out
Just create a new channel that has the roles and permissions you want and put the thread there lol
so ping the role to asd a bunch of ppl w that role
actually i am trying to add particular role and ping all the people with that role, so they can help others
basically:
- make the thread
- send a message with the role mention
- done
alright
Guys
?
You are overthinking it. New channel limited to perms. Put thread onto said channel
:D
i am using private thread
when you ping the role it’ll add people to it
i am replying to @drifting arrow i get your point
👌
@drifting arrow private thread will work like this, it will not use channel role perms

I honestly didn’t know what you guys were discussing I was just putting my two cents in
True successor of @viscid hornet
axo 
How do I setup the Redirect URi for my bot?
ray (stab)
what meant by channel override? in app integration of server settings?
On developers portal
I’m pretty sure it means you override the server settings.
means bot will inherit those permission instead of deault ones right?
and bot dont change those setting if i restart right?
Channel override changes the settings in the channel not bot
sorry i meant app intergration
Bot's integration overrides?
You can allow or disallow specific commands to be used in specific channel or by specific member
If you meant integration app overrides from the server settings
This
Yup
If you disallow it
ok so in simple terms i can remove that command from there
Yes
if something is not there means it will be shown in every channel right?
what will happen like if i have 2 role and they are opposite of each other like one allows to send message and other dont which will take precedence
The higher one
I think it will work similar to channel overrides
Which means this
you meant the one which is above? in role section?
Yes
Role 1 - disallowed
Role 2 - allowed
Role 3 - disallowed
Everyone
If user has all roles he can't use command because highest role is disallowed
If you remove Role 1 from their roles they can use it because now highest role is Role 2
the sent message one
just check if the top role is role 2
ray i saw that
How to check if a embed contains a specific word or not
which part of the embed?
if "rare catch detected" in msg.embeds.title.lower():
Title
msg.embeds[0].title.lower() embeds here is a list of embeds in a message
afaik a message can have upto 5 embeds i think
its an android :(
ratelimited
abusing discord resources against ToS
repl it isnt good for discord bots anymore
it used to be but not anymor
it never was
oracle vps best for free
i prefer digital ocean, hetzner etc
24/7 , 200 GB Disk , 4 core CPU and 24 GB ram is a LOT and the BEST for a free thing specially by a big company like oracle...
u need a credit card tho afaik and if u dont mind about data security
How do I check if a msg have an embed
oracle dosent really have the best reputation for data safety practices
if msg.embeds: <-- empty list if no embeds
I see
thats the problem , and i dont have one :(
dis free without credit card ?
its not free, nothings free almost everything has a clause or price attached lol
those are cheaper alternatives
especially the arm vms
welp fadfddsf
Why would someone pay their own money to run something for you, a rando, forever.
List don't have attribute length??
len(msg.embeds)
or if ur feeling fancy msg.embeds.__len__()
@commands.Cog.listener()
async def on_message(self, msg):
if msg.author == self.bot.user or len(msg.embeds) == 0:
return
if "rare catch detected" in msg.embeds[0].title.lower() :
await self.bot.get_channel(rare_channel_id).send(msg.content)
await self.bot.get_channel(rare_channel_id).send("hi")
elif "shiny catch detected" in msg.embeds[0].title.lower():
await self.bot.get_channel(shiny_channel_id).send(msg.content)
else:
print("nothing")
I don't get it
title of the embed is None
meaning the embed dosent have a title, u might wanna do print(msg.embeds[0].to_dict()) to see contents of the embed
Tysm!!
u use uptimer robot ?
It doesn't work after change of policies in Jan 2024
can i get names of all the thread private/public of a channel?
!d discord.TextChannel.threads
property threads```
Returns all the threads that you can see.
New in version 2.0.
im so smart
dont think threads.name will work : ( and just give me list with names
In your dreams
its a list of threads the bot can see in the channel
it returns threads object right?
yeah?
Returns all the threads that you can see.
i want just name i neeed to loop and then check one by one : I
your_thread.name
Inside of a given text channel
yeah i get that i am not saying i dont know i am looking for efficient handling
He's smart enough to understand unlike you
^^
alright thats it buddy
no more mr nice guy
i have just string name i have to match against the name

"the string" == thread.name
it will still take time
or if you wanna search all threads for the name, use utils.get: py utils.get(your_text-channel.threads, name = 'the string')
!d discord.utils.get
discord.utils.get(iterable, /, **attrs)```
A helper that returns the first element in the iterable that meets all the traits passed in `attrs`. This is an alternative for [`find()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.utils.find).
When multiple attributes are specified, they are checked using logical AND, not logical OR. Meaning they have to meet every attribute passed in and not one of them.
To have a nested attribute search (i.e. search by `x.y`) then pass in `x__y` as the keyword argument.
If nothing is found that matches the attributes passed, then `None` is returned.
Changed in version 2.0: The `iterable` parameter is now positional-only.
Changed in version 2.0: The `iterable` parameter supports [asynchronous iterable](https://docs.python.org/3/glossary.html#term-asynchronous-iterable)s...
yeah utils will do ty
👍
i forgot about utils existance
@latent pier you stink 🗣️
thinking abt it rn 😔
Is it that hard? 😔
woahhhh
Thinking that you're better
yes
if i try to send message in archived channel , channel will get auto unarchived?
no
probs will error
Heyo anyone can help me with this error please ? Its for a bot who make a announcment when a new product or restock is made on the taylorswift-store.fr
2024-05-14 14:36:42 INFO discord.gateway Shard ID None has connected to Gateway (Session ID: 453a32f612f9574a037d597dd2f9f235).
INFO:discord.gateway:Shard ID None has connected to Gateway (Session ID: 453a32f612f9574a037d597dd2f9f235).
Logged in as Restock#5326
DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): taylorswift-store.fr:443
DEBUG:urllib3.connectionpool:https://taylorswift-store.fr:443 "GET //products.json?limit=250 HTTP/1.1" 200 None
INFO:__main__:Taylor Swift Store FR Has Been Cached (37 Products)
DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): taylorswift-store.fr:443
DEBUG:urllib3.connectionpool:https://taylorswift-store.fr:443 "GET //products.json?limit=250 HTTP/1.1" 200 None
WARNING:__main__:Taylor Swift Store FR 'int' object is not subscriptable```
are you allowed to do this?
Yes i think because on Taylor Swift discord they do this
I have just take the js code and translate in py
Translate how?
i have ask ChatGPT because i'm not good in js
thats because its the TS discord
its their website and its their service
Why do they open source the thing? I wonder now
good point
Ah, it's not official then
https://github.com/andrewc2/LHWB-Bot/tree/main
If you want to see the bot they have put open source
A Discord bot for Taylor Swift music. Contribute to andrewc2/LHWB-Bot development by creating an account on GitHub.
He do merch announcement, music and others things
The bot is used in r/Taylor Swift discord and Swifties discord and maybe more because its explained how to start the bot on ubuntu
I just want French Swifties can know when we get a restock or a new product on the french store because everytimes we don't know and everythings is out of stock in 2 minutes
!paste @shrewd vapor put your code here and send us the link
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.
Delusional
do you know any python
check_thread_exists = discord.utils.get(await interaction.client.fetch_channel(REGISTER_REP_CHANNEL_ID).threads, name=thread_title)
interaction.client.fetch_channel(REGISTER_REP_CHANNEL_ID).threads, name=thread_title)
AttributeError: 'coroutine' object has no attribute 'threads'
why???
I see request in coroutine
!d discord.TextChannel.threads
property threads```
Returns all the threads that you can see.
New in version 2.0.
Yes
then why its erroring out
it's a coroutine, you should be awaiting it
interaction.client?
oh nvm you are
nope its not
discord.util is not coroutine
He was talking about fetch channel
already did
That's what he said
here's your issue
await fetch_channel(...).threads
``` means
You're awaiting .threads ```py
(await fetch_channel(...)).threads
``` is what u need
make it little simple and get a channel variable
channel = await bot.fetch_channel()
i am inside view i need to add more constructor value then also : (
^ i would also suggest to use bot.get_channel(...) or await bot.fetch_channel(...) if you have cache enabled
^^
That's better option
if get_channel doesnt return channel it'll pass onto fetch which will make a api call
i subclass my Bot class and make a getch function to implement this, just for sake of comfort
‘’hi’’
😭 wow
Dude think it's a dating server
‘Hello’
That's something interesting I'd like to implement on my code
Then i don't have to repeat it over and over everywhere
Hello
i stole that idea from disnake
!d disnake.Client.getch_user
await getch_user(user_id, *, strict=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Tries to get the user from the cache. If it fails, fetches the user from the API.
This only propagates exceptions when the `strict` parameter is enabled.
steling ideas is bad ....
welcome to open source
I never checked disnake, i steal most of ideas from pycord 😂
you could rather say i took inspiration from lol
i made abot i will showcase it now
Welcome to programming
its highly skidded tho
nope i literally copy pasted it
it's just 2 lines of code so
not new to programming bruh
oh god I have a love and hate relationship with pycord
still that sounds better
Wait they were rewriting it
MY BOT OPPP
I just love how their pycord guide is represented, easy to read and tons of examples
it's nice but the codebase lowkey sucks
in the end the library you're able to work with is the best one for you 😊
Successfully Injected trojan.exe ( this is a prank guys dont get scared )
Dude is self boting
no i edit i made myself
nice selfbot, this is against discord tos
We all know
🤣 recorded, this is going to the mods.
it doesnt casue harm to API or anything so its fine
yes recorded and sended to discord
no one cares imao best of luck with dat
We have few discord moderators in this server 🤣
yea good luck
I saw that buddy:p stop being racist
don't worries, they respond in ~4h everytimes for me
yea LMFAO u didnt even send them
seems like someone from dat country got angry :<
Seems like 14 yo kid to me
Y'all are just feeding the troll rather than ignoring them lol
Jump: #discord-bots message
Self boting caught 📸
YOOOOO :DDDDD
it isnt causing any harm HOW MANY TIMES SHOULD I REPEAT
i care 🤚
Ayye Seedhe Maut 🤣
Ok , waste ur time , that just proves u have sorry but low iq
smkebinakyajeevan
btw it's programmer
ok ? more like 3 persons who dont understand ...
Holds more maturity than you?
don't understand what buddy, your first message in the channel was "any girls here?" !?
ok here is a suggestion , from this message lets stop fighting
Programmer*
Comma separation has a space after not before*
you*
your*
"u have sorry but low iq" ❌
😈 Are you scared lil buddy
nah when it comes to roasting i can handle it good but i dont recommend fighting in this channel , we may dm
is there any way to restore the interaction if my process take more time?
if you are understanding the meaning , doesnt matter
The buttons for it ?
ok
yes i use button then call api
The grammar teacher i need before my English exam 😭😭
just defer the response, and edit the response later
good luck for tomorrow
if you know it can take more time - defer it right away
No documentation found for the requested symbol.
Wtf is this bot high?
👀
bro be using slangs fr
nvm it's me
!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...
!d discord.Interaction.response returns an interaction response object
Returns an object responsible for handling responding to the interaction.
A response can only be done once. If secondary messages need to be sent, consider using followup instead.
!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...
And this^
ok so i just need to add defer after response and then send_message right?
Before
you defer at the start to "acknowledge" discord that you got the command and are going to respond to it
oh so interaction.defer.response.send_message?
you'll have to edit_initial_response after you're done with the stuff in your code to respond again
no, it wont be a single statement
you:
defer
do your stuff
async def test(interaction: nextcord.Interaction):
await interaction.response.defer()
await asyncio.sleep(10) # Doing stuff
await interaction.followup.send("My actual content", ephemeral=True)
Example
Not quite, you first interaction.response.defer - but you can only send a .response once per interaction, so you use interaction.followup.send to send what you want to the user
.send_message will fail
ok
where i can send the ephemeral?
i mean in followup will it work?
Yes
are u sure about it? checked docs yes it has
It's actually a bit nuanced.
If this is a button interaction, and you didn't defer(thinking=True), then you can set ephemeral=True in the followup.
For command interactions (and button interactions with thinking set to True), then the defer(ephemeral=...) will be used for the first followup, since all it's doing is editing the message rather than sending a new one.
For subsequent followup messages, then the ephemeral you pass to followup will always be respected.
got it, ty for the explanation
My exams already finished last week
@glad cradle I'm starting the rewriting tonight, if you have ideas related to design choices and stuff feel free to suggest cause I suck at it
( covering the gateway and rest handler today)
is there a way to archive and unarchive thread?
!d discord.Thread.edit
await edit(*, name=..., archived=..., locked=..., invitable=..., pinned=..., slowmode_delay=..., auto_archive_duration=..., applied_tags=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the thread.
Editing the thread requires [`Permissions.manage_threads`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_threads). The thread creator can also edit `name`, `archived` or `auto_archive_duration`. Note that if the thread is locked then only those with [`Permissions.manage_threads`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_threads) can unarchive a thread.
The thread must be unarchived to be edited.
tnx
if my bot will only stay in thread and i closed the thread then that thread is destroyed?
my bot not able to fetch the closed thread
is there any way to fetch those?
!d discord.TextChannel.archived_threads
async for ... in archived_threads(*, private=False, joined=False, limit=100, before=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator) that iterates over all archived threads in this text channel, in order of decreasing ID for joined threads, and decreasing [`Thread.archive_timestamp`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Thread.archive_timestamp) otherwise.
You must have [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history) to do this. If iterating over private threads then [`manage_threads`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_threads) is also required.
New in version 2.0.
alternatively you could probably track archived threads with on_thread_update, since that event fires just after an archived thread is removed from Guild.threads
https://github.com/Rapptz/discord.py/blob/v2.3.2/discord/state.py#L901-L903
discord/state.py lines 901 to 903
if thread.archived:
guild._remove_thread(thread)
self.dispatch('thread_update', old, thread)```
I am trying to check every thread of a channel if it's archived,locked or unarchived doesn't matter
Is there any way to do it?
sounds like archived_threads() + channel.threads would be sufficient
Problem I am getting is if I close the thread and then run the code it creates new one if I don't close the thread then it adds
You can zip() them
Closing means archived?
yes
Then discord.utils will work?
not sure what you mean by this, like your code is creating a new thread because you couldnt find the closed thread?
Yes
And I can edit close thread right?
on_thread_update would likely be more efficient to use than archived_threads() here, though it would be a bit less reliable...
Make a variable keep it simple
But yeah discord.utils will work
Instead of zip what if I add both list of obj?
on_thread_update sounds like event
er yeah
That works too it's similar way
names = ['Mukesh', 'Roni', 'Chari']
ages = [24, 50, 18]
for i, (name, age) in enumerate(zip(names, ages)):
print(i, name, age)
have you considered storing the thread IDs in a database so you don't have to fetch archived threads?
I think I should do this only else it's getting very complicated btw can I edit the archived thread?
I only need 1 variable bcz I will be comparing same thing with both of them don't know how it will be efficient tbh😅
i believe certain actions like adding members can't be taken until you've unarchived it
If i can unarchive thread with bot then it will be great
After that I will add the member : ) there
ye its the same method that leonardo showed you earlier
append it 😭
Bro appending take more time complexity as u mentioned to do zip before it
I am trying to keep my code faster : ( ,so even if more people uses bot it won't be a problem
Oh i see
!d discord.Thread
class discord.Thread```
Represents a Discord thread.
x == y Checks if two threads are equal.
x != y Checks if two threads are not equal.
hash(x) Returns the thread’s hash.
str(x) Returns the thread’s name.
New in version 2.0.
That's laziness
Lazy enough to not opening docs directly, redirecting from here
And you didn't find it
yes because im on my phone
|| how did you know ||
Excuse 😭
I know everything
Coke
😭🙏🏽
What else?
axo 
guinness

is it possible to transfer thread from one channel to another?
ray what now 😭
What's that? ||I don't drink||
wait are you from the 🇬🇧
I'm not colonizer 🗣️






