#discord-bots
1 messages · Page 1023 of 1
cuz your client's cache is empty
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'members'
cuz your client is not your client
how isn't my client 😂
is it in the main file now
no, should i use the main
but how if it didn't work?
GRRR
😂
how did you do it then
i just changed fetch to get
You still haven't changed what I've said...
but the cache is empty
^
I think it can
It sends the messages so the client works right?
hey guys why does it say interactin failed when it worked?
It keeps loading when I click it as well.
I'm using client.command, it shouldn't mark the command even?
it's a Command instance whatsoever
if you add it to the bot, it works
ey that's one year of python right there
Now simply do await ctx.respond(..., ephemeral=True) to make it an ephemeral message
Why did you have to change everything?
Keep your old code and just append , ephemeral=True as I've said above.
^
I forgot about ctx.guild, let's try it
bro you got the cup of tea already which you put on the table, you know where the tablet is, just take the tablet and put the cup on it before serving
Yeah instead of msg
class Suggestion(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
@discord.ui.button(emoji="✅", style=discord.ButtonStyle.green, custom_id = 'upvote')
async def check_callback(self, interaction, button):
message = interaction.message
embed = message.embeds[0]
embed_dict = embed.to_dict()
upvotes = embed_dict["fields"][0]["value"].replace(" Votes```","").replace("```","")
downvotes = embed_dict["fields"][1]["value"].replace(" Votes```","").replace("```","")
author_url = embed_dict["author"]["url"]
author_name = embed_dict["author"]["name"]
description = embed_dict["description"]
embed = discord.Embed(description=description)
embed.set_thumbnail(url=author_url)
embed.add_field(name=":thumbsup: **__Up Votes__**",value=f"```{int(upvotes)+1} Votes```",inline=True)
embed.add_field(name=":thumbsdown: **__Down Votes__**",value=f"```{downvotes} Votes```",inline=True)
embed.set_author(name=author_name.replace("' Suggestion","") + "'s Suggestion",url= author_url)
try:
embed.set_footer(text="Use -suggest to leave a suggestion!",icon_url=interaction.guild.icon.url)
except:
embed.set_footer(text="Use -suggest to leave a suggestion!")
@discord.ui.button(emoji="❎" , style=discord.ButtonStyle.red, custom_id = 'downvote')
async def x_callback(self, interaction, button):
message = interaction.message
embed = message.embeds[0]
embed_dict = embed.to_dict()
author_url = embed_dict["author"]["url"]
author_name = embed_dict["author"]["name"]
downvotes = embed_dict["fields"][1]["value"].replace(" Votes```","").replace("```","")
upvotes = embed_dict["fields"][0]["value"].replace(" Votes```","").replace("```","")
description = embed_dict["description"]
embed = discord.Embed(description=description)
embed.set_thumbnail(url=author_url)
embed.add_field(name=":thumbsup: **__Up Votes__**",value=f"```{upvotes} Votes```",inline=True)
embed.add_field(name=":thumbsdown: **__Down Votes__**",value=f"```{int(downvotes)+1} Votes```",inline=True)
embed.set_author(name=author_name,url= author_url)
try:
embed.set_footer(text="Use -suggest to leave a suggestion!",icon_url=interaction.guild.icon.url)
except:
embed.set_footer(text="Use -suggest to leave a suggestion!")
await interaction.message.edit(embed=embed)```
Hey there guys!
Why does only the x button work?
your code formatting messed it up
woah wtf
Well you never respond in the first case
You just do some embed formatting, just never do anything at the end
Unlike the second where you await interaction.message.edit(embed=embed)
class Suggestion(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
@discord.ui.button(emoji="✅", style=discord.ButtonStyle.green, custom_id = 'upvote')
async def check_callback(self, interaction, button):
message = interaction.message
embed = message.embeds[0]
embed_dict = embed.to_dict()
upvotes = embed_dict["fields"][0]["value"].replace(" Votes","").replace("","")
downvotes = embed_dict["fields"][1]["value"].replace(" Votes","").replace("","")
author_url = embed_dict["author"]["url"]
author_name = embed_dict["author"]["name"]
description = embed_dict["description"]
embed = discord.Embed(description=description)
embed.set_thumbnail(url=author_url)
embed.add_field(name=":thumbsup: **__Up Votes__**",value=f"{int(upvotes)+1} Votes",inline=True)
embed.add_field(name=":thumbsdown: **__Down Votes__**",value=f"{downvotes} Votes",inline=True)
embed.set_author(name=author_name.replace("' Suggestion","") + "'s Suggestion",url= author_url)
try:
embed.set_footer(text="Use -suggest to leave a suggestion!",icon_url=interaction.guild.icon.url)
except:
embed.set_footer(text="Use -suggest to leave a suggestion!")
@discord.ui.button(emoji=":negative_squared_cross_mark:" , style=discord.ButtonStyle.red, custom_id = 'downvote')
async def x_callback(self, interaction, button):
message = interaction.message
embed = message.embeds[0]
embed_dict = embed.to_dict()
author_url = embed_dict["author"]["url"]
author_name = embed_dict["author"]["name"]
downvotes = embed_dict["fields"][1]["value"].replace(" Votes","").replace("","")
upvotes = embed_dict["fields"][0]["value"].replace(" Votes","").replace("","")
description = embed_dict["description"]
embed = discord.Embed(description=description)
embed.set_thumbnail(url=author_url)
embed.add_field(name=":thumbsup: **__Up Votes__**",value=f"{upvotes} Votes",inline=True)
embed.add_field(name=":thumbsdown: **__Down Votes__**",value=f"{int(downvotes)+1} Votes",inline=True)
embed.set_author(name=author_name,url= author_url)
try:
embed.set_footer(text="Use -suggest to leave a suggestion!",icon_url=interaction.guild.icon.url)
except:
embed.set_footer(text="Use -suggest to leave a suggestion!")
await interaction.message.edit(embed=embed)```
!paste
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 floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
^
I only see like 200 variables
You mean interaction.message.respond?
Just compare the end of your both callbacks
And it worked without cogs @slate swan @heady sluice xD
One has await interaction.message.edit(embed=embed)
The other one has nothing
didn't copy the edit
thank a lot
I still hate it
Indentation is wrong
you've got limitations
hey, please don't use ableist words
I'll see what the issue is
what is that?
are you a new mod
nope, I've been around for a while
or just really rare to see here
more than 1 year
I'm newer
wat dat sir?
the r-word
Embed needs to have some indentation like the following
embed = discord.Embed(
title="...",
color=....
)
embed...
await...
bro it's obiwan kenobi
Oh sorry
who is that?
da heck
You did like
embed = discord.Embed(
title="...",
color=....
)
embed...
await...
star wars
...
Everything should be aligned at the same place as embed = ...
Nope, under msg
Otherwise it won't be executed if it's in the if statement
Which would be unfortunate
Yep, and put at the same level embed = ... and everything else
You have:
msg = "..."
embed = ...
...
You need:
msg = "..." # Which will then be deleted
embed = ...
...
there's nothing wrong with this line right? if isinstance(original_error, (commands.CommandNotFound, commands.CheckAnyFailure, disnake.HTTPException)):
Indentation
Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.
Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.
Example
def foo():
bar = 'baz' # indented one level
if bar == 'baz':
print('ham') # indented two levels
return bar # indented one level
The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.
Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines
More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation
Nope, not all
Everything needs to be at the third line
Can you send code, easier for me to show
Almost
The last two needs to be at the same level
Yep
Yep
How to get id of the person that clicked the button?
You have
embed = discord.Embed(
title="...",
color=....
)
embed...
await...
You need
embed = discord.Embed(
title="...",
color=....
)
embed...
await...
Nope, they're one below
Right now there will be only embed = discord.Embed(...) executed if it goes in the if statement
The ) might confuse you and make you think it's aligned correctly
interaction.author
Yep
oh ok thank
Actually might be interaction.user if you're on discord 2.0, not sure anymore how they did it
Oh ok
I think interaction.author is disnake
nice
Oh yeah that's normal
The .format(...) goes at the end of your string
So like
x = "Blah {...}".format(...)
Use f strings instead
Creating a Python string with your variables using the + operator can be difficult to write and read. F-strings (format-strings) make it easy to insert values into a string. If you put an f in front of the first quote, you can then put Python expressions between curly braces in the string.
>>> snake = "pythons"
>>> number = 21
>>> f"There are {number * 2} {snake} on the plane."
"There are 42 pythons on the plane."
Note that even when you include an expression that isn't a string, like number * 2, Python will convert it to a string for you.
Who can help me, buttons dont work anymor after a certain amount of time
first they do, but after a restart or after 10 minutes they stop
Did you restart the bot?
add_view(view, *, message_id=None)```
Registers a [`View`](https://discordpy.readthedocs.io/en/master/interactions/api.html#discord.ui.View "discord.ui.View") for persistent listening.
This method should be used for when a view is comprised of components
that last longer than the lifecycle of the program.
New in version 2.0.
Use this if you want to restore interactions.
how can i check if a user is already banned?
oh okay thanks
Just try to ban the user? Or doesn't that work?
i’ve got a ban command and when i try to ban the user i want it to reply with like; "This user is already banned". But i’m not sure how to
How can I hold the exception of forbidden?
Just check if the user is in the guild or not
I tried this but get_ban has no attribute```py
entry = await ctx.guild.get_ban(user)
if user in entry:
await ctx.reply("This user is already banned!")```
Yeah just try to ban the user and catch the exception.
how?
!d discord.Guild.ban
await ban(user, *, reason=None, delete_message_days=1)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Bans a user from the guild.
The user must meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.
You must have the [`ban_members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.ban_members "discord.Permissions.ban_members") permission to
do this.
!except
A key part of the Python philosophy is to ask for forgiveness, not permission. This means that it's okay to write code that may produce an error, as long as you specify how that error should be handled. Code written this way is readable and resilient.
try:
number = int(user_input)
except ValueError:
print("failed to convert user_input to a number. setting number to 0.")
number = 0
You should always specify the exception type if it is possible to do so, and your try block should be as short as possible. Attempting to handle broad categories of unexpected exceptions can silently hide serious problems.
try:
number = int(user_input)
item = some_list[number]
except:
print("An exception was raised, but we have no idea if it was a ValueError or an IndexError.")
For more information about exception handling, see the official Python docs, or watch Corey Schafer's video on exception handling.
!d round
round(number[, ndigits])```
Return *number* rounded to *ndigits* precision after the decimal point. If *ndigits* is omitted or is `None`, it returns the nearest integer to its input.
For the built-in types supporting [`round()`](https://docs.python.org/3/library/functions.html#round "round"), values are rounded to the closest multiple of 10 to the power minus *ndigits*; if two multiples are equally close, rounding is done toward the even choice (so, for example, both `round(0.5)` and `round(-0.5)` are `0`, and `round(1.5)` is `2`). Any integer value is valid for *ndigits* (positive, zero, or negative). The return value is an integer if *ndigits* is omitted or `None`. Otherwise, the return value has the same type as *number*.
For a general Python object `number`, `round` delegates to `number.__round__`.
Creating a Python string with your variables using the + operator can be difficult to write and read. F-strings (format-strings) make it easy to insert values into a string. If you put an f in front of the first quote, you can then put Python expressions between curly braces in the string.
>>> snake = "pythons"
>>> number = 21
>>> f"There are {number * 2} {snake} on the plane."
"There are 42 pythons on the plane."
Note that even when you include an expression that isn't a string, like number * 2, Python will convert it to a string for you.
try:
entry = await ctx.guild.get_ban(user)
except discord.NotFound:
await ctx.reply("This user is already banned")
return```
```discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Guild' object has no attribute 'get_ban'```
There is no get_ban, only fetch_ban
In my discord bot, when i type a command it doesn't send a message but when i try ctrl + c it doesn't break out of the script, but sometimes it completely works fine i don't know why
timeouts default value is None
What should i make it then
lol
why f strings and .format
value = f"X **Still on cooldown, please try again in {error.retry_after}s"
don't use f strings and .format on the same string
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.
since when??????
Since the beginning of time.
i swear it was always None

well what is error.retry_after
you are on a really old version of pip
read what it says ( yellow text)
You need to pass a cooldown duration to the decorator
also there's no need to add aliases in slash commands :)
@commands.cooldown(<some length of time>)
Assuming it is d.py the docs for it should be: https://discordpy.readthedocs.io/en/stable/ext/commands/api.html?highlight=cooldown#discord.ext.commands.cooldown
@bot.command()
@commands.has_any_role(692760082085183519, 940008547993927691, 863878825376743475, 902292952381001779, 863879069253894166, 902292952381001779, 863879304110276668, 940008547993927691)
async def пред(ctx, member: discord.Member = None, *, reason = 'Отсутствует'):
print(45)
cursor.execute("""CREATE TABLE IF NOT EXISTS warning(guild_id BIGINT, user_id BIGINT, warn INT, count INT, moderator_id BIGINT, reasons VARCHAR)""")
base.commit()
print(1)
warnings = cursor.execute("SELECT * FROM warning WHERE user_id = ? AND guild_id = ?", (member.id,ctx.guild.id)).fetchone()
print("работает")
if member is None:
await ctx.send("Выберите участника")
return
if warnings is None:
cursor.execute('INSERT INTO warning(guild_id, user_id, warn, count, moderator_id, reasons) VALUES(?, ?, ?, ?, ?, ?)', (ctx.guild.id,member.id,0,1,ctx.author.id,'Отсутствует'))
base.commit()
print(2222)
cursor.execute(f'UPDATE warning SET warn = warn + 1 WHERE user_id = ? AND guild_id = ?', (member.id, ctx.guild.id))
base.commit()
await ctx.send(f"**{ctx.author.name}** Выдал предупреждение #{warnings[2]} {member} (случай # ) {reason}")
else:
cursor.execute(f'UPDATE warning SET warn = warn + 1 WHERE user_id = ? AND guild_id = ?', (member.id, ctx.guild.id))
base.commit()
await ctx.send(f"**{ctx.author.name}** Выдал предупреждение #{warnings[2]} {member} (случай # ) {reason}")
How to make it so that if the reason was not specified, then Отсутствует was not written at the end, and if the reason was specified, then this was entered into the database and the reason was shown in the chat. Help me plz.
What is async?
Normally, python runs your code line by line, and holds up the entire thread while waiting for something. This can be problematic from I/O tasks, such as waiting for a web server to respond, waiting for a database server to respond, etc
Async was created to solve this issue: while you're waiting for something to respond, you can go and do something else, and come back later when the server has responded
Ah I see, that makes a lot of sense.
discord.py greatly benifits from this because due to the way that Discord's Gateway API works, you have to send a heartbeat to the gateway every 45ish seconds letting it know you're still on the other end waiting. This is a problem, because your code would look something like this:
while True:
send_heartbeat()
time.sleep(45)
Which means your code would hang on that part, and it would never do anything else. With asynchronous code however, it can heartbeat, go do something else for 45 seconds, then come back and heartbeat, rinse & repeat
Thank you so much, I understand it now.
Hello Robin, can you help?
Yup. It gets a lot more complex, so if this is interesting to you, I suggest you do some more research on it and try to understand how things such as the executor, event loop work, and differences between parallel computing and concurrency
I'd like to try, yes
kk, ill look into it. Ty
@bot.command()
@commands.has_any_role(692760082085183519, 940008547993927691, 863878825376743475, 902292952381001779, 863879069253894166, 902292952381001779, 863879304110276668, 940008547993927691)
async def пред(ctx, member: discord.Member = None, *, reason = 'Отсутствует'):
print(45)
cursor.execute("""CREATE TABLE IF NOT EXISTS warning(guild_id BIGINT, user_id BIGINT, warn INT, count INT, moderator_id BIGINT, reasons VARCHAR)""")
base.commit()
print(1)
warnings = cursor.execute("SELECT * FROM warning WHERE user_id = ? AND guild_id = ?", (member.id,ctx.guild.id)).fetchone()
print("работает")
if member is None:
await ctx.send("Выберите участника")
return
if warnings is None:
cursor.execute('INSERT INTO warning(guild_id, user_id, warn, count, moderator_id, reasons) VALUES(?, ?, ?, ?, ?, ?)', (ctx.guild.id,member.id,0,1,ctx.author.id,'Отсутствует'))
base.commit()
print(2222)
cursor.execute(f'UPDATE warning SET warn = warn + 1 WHERE user_id = ? AND guild_id = ?', (member.id, ctx.guild.id))
base.commit()
await ctx.send(f"**{ctx.author.name}** Выдал предупреждение #{warnings[2]} {member} (случай # ) {reason}")
else:
cursor.execute(f'UPDATE warning SET warn = warn + 1 WHERE user_id = ? AND guild_id = ?', (member.id, ctx.guild.id))
base.commit()
await ctx.send(f"**{ctx.author.name}** Выдал предупреждение #{warnings[2]} {member} (случай # ) {reason}")
How to make it so that if the reason was not specified, then Отсутствует was not written at the end, and if the reason was specified, then this was entered into the database and the reason was shown in the chat. Help me plz.
isn't that the same question @toxic thicket asked?
Doesn't look like it
I'm not sure what's going on here - why are 2 people asking for help on the same exact thing?
Right now
Indeed it is
Combined effort
who knows if it's ok to use from discord.ext import menu ?
a greater chance to get to the person who will help
@slate swan
I see you're Russian
@slate swan
don't throw Russian letters here at all, here they have a bad effect on people.
how to make the message "hello word" deleted after clicking on any of the reactions?
why is this saying BotBase.add_cog was never awaited ```py
bot.add_cog(Greetings(bot))
You need to await it
sends an error
Subclass commands.Bot and define an async function named setup_hook and do stuff there
It was a recent change
For my python bot, the timed mute commands i have tried all do not work, and I don't understand the methods used so I can't like do anything :/
Does anyone have a code I can look at or can help me at all?
basically i just need to understand how to get my code to understand time then min/sec/hour/day, then await that time period then do the action (for example giveaway or mute cmd)
smth like .gcreate 1min test prize or .gcreate 1 min prize here!
.mute @keen mural 1m bad or .mute @keen mural 1 min bad!!
send code
because most likely and no one will send open code for a mute command
i dont mind helping you since i do have a timed mute command
(keep in mind this is prob ugly since i have no idea what im doing)
im just tryna get different time variables that the person states in the command then make it sleep for that long basically
also i prob messed up that code a lot
idk what int means tbh 🥶
I could only make it work in seconds without any min sec hour etc things
int means integer, other known as a number.
its in the cmd ig
did you make the code?
like .gcreate 40min test
i just like mix code from different tutorials like i said im new :/
ah
which u can prob tell 😂
yea mix code will not work lmfao
its more like taking things i know and using it but i dont know what i am doing here
Giveaway bots aren't easy.
yeah ik i made one in seconds but idk how to get it to understand minutes hours etc
holdup i asked you to send mute thingy and you sent giveaway code?
its the same code
huh
Even so, you need a database, schedular and handle the result.
hello
well im making it sleep till the given time is over then it picks a random reaction
any idea on how to pinpoint latitude and longitude on a map using python ?
Who wants to learn the best programming language for the English - speaking population ??
That method means that if you restart the bot the giveaway won't work anymore.
yeah im a beginner
from async def command(time) you can use this to understand s, m, h, m directly from my code. ```py
blahblahblah = {"s":1, "m":60, "h":3600, "d":86400, "w":604800, "mo":18144000, "y":31536000}
blah = int(time[:-1]) * blahblahblah[time[-1]]
my first advanced cmd attempt
@heady sluice @cloud dawnI have found the perfect programming language for you
ok thx
but if i put (time) doesnt say the field is like unfulfilled when i do the cmd
Yeah I recommend a converter, but that is a bit complex.
you need to put ctx, member: discord.Member, time, reason
if you want to use that you can but dont have to
oh so just add on the others is what u mean
idk if i would want to use complex discord.py from a beginner level
time is an argument in that
Wizguy's method is a pretty solid one for beginners.
ig so
but from the basically i mixed other peoples code around into one thats really beginner
ok so
blahblahblah = {"s":1, "m":60, "h":3600, "d":86400, "w":604800, "mo":18144000, "y":31536000}
blah = int(time[:-1]) * blahblahblah[time[-1]]
what would the blahblah be
💀
just a var
so if i had
async def gcreate(ctx, args,*,prize=None):
why are you using args
idk man idk what im doing
async def gcreate(ctx, time,*,prize=None):
is that better
well im not gonna spoonfeed much more but you need a member in commands arg, and blah is used to convert essentially. One last tip is use await.asyncio.sleep(desctime) when dont want muted anymore but gl
huh
🤷
really weird...
it works only thing it doesn't make the channel
but somehow it mentions the channel
did you ever do create_text_channel(channel) ?
or whatever it is
i dont see like it actually being made
channel = await interaction.guild.create_text_channel(name=f"{interaction.user.name}-{interaction.user.discriminator}")
is it that?
yea but you have to create it
channel is just a variable im pretty sure just like that 💀
so if do await interaction.guild.create_text_channel(name=f"{interaction.user.name}-{interaction.user.discriminator}")
Or
await guild.create_text_channel(name=f"{interaction.user.name}-{interaction.user.discriminator}")
i think it was like that on v1
idk man but you have to 'activate' the var lol
ok
idk if that makes sense
it should be created in this
pretty sure to set prms you just find the channel name
pretty much everything will be the same in a cog
Did the timeout added for discordpy?
!d discord.Member.timeout
await timeout(until, /, *, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Applies a time out to a member until the specified date time or for the
given [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta "(in Python v3.10)").
You must have the [`moderate_members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.moderate_members "discord.Permissions.moderate_members") permission to
use this...
For some reason I didn't find it in docs but thanks
hey do you know why im getting this error?
oh
unhashable type: slice
My cogs is not being loaded
async def load(ctx, extension):
client.load_extension(f'cogs.{extension}')
@client.command()
async def unload(ctx, extension):
client.unload_extension(f'cogs.{extension}')
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
client.load_extension(f'cogs.{filename[:-3]}')```
How do i fix this?
This is the file i want it to load
How can I send more than one message with a command in 2.0
what version of dpy are you using?
you mean like using slash commands?
Yes
don't think you can, however I've not experimented enough with slash commands so I'm not so sure
dpy, not python version
await ctx.send("message 1")
await ctx.send("message 2")
You can't use CTX in slash commands
Ah you're using slash commands
You should be able to get the channel and use channel.send() then
How do i know that?
Ah yes I remember that now thank you
print out discord.version_info
or discord.__version__, either one works
pip show discord.py
1.7.3 is my py version
^
are you getting any errors when trying to load them?
raise MissingRequiredArgument(param) discord.ext.commands.errors.MissingRequiredArgument: extension is a required argument that is missing.
Yes
I mean i want it to where when the code runs all the extension gets loaded
dude in my server muted my bot because it stopped working, I keep unmuting it but it still thinks it's muted
how tf do I fix this
the error is pretty self-explanatory, and if you want all cogs to get loaded on startup, don't add the load_extension inside a command
could you elaborate on what you mean by your bot being muted? are messages not being sent? are you getting any errors? are you using slash commands?
Well what does that return?
So it would look like this?
And what is this?
I keep on getting channel is not assigned
!d discord.ClientUser.created_at
property created_at```
Returns the user’s creation time in UTC.
This is when the user’s Discord account was created.
returns datetime.datetime
Well they muted the bot (I'm assuming they used the default Discord red button mute) and now I just keep getting the
raise Forbidden(r, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
error every single time I type a command.
Also no I'm not using slash commands
class datetime.datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)```
The *year*, *month* and *day* arguments are required. *tzinfo* may be `None`, or an instance of a [`tzinfo`](https://docs.python.org/3/library/datetime.html#datetime.tzinfo "datetime.tzinfo") subclass. The remaining arguments must be integers in the following ranges...
time travel
!d datetime.datetime.timestamp
datetime.timestamp()```
Return POSIX timestamp corresponding to the [`datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "datetime.datetime") instance. The return value is a [`float`](https://docs.python.org/3/library/functions.html#float "float") similar to that returned by [`time.time()`](https://docs.python.org/3/library/time.html#time.time "time.time").
Naive [`datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "datetime.datetime") instances are assumed to represent local time and this method relies on the platform C `mktime()` function to perform the conversion. Since [`datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "datetime.datetime") supports wider range of values than `mktime()` on many platforms, this method may raise [`OverflowError`](https://docs.python.org/3/library/exceptions.html#OverflowError "OverflowError") for times far in the past or far in the future.
For aware [`datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "datetime.datetime") instances, the return value is computed as:
```py
(dt - datetime(1970, 1, 1, tzinfo=timezone.utc)).total_seconds()
``` New in version 3.3.
Changed in version 3.6: The [`timestamp()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.timestamp "datetime.datetime.timestamp") method uses the [`fold`](https://docs.python.org/3/library/datetime.html#datetime.datetime.fold "datetime.datetime.fold") attribute to disambiguate the times during a repeated interval.
did you know duck, you can send
try it and see
!e import time; print(time.time())
@iron sorrel :white_check_mark: Your eval job has completed with return code 0.
1651621174.6953475
So bot.user.created_at.???
can u suggest me a good discord api library that has slash cmds + a cheap hosting
Hosting is not part of an API library
And I'd suggest discord.py which has been the de-facto
Nope it wont get loaded
i know
It just says my bot is online
i mean suggest me a cheap hosting
disnake
for python
Ok my bot literally can't send any messages at all now even though I kicked it and readded it
if your bot's send_message perms got removed, then that'll probably be causing the issue
but what do you mean cheap hosting
alr
I just kicked and rekicked it and gave it the send message perm
thanks
k never mind it's fine now
do i need to do channel = member.channel
member does not have channel
So what do I need to do?
technically they can if they name it ctx, but its going to be misleading as slash commands have interactions and not Contexts
what do u want to do?
I have a giveaway command but it sends multiple messages in one command though
show ur code maybe someone will have an idea
Which of the messages are getting sent multiple times?
None of them are getting sent multiple times it's just you can't use the reply feature which is what you use when sending the message multiple times
after the first response you get a followup webhook you can use to send multiple messages
e.g. ```py
await interaction.response.send_message('hello world!')
any messages afterwards...
await interaction.followup.send('hello once more!', ephemeral=True)```
?
For the followups, it will be ephemeral if the response is ephemeral.
Followup will be same ephemeral as response
If interaction.author does not exist what do I use instead?
interaction.user
Ok thx
I keep on getting with this command that I did not mention a channel properly but I did and I do not understand why
in some libs it does btw
i.e disnake has aliases for it so it can be author and user
Yeah I know I fixed it and changed that issue now I'm running into a different one
which error?
Hear
Is it possible to make a discord bot that I text in dms to it then it sends an image to a channel?
Yes
Kk.
I tried but it won’t work
client.on("message", message => {
message.author.send("Please send a screenshot");
const collector = new Discord.MessageCollector(message.channel, m => m.author.id === message.author.id, {});
console.log(collector)
collector.on('collect', message => {
if (message.attachments.size > 0) {
message.channel.send("You successfully sent a screenshot")
console.log(`Collected ${message.content}`)
client.channels.get(`628607857662623745`).send(message.content);
} else if (message.attachments.size < 0) {
message.channel.send("you did not");
}
})
That is discord.js
This is a python server
Oh forgot this is python sorry
Oh thanks
Ask here
I keep on getting with this command that I did not mention a channel properly but I did and I do not understand why
!d discord.ext.commands.TextChannelConverter.convert
await convert(ctx, argument)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
The method to override to do conversion logic.
If an error is found while converting, it is recommended to
raise a [`CommandError`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CommandError "discord.ext.commands.CommandError") derived exception as it will
properly propagate to the error handlers.
You can do this await commands.TextChannelConverter().convert(ctx, “some arg here”)
I don't even know what lines causing it it doesn't even give me an error
Plus this is unsupported
How would I achive something like this
js 💀
when u r generating ur url select the identify scope
also guilds.join scope
@client.command(aliases=['8ball'])
async def _8ball(ctx, *, question):
responses = ["It is certain.",
"It is decidedly so.",
"Without a doubt.",
"Yes - definitely.",
"You may rely on it.",
"As I see it, yes.",
"Most likely.",
"Outlook good.",
"Yes.",
"Signs point to yes.",
"Reply hazy, try again.",
"Ask again later.",
"Better not tell you now.",
"Cannot predict now.",
"Concentrate and ask again.",
"Don't count on it.",
"My reply is no.",
"My sources say no.",
"Outlook not so good.",
"Very doubtful."]
await ctx.send(f'**Question:** {question}\n**Answer:** {random.choice(responses)}')
how would I make this send a different message if the user did not input a value for question
well ive tested it, you can flip flop between normal and ephemeral messages regardless of the response
ok thx
add a default value to question and then check if the value changed or not
I will try this, thank you.
ight
Does this work with interactions?
you could handle the MissingRequiredArgument exception using a command error handler: ```py
@bot.command()
async def my_command(ctx, arg):
await ctx.send(f'you passed {arg}!')
@my_command.error
async def my_command_error(ctx, error):
if isinstance(error, commands.MissingRequiredArgument):
await ctx.send(f'please pass the parameter: {error.param.name}')
# error.param.name would give the name of the missing argument, i.e. "arg"
else:
# some other error happened that we need to print
raise error``` if its going to be a common response for many commands then a global error handler would be more suitable which you can read more about in the docs: https://discordpy.readthedocs.io/en/stable/ext/commands/commands.html#error-handling
Is there any way to align my embed fields, although they're all inline?
I will try this too, thank you.
am missing 'coro'
async def on_mute_error
if you just tried running the bot you have to wait a while for it to update.
take there word for it. I'm not 100% sure
also i dont think the error handler is the problem, check traceback
doesnt work
commands.Bot already has its own tree, don't use both Client and Bot
what do i do now :/
no i meant @keen mural
how many on_message events do you have
i have 1, a snipe command that has caused problems in the past
you think thats a problem?
Can anyone else help me on this
or when you run the mute command
then its not a command related issue
is this the problem?
you're probably doing something like this right?
import discord
from discord.ext import commands
bot = commands.Bot(...)
app_commands = discord.app_commands.CommandTree(bot)
The traceback will tell you where the issue is
isinstance just checks if the first argument is an instance of the second
So perhaps have a look at that
^
oh
idk what most recent call last means
Seems like mute.error() expects an arg
youtube tutorial did me dirty 😭
lol
thanks so much now my bot will hopefully no longer get banned from too many errors
Your error handling is a little weird
You're returning in every condition for some reason, rather than using elif's
yeah, as I said, bot already has it's own tree, so you can just do bot.tree. That'll be your new tree var
!d discord.ext.commands.Bot.tree
property tree```
The command tree responsible for handling the application commands
in this bot.
New in version 2.0.
what do e lifts do even
ik its like a different if
what is bot.tree
An elif will run if all conditions above it are False and its condition is True
never used it
yeah
oh
not according to my cs teacher this year though 💀
So you should be doing ```py
if isinstance(...):
...
elif isinstance(...):
...
else:
...
thats helpful 😢
And don't return in every condition since it would be redundant if you use elif
it's kinda like discord.app_commands.CommandTree, but instead of using discord.Client, you use commands.Bot and you don't pass your bot var to the CommandTree
what kind of tutorial were you watching lol
it all makes sense now 
i see
idek i think i just copied some kids code on an unrelated video from a year or two ago
docs?
There aren't many discord.py resources that are any good, which is another reason why it's really not a beginner friendly lib
oh
i learnt it from just the docs
Yeah, but beginners don't know how to read docs 👀
uh
can relate 😔
i started learning d.py 3 weeks after i started learning python ;)
i basically learnt how to read docs from that
...
the guy in the vid was probably using cogs
yeah idk why self was in there
doesnt self make the bot like recognize itself or something
Chances are whatever you were watching defined the function in a class
In the context of a class, kinda
its the first required argument in cogs
I already installed and still the same error
it represents the instance
oh i didnt know that. thats interesting
yes i understand 
if i wanna add more examples of each one would i have to do the seconds to it too
i dont even know what im asking ill be right back and test
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 floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
Did you just spoonfeed
no 😨
🗿
💀
this was what i was talking about, adding some things but it dont work
im guessing cuz the code on the last line?
smth about the -1
well -1 gets the last character in the string so only s, m, h, w and d would work
could i use if and elif with different minus amounts each time? or
How can I display the bots avatar in the embed title?
through an emoji
idk 💀
no theres a built in way, I just forgot how
do you remember anything about it
!d discord.Embed.set_author
set_author(*, name, url=None, icon_url=None)```
Sets the author for the embed content.
This function returns the class instance to allow for fluent-style
chaining.
icon_url
that never works ong
@torn sail u think i could?
im not sure waht you mean
embed.set_author(name="title", icon_url=ctx.author.avatar_url)
?
you could use a regex
Ye it should work
the bots avatar or the authors?
the bots avatar.
then ctx.author.avatar_url should be bot.user.avatar_url
How can I add space between my embed footer?
wdym
basically a new line
\n
doesn't work
then the text wont be small like the footer.
dont provide invalid help lmao
try \n then an invisible character or smth idk
hey nobody else is here im just tryna help
Wdym small
nvm.
If i was doing
mutetime = int(time[:-1]) * validation[time[-1]]```
how would i add longer validations?
Can you not bold footer text?
!d discord.Embed.set_author
set_author(*, name, url=None, icon_url=None)```
Sets the author for the embed content.
This function returns the class instance to allow for fluent-style
chaining.
Maybe you can
sure you can
how so
** **
What
Yeah
it just sends the footer literally with the asterisks
oh
footer doesnt support any markdown
Really?
maybe you cant 💀
If i was doing
mutetime = int(time[:-1]) * validation[time[-1]]```
how would i add longer validations?
Sadge
like secs seconds etc
instead of just s
might as well copy and paste the entire command
Add them in the dict?
but mutetime = int(time[:-1]) * validation[time[-1]]
-1 thingy
so if it was longed
there would still be text instead of just numbers
and that messes it up to my understanding
is there any way I could add more space between my embed fields and footer?
just make another field with seconds
validation = {"s":1, "m":60, "h":3600, "d":86400, "w":604800, "seconds":1}
i tried that
Hi
but the second line of code only subtracts 1 letter
hey
What's the problem
or whatever
I want to know if theres any way I could add more space between my embed fields and footer
If i was doing
mutetime = int(time[:-1]) * validation[time[-1]]```
how would i add longer validations?
like secs seconds etc
instead of just s
/n
take a screenshot of you using it
wait nvm Im dumb
sparky do u know
not alias for the cmd
its a mute command and that determines the time
Ye alias for dict
i mean
so u can use s sec sond
how do i do that
embed.add_field(name="``help``", value="sends this help message\n\n", inline=True)
embed.set_footer(text="Contact y9su#8009 for further help or if you find any bugs")
this isnt adding the newlines
Try adding a text or emoji at last
After n
that error line seems unusual but its hard to tell without the full traceback, however it may be related to incorrectly using the @bot.tree.command decorator in your group rather than the generic @app_commands.command deco that Group looks for
Ye something like that
anyway sparky how do i add aliases
Wait
ah okay
I'll send code
for aliases?
um try a list maybe
async def parse_time(time: str, function=None, next_function=None, parsekey: str=None):
import asyncio
if parsekey in time:
time = time.replace(parsekey, "")
time = int(time)
await function
await asyncio.sleep(time)
await next_function()
try this
oh can you paste the full traceback then?
just do
do i just paste it in after the code
Don't sleep
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 floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
i have 3 iq can you elaborate
@bot.command()
async def mute(ctx, member, time):
async def check1():
role = discord.utils.get(ctx.guild.roles, name="muted")
await member.add_roles(role)
async def check2():
role = discord.utils.get(ctx.guild.roles, name="muted")
await member.remove_roles(role)
await parse_time(time, function=check1, next_function=check2, parsekey="s")
@keen mural
maybe i should try with decorators
ig
??
ohh you're missing the self parameter at the start of the function
i know
then?
he can use this instead
class ParsekeyNotInString(Exception):
pass
class StringParseError(Exception):
pass
async def parse_time(time: str, function=None, next_function=None, parsekey: str = None):
import asyncio
if parsekey in time:
time = time.replace(parsekey, "")
try:
time = int(time)
except ValueError:
raise StringParseError("Resulting string after removing the parsekey was not an integer/float")
await function
await asyncio.sleep(time)
await next_function()
else:
raise ParsekeyNotInString(f'The gives parsekey "{parsekey}" was not found in the given string "{time}"')
@slate swan

ParseKeyNotInString should be called KeyNotFound or StringKeyNotFound and it should be the subclass of the StringParseError exception, as it would make more sense since the super class would be the base/general exception and then the subclass would be the specific error
oh ye
smart
wait what string parse error
that isnt defined
is it from an import
the exception you made?
you think i can make this work?
oh yeah
🤦♂️
i just saved like 100 lines of code with this
could i make the code detect letters and subtract the amount of letters
what
async def start_loop():
await self.api.start_loop()
print("Post Count")
async def main():
asyncio.create_task(start_loop(bot))
asyncio.run(main())``` ```py
RuntimeError: asyncio.run() cannot be called from a running event loop``` I seem to keep on getting this error and I can't exactly seem to figure out how to fix it can someone help?
Looks like your asyncio.run() is indented - where's it nested in?
nested?
By this I mean it should be the very last line in your code, and it should also not have any spaces preceeding it
that is the file
asyncio.run has to be at the bottom, outside the class
iirc
Persisting the access token inside of a database is a very bad idea, unless you're using like JWTs or something else to encrypt it
Also because access tokens expire and there's not much you can do about it
That's why they provide you with an expires_in field so you can anticipate its expiry and generate a new one using your refresh token
Ya
Thats what I am doing
So put it up at the top of the class outside of everything?
It should also be in your main file, not in a cog
Don't think of asyncio.run() as a way to run any coro without awaiting it
Or a "get out of awaiting a coro free card"
How would I refresh the token with out making the user input anything
You'd need to somehow schedule a task in expires_in to refresh it
Moving it to the main file just says it's not defined
Or, whenever you need to use it, you can check if it's a valid access token, and if it's not, you can get a new one using the refresh token
what's not defined?
Yeah, you need a main function
try:
r = exchange_code("8xaVc3klYCFEZfdjdYyGaXsp4MmqNX")
code = r["access_token"]
except Exception as e:
code = refresh_token(r["refresh_token"])
like this??
Sure, if you get a non-200 status code that means it's an invalid code
Thought I had that I'm a bit confused now
The only problem is how would I access r because it is defined in try
Your main() function can look like this:
async def main():
try:
await bot.start()
finally:
# cleanup tasks here
asyncio.run(main())
Good point
You'd need to figure out how to get that
mabye I could save and when I need it
Do I just need to move everything in that one file over to the main file?
or encryption
You're using asyncio.run() to start a loop which is NOT its intended purpose
It's meant to kickstart your ENTIRE bot file, not just a task
So from my understanding I need to move everything from my API file over to my main start file and use create task inside of my main function which starts my bot
Not necessarily
You can start your tasks inside setup()
And remove your main() and asyncio.run(main())
I'm just all get out confused right now
async def start_loop():
await self.api.start_loop()
print("Post Count")
start_loop()``` this?
^^^^^^^^^^^^
async def setup(bot):
cog = DiscordListsPosts(bot)
await bot.add_cog(cog)
await cog.start_loop()
Or use on_ready
yes, there should be
I wouldn't do anything in on_ready except printing
uh why
It's unpredictable, and can get called multiple times. It's also not guaranteed to be the first event called
That's why it's generally discouraged to do anything in on_ready
Okay I'll remember it
async def status(self, ctx, member:discord.Member):
print(member.status)
if member.status == online:
await ctx.send(f'{member} is online!')
else:
await ctx.send('You are not online.')
I am running into an issue where I want member.status to send a message only if it returns online, but I am not sure what to put after the member.status ==
I tried putting just online but it didnt work.
*edit: I was being dumb and didn't use the class. I resolved my issue by using discord.Status.online instead of just online. *
!d discord.Member.status
property status```
The member’s overall status. If the value is unknown, then it will be a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") instead.
So put that underneath start loop? Or main file?
You would have to read the entire conversation to see what I'm talking about
U want a loop right
yes
Show code where r now
async def start_loop():
await self.api.start_loop()
print("Post Count")
async def setup(bot):
cog = DiscordListsPosts(bot)
await bot.add_cog(cog)
await cog.start_loop()```
Do u have a setup hook?
I mean
REMOVE start loop from start loop function
And put it in the setup
um
And
use tasks.loop
whare
In your setup() in your cog file
what is guild splash?
async def start_loop():
await self.api.setup()
print("Post Count")
async def setup(bot):
cog = DiscordListsPosts(bot)
await bot.add_cog(cog)
await cog.start_loop()
await bot.add_cog(DiscordListsPost(bot))```
Do I have it right now?
Anybody else know if I got this correct
No
i think my class attributes are getting too long 
No async setup
Just def setup(bot):
bot.add_cog()
Etc
@bot.slash_command(name = "serverinfo", description = "information about a server")
async def serverinfo(ctx: commands.Context):
role_count = len(ctx.guild.roles)
owner = await ctx.guild.fetch_member(ctx.guild.owner_id)
embed = disnake.Embed(title=f"{ctx.guild.name}'s Info", timestamp=ctx.message.created_at, colour=0x00FF00)
embed.add_field(name="Name", value=f"{ctx.guild.name}", inline=False)
embed.add_field(name="Member Count", value=ctx.guild.member_count, inline=False)
embed.add_field(name="Verification Level", value=str(ctx.guild.verification_level), inline=False)
embed.add_field(name="Owner", value=f"{owner.name}#{owner.discriminator}", inline=False)
embed.add_field(name="Number Of Roles", value=str(role_count), inline=False)
await ctx.send(embed=embed)
``` im getting this error, can someone please help
he might be on the newest version
I'm confused because I thought that's what they wanted me to do is what I have in there
Since when is setup() async
slash commands have interaction, not context
newest version!
so what do i change ctx: to?
Imma look into that
So what do I need to do?
not sure
I think discord.MessageInteraction
alr
!d discord.MessageInteraction
class discord.MessageInteraction```
Represents the interaction that a [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") is a response to.
New in version 2.0.
x == y Checks if two message interactions are equal.
x != y Checks if two message interactions are not equal.
hash(x) Returns the message interaction’s hash.
im using disnake, is it the same method?
I hope so
So what do I need to do?
last line bad
how do i fix it?
Traceback (most recent call last):
File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 924, in _load_from_module_spec
await setup(self)
File "C:\Users\culan\OneDrive\Desktop\3.0.0 echo\cogs\api.py", line 36, in setup
cog = DiscordListsPosts(bot)
NameError: name 'DiscordListsPosts' is not defined
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\culan\OneDrive\Desktop\3.0.0 echo\echo.py", line 55, in <module>
asyncio.run(main())
File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\asyncio\runners.py", line 44, in run
return loop.run_until_complete(main)
File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 642, in run_until_complete
return future.result()
File "C:\Users\culan\OneDrive\Desktop\3.0.0 echo\echo.py", line 48, in main
await bot.load_extension('cogs.api')
File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 990, in load_extension
await self._load_from_module_spec(spec, name)
File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 929, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.api' raised an error: NameError: name 'DiscordListsPosts' is not defined```
what's your cog called
https://paste.pythondiscord.com/kenivaworo DiscordListsPost
Traceback (most recent call last):
File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 924, in _load_from_module_spec
await setup(self)
File "C:\Users\culan\OneDrive\Desktop\3.0.0 echo\cogs\api.py", line 33, in setup
await cog.start_loop()
TypeError: start_loop() takes 0 positional arguments but 1 was given
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\culan\OneDrive\Desktop\3.0.0 echo\echo.py", line 55, in <module>
asyncio.run(main())
File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\asyncio\runners.py", line 44, in run
return loop.run_until_complete(main)
File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 642, in run_until_complete
return future.result()
File "C:\Users\culan\OneDrive\Desktop\3.0.0 echo\echo.py", line 48, in main
await bot.load_extension('cogs.api')
File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 990, in load_extension
await self._load_from_module_spec(spec, name)
File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 929, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.api' raised an error: TypeError: start_loop() takes 0 positional arguments but 1 was given```
hi DeniaL
so await self.bot.add_cog(cog)
hi
ok
async def start_loop(self):
oooo ok
Traceback (most recent call last):
File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 924, in _load_from_module_spec
await setup(self)
File "C:\Users\culan\OneDrive\Desktop\3.0.0 echo\cogs\api.py", line 33, in setup
await cog.start_loop()
File "C:\Users\culan\OneDrive\Desktop\3.0.0 echo\cogs\api.py", line 26, in start_loop
await self.api.setup()
AttributeError: 'Client' object has no attribute 'setup'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\culan\OneDrive\Desktop\3.0.0 echo\echo.py", line 55, in <module>
asyncio.run(main())
File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\asyncio\runners.py", line 44, in run
return loop.run_until_complete(main)
File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 642, in run_until_complete
return future.result()
File "C:\Users\culan\OneDrive\Desktop\3.0.0 echo\echo.py", line 48, in main
await bot.load_extension('cogs.api')
File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 990, in load_extension
await self._load_from_module_spec(spec, name)
File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 929, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.api' raised an error: AttributeError: 'Client' object has no attribute 'setup'```
I did what sparky told me to do earlier on this one which is why I'm a bit confused when I read this one
I don't know what y'all mean by self.api
Has to do with a library
and what do you want to setup on it
!discord.ext.commands.Cog.api
doesn't even exist?
(it doesn't)
(ok)
await self.api.setup()
self.api doesn't exist, what are you trying to do?
tf is discordlists
Api library
na no way
Don't know what that is
That's what I've been trying to refer to
sh I just got to school bye
well it doesn't have a method called setup then...
I was just doing what I was told to do
so this then ```py
async def start_loop(self):
await self.api.start_loop()
print("Post Count")
async def setup(bot):
cog = DiscordListsPost(bot)
await bot.add_cog(cog)
await cog.start_loop()```
i guess, run it and see
Traceback (most recent call last):
File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 924, in _load_from_module_spec
await setup(self)
File "C:\Users\culan\OneDrive\Desktop\3.0.0 echo\cogs\api.py", line 33, in setup
await cog.start_loop()
File "C:\Users\culan\OneDrive\Desktop\3.0.0 echo\cogs\api.py", line 26, in start_loop
await self.api.start_loop()
File
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\culan\OneDrive\Desktop\3.0.0 echo\echo.py", line 55, in <module>
asyncio.run(main())
File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\asyncio\runners.py", line 44, in run
return loop.run_until_complete(main)
File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 642, in run_until_complete
return future.result()
File "C:\Users\culan\OneDrive\Desktop\3.0.0 echo\echo.py", line 48, in main
await bot.load_extension('cogs.api')
File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 990, in load_extension
await self._load_from_module_spec(spec, name)
File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 929, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.api' raised an error: AttributeError: loop attribute cannot be accessed in non-async contexts. Consider using either an asynchronous main function and passing it to asyncio.run or using asynchronous initialisation hooks such as Client.setup_hook```
Can someone help me I’m having a hard time figuring out on
“How to get notified when someone updates their GitHub, through webhook on my of my channels”
Just can’t find anywhere
what i have right now https://paste.pythondiscord.com/acufamanef
def start_loop(self):
"""
Start a loop that automatically updates the server/guild count for the bot
"""
self.bot.loop.create_task(self.__loop(self.interval))
start_loop is a sync function, so i dont think u need await for it
so py async def start_loop(self): self.api.start_loop() self.bot.loop.create_task(self.__loop(self.interval)) print("Post Count")
no no no, thats the source code, dont copy that lmao
oop
self.bot.loop.create_task(self.__loop(self.interval))
remove that
ya
AttributeError: loop attribute cannot be accessed in non-async contexts. Consider using either an asynchronous main function and passing it to asyncio.run or using asynchronous initialisation hooks such as Client.setup_hook``` ```py
async def start_loop(self):
self.api.start_loop()
print("Post Count")
async def setup(bot):
cog = DiscordListsPost(bot)
await bot.add_cog(cog)
await cog.start_loop()```
def start_loop(self):
self.api.start_loop()
print("Post Count")
async def setup(bot):
cog = DiscordListsPost(bot)
await bot.add_cog(cog)
cog.start_loop()
try this
Extension 'cogs.api' raised an error: AttributeError: loop attribute cannot be accessed in non-async contexts. Consider using either an asynchronous main function and passing it to asyncio.run or using asynchronous initialisation hooks such as Client.setup_hook```
Any other ideas?
nope.
You got any ideas?
👀
What is your name for the coin toss game?
coin?
there are 2 answers true and false\
wht should i import to use buttons ?
discord.ui.button(*, label=None, custom_id=None, disabled=False, style=<ButtonStyle.secondary: 2>, emoji=None, row=None)```
A decorator that attaches a button to a component.
The function being decorated should have three parameters, `self` representing the [`discord.ui.View`](https://discordpy.readthedocs.io/en/master/interactions/api.html#discord.ui.View "discord.ui.View"), the [`discord.Interaction`](https://discordpy.readthedocs.io/en/master/interactions/api.html#discord.Interaction "discord.Interaction") you receive and the [`discord.ui.Button`](https://discordpy.readthedocs.io/en/master/interactions/api.html#discord.ui.Button "discord.ui.Button") being pressed.
Note
Buttons with a URL cannot be created with this function. Consider creating a [`Button`](https://discordpy.readthedocs.io/en/master/interactions/api.html#discord.ui.Button "discord.ui.Button") manually instead. This is because buttons with a URL do not have a callback associated with them since Discord does not do any processing with it.
um how can i get embed from msg object?
!d discord.Message.embeds
A list of embeds the message has.
thanks :D
Np
guys i have a cog folder so everything was working fine until i added a leveling system its crashing and giving errors for quite a bit of my code
anyone has some time to help me fix after
how is it possible for a bot to have permission to read and send messages on a server but get the forbidden error on it when trying to send message? what permission do i need to check
right now i use message.channel.permissions_for(message.guild.me).read_messages and message.channel.permissions_for(message.guild.me).send_messages but somehow its not enough
maybe you're trying to send an embed.
send the full traceback
Ignoring exception in on_message
Traceback (most recent call last):
File "bot_file.py", line 51, in on_message
await message.channel.send(response)
File "python3.7/site-packages/discord/abc.py", line 1067, in send
message_reference=reference)
File "python3.7/site-packages/discord/http.py", line 248, in request
raise Forbidden(r, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
how can i get title
message.embeds[0].title
^
!d discord.Embed.title
The title of the embed.
This can be set during initialisation.
Can only be up to 256 characters.
i tried printing items but it didnt print
message.embeds returns a list of embeds, and indexing to 0 gets the first embed
for example:
ohkay now i understand
!e ```py
x = [1, 2, 3, 4]
print(x[0])
@spring flax :white_check_mark: Your eval job has completed with return code 0.
1
i thought it only return one embed
nvmd
and the code?
async def on_message(message):
if (message.channel.permissions_for(message.guild.me).read_messages and message.channel.permissions_for(message.guild.me).send_messages):
response = "sample text"
await message.channel.send(response)
i tried using a test bot, to check the behavior, and i wasn't able to replicate this forbidden error
i could only replicate the forbidden error by removing the permission check in my code
you can probably just use ```py
async def on_message(message):
try:
response = "sample text"
await message.channel.send(response)
except discord.Forbidden:
return
i could but i don't want to process the message
not sure tbh
ideally i could check for some permission instead
is the traceback you posted the full one?
Traceback (most recent call last):
File "/home/runner/mv/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/home/runner/mv/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/home/runner/mv/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NameError: name 'Button' is not defined
yes
you used Button in your code but didn't define it
it's identical to what i would get if i didn't do the permission check for send message, then added the bot to some server channel where it could read the messages but not allowed to send messages
@bot.command()
async def google(ctx):
url = f"https://www.google.com"
await ctx.send("Test",components=[Button(style=ButtonStyle.URL,
label="Click Here", url=url)])
almost identical
+= 1
gg i forgot this
sould i install any module for button ?
Traceback (most recent call last):
File "C:\Users\thoma\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\thoma\OneDrive\Desktop\discord server bot\cogs\ticket.py", line 17, in createticket
channel_id = int(format_args[0].strip('<').strip('>').replace('#', ''))
IndexError: list index out of range```
def __init__(self, client):
self.client = client
@commands.command()
@commands.has_permissions(administrator=True)
async def createticket(self, ctx, *args):
format_args = list(args)
guild_id = ctx.message.guild.id
channel_id = int(format_args[0].strip('<').strip('>').replace('#', ''))
title = ' '.join(format_args[1:])```
dont, dpy 2.0 has built-in support for those
@bot.command()
async def google(ctx):
url = f"https://www.google.com"
await ctx.send("Test",components=[Button(style=ButtonStyle.URL,
label="Click Here", url=url)])
@bot.command()
async def google(ctx):
url = f"https://www.google.com"
await ctx.send("Test",components=[Button(style=ButtonStyle.URL,
label="Click Here", url=url)])
i don't think you can give *args as argument in a command, you can add have *, variable and that variable will take the whole string you pass in it
if isinstance(original_error, (commands.CommandNotFound, commands.CheckAnyFailure, disnake.HTTPException)):
return
Even with this in my error handler, this error gets raised in terminal
disnake.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In data.choices.5.name: This field is required
well....see the documentation on how to create buttons...
uhm discord formatting
ok
!d discord.ui.Button
class discord.ui.Button(*, style=<ButtonStyle.secondary: 2>, label=None, disabled=False, custom_id=None, url=None, emoji=None, row=None)```
Represents a UI button.
New in version 2.0.
how to give role
@commands
async def test(ctx, *, message):
await ctx.send(message)
!d discord.Member.add_roles
await add_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s.
You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to
use this, and the added [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s must appear lower in the list
of roles than the highest role of the member.
thanks
but how do i give someone role
for example 757508305256972338
?
@Command
async def gib_role(ctx: commands.Context):
role = ctx.guild.get_role(role_id)
await ctx.author.add_roles(role)
thanks

...
=.=
i have a down down menu and a list how can i add items in the down menu with list
dropdown I assume
u dont help
how to edit message?
click on 3 dot
wow
no, at bot
pls help
i have a down down menu and a list how can i add items in the down menu with list
I'm trying to do something a little weird. I have a dictionary who's values are lists. Those lists are greater than 25 items long so I created a function that creates a new list and splits them up into 25 item long lists and adds them to a new dictionary. I want the user to use .menu, select a key from that new dictionary, and then send out buttons for every item in that key's value (which is a list). I think I have to use defers to accomplish this. Can anyone point to an example of something similar?
i give up byebye
A gist explaining the right way to make drop down menus/select menus/selects in discord.py v2(version 2.0.0a) - selects_or_dropdowns.md
how to edit message????
i have a down down menu and a list how can i add items in the down menu with list
u mean bot or what
yea
help me pls i have a down down menu and a list how can i add items in the down menu with list
@loud junco
anyone?
speak in human language?
what is down down menu bruh
😦
down down drop down
byebye
how to edit message? at bot
bye
class Select(discord.ui.Select):
def __init__(self):
options = []
for x in lst:
options.append(discord.SelectOption(label = x, description=x)
super().__init__(placeholder="Select an option",max_values=1,min_values=1,options=options)
thanks
MercyMoon is best
several people is bad he didnt help me
help pls,how to edit message? at bot```
Some good documentation in here too. https://gist.github.com/lykn/a2b68cb790d6dad8ecff75b2aa450f23
A gist explaining the right way to make drop down menus/select menus/selects in discord.py v2(version 2.0.0a) - selects_or_dropdowns.md
ok
thx
@slate swan hope this helps u
no
i googled it
msg = await ctx.send("hi")
await msg.edit("hello")
channel = bot.get_channel(id_of_the_channel)
message = await channel.fetch_message(id_of_the_message)
await message.edit(content="the new content of the message")
``` @slate swan
channel = await bot.get_channel(id_of_the_channel).fetch_message(id_of_the_message).edit("hi")

