#discord-bots
1 messages ยท Page 183 of 1
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.
There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.
Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.
but the bot part is just client for u
Gonna test it
Didn't understand
worked ty
Can someone help?
how can I check who has reacted to a message in cog.listener payload
What event are you listening to?
on_raw_reaction_add
so basically my problem is that my bot sends a message and auto adds a โ and โ reaction, then this listener needs to wait until someone reacts with either yes or no
but it already detects the tick that's been added by the bot itself
Does the reaction listener need to be persistent? Or should it only work for a some time?
I want it to timeout after like 15 mins
if str(payload.emoji) == "\U00002705":```
that's the check in the cog listener
!d discord.ext.commands.Bot.wait_for consider using this instead
wait_for(event, /, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.11)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.11)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.11)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/latest/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
There's an example in the docs on how you'd implement a reaction if you need that
@fading marlin
I don't use client so what would I use instead of here I forgot
client.wait_for
is it self.wait_for ?
Wdym?
reaction, user = await client.wait_for('reaction_add', timeout=60.0, check=check)```
Looks good to me?
Then replace client for bot ๐คท
when you react with yes
@commands.Cog.listener()
async def on_raw_reaction_add(self, payload):
if payload.channel_id == 1065720365021679718:
channel = self.bot.get_guild(payload.guild_id).get_channel(payload.channel_id)
message = await channel.fetch_message(payload.message_id)
for user in message.mentions:
i = user
def check(reaction, user):
return user == i and str(reaction.emoji) == '\U00002705'
try:
reaction, user = await self.bot.wait_for('reaction_add', timeout=60.0, check=check)
except asyncio.TimeoutError:
await channel.send('๐')
else:
await channel.send('๐')
for user in message.mentions:```
Ok nevermind, what I send isn't gonna be useful for your case. To answer your question, you can check if payload.user_id is equal to the ID of the bot
!d discord.RawReactionActionEvent this is the type of payload
class discord.RawReactionActionEvent```
Represents the payload for a [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add") or [`on_raw_reaction_remove()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_raw_reaction_remove "discord.on_raw_reaction_remove") event.
check if
payload.user_idis equal to the ID of the bot
user_id is an integer, and you're comparing it to a string
omg I'm so dumb
How is it i print a value to a string? Like it takes a value and sendes it in a discord server
how do you know where you want to send it?
With a discord webhook
class discord.SyncWebhook```
Represents a synchronous Discord webhook.
For an asynchronous counterpart, see [`Webhook`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Webhook "discord.Webhook").
x == y Checks if two webhooks are equal.
x != y Checks if two webhooks are not equal.
hash(x) Returns the webhooksโs hash.
Changed in version 1.4: Webhooks are now comparable and hashable.
can probably just use this then
Ok thx
use the send method on that and just pass the value you want printing
to construct one use the from_url classmethod
!d discord.Webhook
class discord.Webhook```
Represents an asynchronous Discord webhook.
Webhooks are a form to send messages to channels in Discord without a bot user or authentication.
There are two main ways to use Webhooks. The first is through the ones received by the library such as [`Guild.webhooks()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.webhooks "discord.Guild.webhooks"), [`TextChannel.webhooks()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel.webhooks "discord.TextChannel.webhooks"), [`VoiceChannel.webhooks()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceChannel.webhooks "discord.VoiceChannel.webhooks") and [`ForumChannel.webhooks()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.ForumChannel.webhooks "discord.ForumChannel.webhooks"). The ones received by the library will automatically be bound using the libraryโs internal HTTP session.
The second form involves creating a webhook object manually using the [`from_url()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Webhook.from_url "discord.Webhook.from_url") or [`partial()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Webhook.partial "discord.Webhook.partial") classmethods.
For example, creating a webhook from a URL and using [aiohttp](https://docs.aiohttp.org/en/stable/index.html "(in aiohttp v3.8)"):
Don't use SyncWebhook please ๐
reaction = next((r for r in message.reactions if r.emoji == '๐'), None)
if reaction:
users = list(await reaction.users())
if len(users) > 0:
winner = random.choice([user for user in users if not user.bot])
embed.add_field(name='Winner', value=winner.mention)
await message.edit(embed=embed)
else:
await ctx.send("No one reacted to the giveaway.")
else:
await ctx.send("No one reacted to the giveaway.")
Heyo for some reason its not detecting that I reacted to the message, any idea?
how get unicode of an emoji
back slash it in chat
reaction.users() is an async iterator.
users = [user async for user in reaction.users()]
reaction = message.reactions()
users = [user async for user in reaction.users()]
winner = random.choice(users)
embed.add_field(name='Winner', value=winner.mention)
await message.edit(embed=embed)
yeah then i updated it to this and still nothing
can you show full code?
async def create_giveaway(ctx, title: str, duration: str, *, description: str):
duration_dict = {"s": 1, "m": 60, "h": 3600, "d": 86400}
match = re.match(r"(\d+)([a-zA-Z]+)", duration)
if match:
duration_num = int(match.group(1))
duration_unit = match.group(2).lower()
duration_seconds = duration_num * duration_dict.get(duration_unit, 1)
else:
duration_seconds = int(duration)
end_time = datetime.datetime.now() + datetime.timedelta(seconds=duration_seconds)
if duration_seconds < 60:
duration_string = f'{duration_seconds} seconds'
elif duration_seconds < 3600:
duration_string = f'{duration_seconds // 60} minutes'
elif duration_seconds < 86400:
duration_string = f'{duration_seconds // 3600} hours'
else:
duration_string = f'{duration_seconds // 86400} days'
embed = discord.Embed(title=title, description=description)
embed.add_field(name='Duration', value=duration_string)
embed.add_field(name='Ends at', value=end_time.strftime("%Y-%m-%d %H:%M:%S"))
message = await ctx.send(embed=embed)
await message.add_reaction('๐')
while True:
now = datetime.datetime.now()
remaining_time = end_time - now
if remaining_time.total_seconds() <= 0:
break
if remaining_time.total_seconds() < 60:
duration_string = f'{remaining_time.total_seconds():.0f} seconds'
elif remaining_time.total_seconds() < 3600:
duration_string = f'{remaining_time.total_seconds() // 60:.0f} minutes'
elif remaining_time.total_seconds() < 86400:
duration_string = f'{remaining_time.total_seconds() // 3600:.0f} hours'
else:
duration_string = f'{remaining_time.total_seconds() // 86400:.0f} days'
embed.set_field_at(index=0, name="Duration", value=duration_string)
await message.edit(embed=embed)
await asyncio.sleep(300)
reaction = message.reactions()
users = [user async for user in reaction.users()]
winner = random.choice(users)
embed.add_field(name='Winner', value=winner.mention)
await message.edit(embed=embed)
hmmmm! wait think hard lol.
thx
slash or ctx?
ctx
File "sk.py", line 121
await client.get_channel(x).send(embed=embed)
^
SyntaxError: invalid syntax
=====
Update, solution found fix done.
add some print statements inside ur while True
print("here??????")
reaction = message.reactions()
print("only here")
users = [user async for user in reaction.users()]
print("made it here")
winner = random.choice(users)
print("at least here")
embed.add_field(name='Winner', value=winner.mention)
await message.edit(embed=embed)
I did this really scuffed print section and it printed print("here??????")
Error: Command raised an exception: TypeError: 'list' object is not callable
This is the error message btw
embed.add_field(name=...,value=",".join(guild.name for guild in client.guilds))
show full traceback
yeah i know my forget missing fix.
Jay and Spooky solution:
oh, i have
@client.event
async def on_command_error(ctx, error):
await ctx.send(f'Error: {error}')
So it doesnt send the traceback into console
okay itll be done in about 5 minutes
wait forgot to ask what lib is this?
okay
yeye
hecc, now it gets to here
users = [user async for user in reaction.users]
but gives me the error
Error: Command raised an exception: AttributeError: 'list' object has no attribute 'users'
@slate swan sorry question: await client.get_channel(x).send(embed=embed) there edit message channel?
example: client.get_channel.edit right?
How can I get an invitation by which a new user has joined? any ways?
if str(payload.emoji) != '\u274E' and payload.user_id != 1002921149795143680:```
This seems to not be working, does anyone know why?
Print to see what the thing you're trying to compare first
use on member join event then check list of invites and which num increased on usage
wdym?
how can I see what reactions are in a message
like I wanna basically do py if 'unicode' in message.reactions: but message.reactions is in a diff format
its a list
so how can I do it
for a discord bot view, can there only be a set list of buttons? can the buttons change dynamically?
i mean technically yeah. you can edit the view with a new view
and for views you can use a decorator also
how would a decorator help?
I don't even think I have an app.yaml to be honest with you ๐ I didn't see that in docs, let me look again
check at the bottom of the github repo
i guess i didnt really understand your "set list of buttons" statement
I see the link in the docs but it doesn't link to a file in the repo, what is the path and is in it in main?
I see publish.yml in github workflows but that's the only yml I've seen thus far
readthedocs.yml too
making a text adventure game
obviously, sometimes the options change depending on where the user is
is there a way to have these option changes reflect in the buttons on the view?
but no app.yml or as they reference application.yaml
yeah
create view sets
you can change between them depending on the options selected
its at the bottom. herer
and that link takes u a page that shows u an example of the app.yml
This example tells you how many times you've pressed a button
https://github.com/Rapptz/discord.py/blob/master/examples/views/counter.py
that's...not really what i'm looking for?
and it means you don't have installed
yes resend the view with the editted buttons
you would do that in the callback
is there an example? last time i checked each button needed its own function, etc.
i kinda need a way to create buttons on the fly
You can subclass button if you'd like
The tictactoe example in the repo shows you how to do that
how deep into dpy are you? i have a suggestion that allows you to create buttons on the fly without views but its a different lib
It's a lot more dynamic and closer to what you want
(Since tictactoe is also a game and the buttons reflect the game state)
not very deep lol
at least in that game, the # of buttons are constant
You're probably just looking to subclass Button
You can change the # of buttons no problem
You can change anything in the view really
oh alr then
that tictactoe is a good example for what you are looking for within that lib
here is an example of creating buttons without views if a different lib
https://github.com/DisnakeDev/disnake/blob/master/examples/interactions/low_level_components.py
doest help anyway i fixed and got a new error
idk how to replace the options like python discord_slash.utils.manage_commands.create_option
can u help
@sick birch @slate swan ^
I don't use the discord_slash library sorry
how do you implement the .create_option feature with that
Oh it's really easy in discord.py
@tree.command()
async def my_slash_command(interaction: discord.Interaction, option1, option2):
...
?
option1 and option2 are your options
oh nice ill try it out thanks
Probably won't work without a little initial setup
I'd recommend reading up on the docs and examples for that
My intention was just to give an example
Alright, I'll check it out. Thanks for the help.
every time i try to run a bot from discord.py i get this error can sum1 plz help
you either have a file named discord.py, a folder named discord or some fork/third party application using the discord namespace
i dont ๐ง
No
thats what I've been using and its working
all is a classmethod
I have had 0 issues
reinstall discord.py then
it will work, but the () are not required there in Intents
ah gotcha
hm
i did that and it works
itsn not letting me type "thx" in this channel
thx*
great
async def test():
try:
channel = client.get_channel(1044458591664488529)
await channel.send(" Bumping time")
except Exception:
#PASS OUT Without doing anything
pass```
No solution automatic message channel? | there code by stackoverflow
what is the issue?
Yeah there time reload automatic message send channel
but no received channel message
you need to wait until bot is ready
Yes my already bot online and waiting 1 minutes no reply message channel.
are u starting the task?
yea ur task starts as soon as u fire the bot up
so ur trying to get the channel before the bot is ready
im telling you you are trying to get the channel before the channel is in the bot's cache
hmm
ok check
async def my_background_task(self):
^
IndentationError: unexpected indent
hmm lol.
fix edit
uhh
no recevied channel message
hmmm logs error?
Good job!
yes thanks
xd there is
here
explain automatic message send channel
time one min
Which line prob?
Ah i see but missing think "hello world" memssage
sorry confuse.
Ur loop func is outside cog btw
Ahh.. my no is have cog, no need
Okay there is code: @shrewd fjord
Checkinh
!d discord.Client.wait_until_ready
await wait_until_ready()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits until the clientโs internal cache is all ready.
Warning
Calling this inside [`setup_hook()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.setup_hook "discord.Client.setup_hook") can lead to a deadlock.
Hmmm
Altho idk what's the problem?
Bot is not sending message?
How are you starting the loop?
yeah but think hard.. and moment search google.
idk.
correct maybe.
Start the loop on setup_hook
yeah there is
Seems like the loop starting before even bot fully loaded ๐ฟ
Hmm
Also make sure to learn english more standardly :)
Works
but alredy little i am no good.
Ok try.
Ye ik ;-;
Show the before_loop func?
yeah
Gud job!
Yes noice
Yeah ok moment...
Ok let me send what's happening here
- You started the loop before the bot came online
- so doing it on setup_hook fixes that
- you need load the internal cache, so bot can get the channel with no problem
And these are the problems and solutions ๐ฟ
Sarth 
Ahh
you can use ```py
channel = client.get_partial_messageable(channel_id, type=discord.ChannelType.text)
await channel.send("...")
....
Why using big brain ;-;
Solve my problem bruh
im using my last brain cells, that got left after making a slash help command
๐
if it's mongodb then you're talking to wrong person
Slashes are not that bad-
aiosqlite ๐
bet
ok so i have problem with syntax and stuff
Whatever, i just need to delete whole table to make changes... Anyway to avoid that? Like typing the command on console it will execute for only 1 time?
I can add ALTER syntax or query on code, but the prob is it doesn't detect if it ran alr or not ๐
We are gonna lose even more when we get to items
Meh
nahh.
what error do you get
๐ right
nop, but is correct spooky.exe solution code ๐
๐ฅฒ
ya already thanks spooky
and @slate swan no good okay lol.
whats wrong with it
What's wrong?
it was working awhile ago
U have 2 message event?
every message doesn't have a content, it will return None for messages which have only images or embeds
and you cannot use in on None
!e ```py
if "deneme" in None:
print("he")
@slate swan :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | TypeError: argument of type 'NoneType' is not iterable
import discord
import responses
async def send_message(message, user_message, is_private):
try:
response = responses.handle_response(user_message)
await message.author.send(response) if is_private else await message.channel.send(response)
except Exception as e:
print(e)
def run_discord_bot():
TOKEN = 'token'
client = discord.Client()
@client.event
async def on_ready():
print(f'{client.user} is now running!')
@client.event
async def on_message(message):
# Make sure bot doesn't get stuck in an infinite loop
if message.author == client.user:
return
# Get data about the user
username = str(message.author)
user_message = str(message.content)
channel = str(message.channel)
# Debug printing
print(f"{username} said: '{user_message}' ({channel})")
# If the user message contains a '?' in front of the text, it becomes a private message
if user_message[0] == '?':
user_message = user_message[1:] # [1:] Removes the '?'
await send_message(message, user_message, is_private=True)
else:
await send_message(message, user_message, is_private=False)
# Remember to run your bot with your personal TOKEN
client.run(TOKEN)
help
message.content will also be set to None if you haven't enabled the message_content intent
I get intends error about init() in client = discord.Client()
Code golfing enthusiast, you're a great lad, could you help me resolve my issue please?
It's probably something very dumb
I've removed the "fixes"
the "fixes" are just an example of how you should create your bot/clients
I meant that the code sent here is without the copied code
What's the point of that function
you have to specify intents when you create the client with discord.Client()
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.
There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.
Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.
I'm quite dumb, can you give me an example 9f how that would work?
in your case that would be creating a similar intents object as shown and adding intents=intents when you create the client
in the example here intents are passed in through intents=intents in commands.Bot(...)
you can do a similar thing with discord.Client(...)
Where do I get intents from?
this bit creates the intents in the example```py
Enable all standard intents and message content
(prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True
discord.intents or discord.Client(intents) or importing it
So it's from the discord package
from discord import Intents
```yes
intents = discord.Intents.default()
intents.message_content = True
```this also works if you don't want to import `Intents` separately
sorry no
my brain's cache is overflowing with intents
just know you have to pass them in when you create discord.Client() and the like
and this is how you create them
which line is that ?
and it's very helpful
I would disagree on that
Not again
Chat gpt isn't "I can't code so use this" tool
it literally made my bot and now I'm just telling it to make the responses whatever I like, its making it faster than I can type it, even if its just simple if statements
eh, I told it to make a working code based on my nonworking code
and it did just that, it had several errors, but I just told it the errors
ChatGPT's knowledge is cut off after 2021, so it doesn't know that intents are required now
you can get it for free if you're a student
ye, it literally told me that lol
I said the version and the date of release

and it told me that it's most likely a change in the package causing it or (something else I forgot) but it doesnt know
true, i asked it and it said 2021.
cant wait for ChatGPT4 lol, it should be able to make an entire website without a problem
Not true
not that the current one cant, but it uses some outdated packages
^
we've had this discussion multiple times a day for a while in #python-discussion now
don't write code with chatGPT
Chat gpt is too slept on
not entirely by itself, but it made me a website about cats when I asked it and also can code in sass to make fancy animations lol
its overrated too
Yea only frontend
Not at all
in a few cases yes
it helped me with a presentaiton...
for me at least, its more helpful than asking someone else lol
because I can just copy my code and say "I get his error, make it work"
and it does
Anyways, it's getting off-topic 
Off-topic channel: #ot2-never-nesterโs-nightmare
Please read our off-topic etiquette before participating in conversations.
nostalgia after seeing ur pfp.......................................
who cares if I do when I use it for personal use lol
also, I just placed the text from changelog about discord packages 2.1 and about what intents are from another updated recently thread and told it to adjust my code based on the way the other codes are and it actually worked
do whatever you want, but don't complain when it can't do whatever you tell it to do
Im not relaying only on it, Im just using it because its a great tool
Dont be like the web developers that hated copilot when it first released, please
(reddit threats)
sometimes it will try to fix an error, fail, and give you a paragraph bsing about how it supposedly fixed the error
copilot is a different story, chatgpt wasn't made to write code
ye, it did that the first time before I mentioned the dates of changelogs. You gotta tell it when its wrong instead of trying to fix an issue that's just change how it works in newer versions
and even then, based on what text you give it, it can redact your code to it if you supply it with changelogs
we should move to ot
off topic?
yes
but that's still about how it helped me fix my python code
discord bot that uses python code
that reminds me, now i gotta use time and date with my bot
Should I make it so it remembers when a message is sent or do I make it save the current time and date when its asked to execute a command that requires it to do so?
and does it matter from where i save the current time and date?
what are you trying to make?
"I apologize for the confusion, here's an example of how your main.py, bot.py, and responses.py could be set up using the latest version of discord.py (2.1) and the features it provides. is the log from chatGPT(and the code afterwards provided) that made my bot work
just a bot that's only for my servers and helps me and my friend automate stuff
and keep the dates of certain information that we supply to it (we need the dates and how long the prosses takes)
I meant, what are you trying to make that involves storing time/date
and he's making a script that we can have on both PCs that automatically say the bot commands and then save the reply in a notepad (on both PCs)
it's somewhat personal
๐คฆโโ๏ธ
And we need it to be a discord bot
so you're just testing ping?
no
we are having a start and end commands
it saves the time from -start to -end commands and when you've said them
and then we need a way to store them in a txt file and to filter that
and it also saves other irelevant information among the dates.
its kinda like the chatlogs, but not exactly
like I said, its just for my server
then datetime.now() should be fine
ty
txt files ain't gonna work for that, use something like postgres (recommended) or sqlite (fine for a small bot)
He already has a scripts made that works with discord bot commands and then saves the bot replies
he who
it automatically times the command and saves the reply, we tested it on song requests and it works, it also has a small UI where we type the command we want to run
My friend who's working with me on something
๐ oh ok
hello, I would like to be able to have the choice to add a @mention in my command with a condition.
1 !hi = send "hi + author mention
2 !hi @mention = author mention say "hi" to @mention
how to do this please?
hello do you know any good youtube tutorials to learn how to make discord bots in python ?
!d discord.Member.mention
you can use the mention property to mention users
No documentation found for the requested symbol.
!d discord.Member.mention
property mention```
Returns a string that allows you to mention the member.
just"Returns a string that allows you to mention the member."...
that, I already knew, I ask how to write that now?
if I send for example:
!hi @winged coral
the bot's response should be:
Tom Evans say hello to @winged coral
So access that property and use string formatting to plug it into your response string
F strings would be easiest
something like
ctx.send(member.mention)
where member is an instance of discord.Member
sorry, its not my question
this is correct?:
async def test(self, ctx, member):
member=discord.Member
if member ==True:
await ctx.send (f"{ctx.author.mention} say hello to {ctx.member.mention}")
else:
await ctx.send (f"Hello {ctx.author.mention}")
Not at all
discord.Member is a class, you want a specific instance of that class which is being passed to your command
You can typehint the member arg as the discord.Member class to get the library to handle the conversion implicitly
You also don't need the if True check, I don't really understand why it's there at all
And you're using ctx.member, which isn't a thing
i'm a noob, sorry ^^
It's okay
Even with the information you gave me, I don't quite understand how to correct this.
Do you have any kind of understanding in regards to OOP (object oriented programming) in python? Classes etc
not really
I help myself a lot of tutorials in French to understand and I am taking courses on the udemy website, but I still have work to do
I recommend you begin to learn about some basic OOP
is there an event for the server join ?
d.py is HEAVILY object oriented and almost every argument your receive will be a custom class
When the bot joins a server or when a user joins a server?
the bot
!d discord.on_guild_join Here :)
discord.on_guild_join(guild)```
Called when a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild") is either created by the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") or when the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") joins a guild.
This requires [`Intents.guilds`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.guilds "discord.Intents.guilds") to be enabled.
thanks
@tree.command(name='meme',description='yay a meme') #declares a slash command
async def meme(interaction:discord.Interaction): #creates function for interaction
await interaction.response.defer() #Defers the response, allowing upto 15 minutes to respond to the interactiob
em = discord.Embed(title='',description='')
async with aiohttp.ClientSession() as cs:
async with cs.get('https://www.reddit.com/r/shitposting/new.json?sort=hot') as r:
res = await r.json()
x = randint(0,25)
em.set_image(url=res['data']['children'][x]['data']['url'])
em.set_footer(text='these memes suck')
print(res['data']['children'][x]['data']['url'])
await interaction.followup.send(embed=em)
most of the time the image does not load why
i looked at the url and there is an image
Doesn't load you mean what exactly
Is there an error
Also print the url you put into embed
A you already do that
Then give an example of that URL
how can i replace ctx.author.display_name by @mention? in line 4
embed=discord.Embed (title=f"Un gage pour {ctx.author.display_name}
@commands.command()
async def gage(self, ctx,):
r = random.choice(liste_gage)
description_embed = r.format(mention=ctx.author.mention)
embed=discord.Embed (title=f"Un gage pour {ctx.author.display_name}!", color=discord.Color.orange(), description = (description_embed))
embed.set_author(name=ctx.author.display_name, icon_url=ctx.author.avatar.url)
file = discord.File('images/gage_img.png')
embed.set_thumbnail(url="attachment://gage_img.png")
await ctx.send(embed=embed, file=file)
author.mention
without ctx?
dont work!
why?
because that doesn't work

and if i want add this in the description, its work for the author, but dont work for mention...
look
@commands.command()
async def gage(self, ctx,):
r = random.choice(liste_gage)
description_embed = r.format(mention=ctx.author.mention)
embed=discord.Embed (title=f"Un gage pour {ctx.author.display_name}!", color=discord.Color.orange(), description =(f"{ctx.author.mention}, {description_embed}"))
embed.set_author(name=ctx.author.display_name, icon_url=ctx.author.avatar.url)
file = discord.File('images/gage_img.png')
embed.set_thumbnail(url="attachment://gage_img.png")
await ctx.send(embed=embed, file=file)
ctx.author.mention = !gage @mention, no?
is there a way to check if a user has a early supporter badge or not
Iirc it actually does but for some reason only on certain OSs cause discord smokes smth
!d discord.User.public_flags
property public_flags```
The publicly available flags the user has.
Can somebody tell me why my code isnt working? When I do !verify nothing happens?
import discord
from discord.ext import commands
client = commands.Bot(command_prefix = "!")
@client.command()
async def verify(ctx):
author = ctx.message.author
role = discord.utils.get(ctx.guild.roles, name="Verified")
await author.add_roles(role)
await ctx.send(f"{author.mention} has been verified and given the {role.name} role.")
client.run("-")
user_channels = {}
@bot.event
async def on_message(message):
if message.guild is None:
user_channel = user_channels.get(message.author.id)
if user_channel:
await bot.get_channel(user_channel).send(f"{message.author.mention} said: {message.content}")
else:
guild = bot.get_guild(1063208577130582016)
user_channel = await guild.create_text_channel(f"modmail-{message.author.name}")
user_channels[message.author.id] = user_channel.id
await user_channel.send(f"{message.author.mention} said: {message.content}")
why isnt this working? Its not creating a channel in the guild.
bot has admin, bot is in the guild
nvm, i got the issue.
whoever wants that code can have it
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.
There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.
Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.
enable intents
hello
async def warn(ctx, user: discord.User, *, reason):
warn.warn_user(ctx, user, user_warns, *reason)
def warn_user(ctx, user: discord.User, user_warns: dict, *, reason):
user_id = str(user.id)
if user_id not in user_warns:
user_warns[user_id] = {}
warns = user_warns[user_id]
warn_number = len(warns) + 1
warns[f"warn{warn_number}"] = reason
saves.save_user_warns(user_warns)
await ctx.send(f'{user.name} was warned for {reason}')
I have these two functions where warn_user is in a file called warn, but the *reason in the original async def warn gets errored out and says its an unexpected argument? Anyone know why
I was writing my discord bot and i got this error:
can anyone help me pls
i writing it on replit
it says to enable your priveleged intents in the developer portal
well, i guess there isn't the object AsyncWebhookAdapter in discord
cuz ur hungarian Imma give you an advice that's gonna last you for the rest of your life
type "discord.py api reference" in google
type AsyncWebhookAdapter in the search bar
and it's gonna show you where the object is
szรญvesen tesรณ
!rule 5
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
why did a break the laws?
close call
"Lightening nuke bot" doesn't sound very appropriate in this server
nuke bot? sounds sus
oh, ye I tried to do it, but i changed the commands, and now the name is only nuke bot
yeah or if it still exists
its the file name and Im too bored to change it
I'm on phone I didn't check
Sus
user_channels = {}
first_dmed_user = None
@bot.event
async def on_message(message):
global first_dmed_user
user_channel = user_channels.get(message.author.id)
if message.guild is None:
if first_dmed_user is None:
first_dmed_user = message.author
if user_channel:
if message.channel.id in user_channels.values():
await first_dmed_user.send(f"You said in {message.channel.mention}: {message.content}")
else:
await bot.get_channel(user_channel).send(f"{message.author.mention} said: {message.content}")
else:
guild = bot.get_guild(1063208577130582016)
user_channel = await guild.create_text_channel(f"modmail-{message.author.name}")
await user_channel.set_permissions(message.author, read_messages=False)
await user_channel.set_permissions(guild.default_role, read_messages=False)
category_id = 1066437408582815754
category = bot.get_channel(category_id)
await user_channel.edit(category=category)
# Store the channel ID in the dictionary
user_channels[message.author.id] = user_channel.id
# Send the message to the user's channel
await user_channel.send(f"{message.author.mention} said: {message.content}")
@bot.event
async def on_ready():
@bot.event
async def on_message(message):
if message.channel.id in user_channels.values():
await first_dmed_user.send(f"{message.author.mention} said in {message.channel.mention}: {message.content}")```
Why are you nesting the on_message?
Anyone know why this isnt working?
Also FYI you can only one one @client.event for each event
So the 2nd on_message will override the first one
weirdest thing I saw today
so i should remove one?
oh? are you not able to do 2 on_message() events?
ig not
well that sux
what should i do? @sick birch
not with discord.Client, but it's possible with commands.Bot using listeners
Is this leetcode
I have a "@client.listen()"
Don't nest the on message
And remove one of your other on messages
you can have 2 event of same kind using this ```py
@bot.listen("on_message")
async def name_this_anything(msg):
...
@bot.listen("on_message")
async def name_this_anything_but_not_same_as_above(msg):
...
Command raised an exception: TypeError: Context.send() got an unexpected keyword argument 'components'
u send a view in discord.py
Yes
?
i have a bot thats broken
i need it to read a discordid and give it a role from the message
the message author is not the person receiving the role
.send doesn't not have a arg components
!d discord.ext.commands.Context.send
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
This works similarly to [`send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") for non-interaction contexts.
For interaction based contexts this does one of the following...
Can someone help me? I get this error line 5, in <module> intents.guild_role = True
This is the code
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.guild_role = True
client = commands.Bot(command_prefix = "!", intents=intents)
@client.command()
async def verify(ctx):
author = ctx.message.author
role = discord.utils.get(ctx.guild.roles, name="Verified")
await author.add_roles(role)
await ctx.send(f"{author.mention} has been verified and given the {role.name} role.")
client.run("-") ```
?
And how to add a component?
can someone help me
that intent does not exist
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.
There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.
Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.
hey, its me again, anyone can help me pls
discord.Member.
omg im so stupid
ty
ummm
i think i have another
question
@client.has_permissions(kick_members=True)
@discord.ext.commands.bot_has_permissions(**perms)```
Similar to [`has_permissions()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.has_permissions "discord.ext.commands.has_permissions") except checks if the bot itself has the permissions listed.
This check raises a special exception, [`BotMissingPermissions`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.BotMissingPermissions "discord.ext.commands.BotMissingPermissions") that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
@proper plume
tyy
Decors
you need to import it
this?
huh?
no look at the docs of what i linked
if u dont understand how to import what i just linked i suggest learning some basics before divining into a discord bot
Bro he linked docs
they should make a quiz for python basics to gain access to this channel
Fr people in this channel are so clueless and first thing they do is make discord bot when learning python and are stuck in tutorial hell
Can someone help me with those errors? Heres the code
class Verification(discord.ui.View):
def __init__(self):
super().__init__(timeout = None)
@discord.ui.button(label="Verify",custom_id = "Verify",style = discord.ButtonStyle.success)
async def verify(self, interaction, button):
role = -
user = interaction.user
if role not in [y.id for y in user.roles]:
await user.add_roles(user.guild.get_role(role))
await user.send("You have been verified!")
@bot.command()
async def initialize(ctx):
embed = discord.Embed(title = "Verification", description = "Click below to verify.")
await ctx.send(embed = embed, view = Verification())
bot.run(os.environ.get('-'))
Where is the error
All you did was sent the traceback (I think it's called) but no actual error
ur token wrong
Nah I mean that the bot aint starting
im pretty sure
the token will be pasted into bot.run(os.environ.get('Token'))
Alright sec
from discord.ext import commands
import discord.ui
import os
intents = discord.Intents.all()
bot = commands.Bot(command_prefix='.', intents=intents, help_command=None)
@bot.event
async def on_ready():
print('System rebooted.')
bot.add_view(Verification())
class Verification(discord.ui.View):
def __init__(self):
super().__init__(timeout = None)
@discord.ui.button(label="Verify",custom_id = "Verify",style = discord.ButtonStyle.success)
async def verify(self, interaction, button):
role = -
user = interaction.user
if role not in [y.id for y in user.roles]:
await user.add_roles(user.guild.get_role(role))
await user.send("You have been verified!")
@bot.command()
async def initialize(ctx):
embed = discord.Embed(title = "Verification", description = "Click below to verify.")
await ctx.send(embed = embed, view = Verification())
bot.run(os.environ.get('-'))```
can't tell why the bot won't start with what u provided
traceback the error log
not ur code
Traceback (most recent call last):
File "c:\Users\kamil\Desktop\Python\Worthy-Bot\main.py", line 31, in <module>
bot.run(os.environ.get("TOKEN"))
File "C:\Users\kamil\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 716, in run
return future.result()
File "C:\Users\kamil\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 695, in runner
await self.start(*args, **kwargs)
File "C:\Users\kamil\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 658, in start
await self.login(token)
File "C:\Users\kamil\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 508, in login
raise TypeError(
TypeError: token must be of type str, not NoneType ```
yeah ur not supplying a token
Lmao I know that I need to put the token where it says TOKEN
You need to import dotenv
Collecting dotenv
Using cached dotenv-0.0.5.tar.gz (2.4 kB)
Preparing metadata (setup.py) ... error
error: subprocess-exited-with-error
ร python setup.py egg_info did not run successfully.
โ exit code: 1
You have to pip install python-dotenv
Ah ok
python-dotenv
thanks I wrote pip install dotenv
Yeah I figured
line 1
.all()
^
SyntaxError: invalid syntax
Now i get this
Idk why it says line 1 but .all is in line 9
Traceback (most recent call last):
File "c:\Users\kamil\Desktop\Python\Worthy-Bot\main.py", line 34, in <module>
bot.run(os.environ.get("TOKEN"))
File "C:\Users\kamil\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 716, in run
return future.result()
File "C:\Users\kamil\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 695, in runner
await self.start(*args, **kwargs)
File "C:\Users\kamil\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 658, in start
await self.login(token)
File "C:\Users\kamil\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 508, in login
raise TypeError(
TypeError: token must be of type str, not NoneType
Now theres thesee errors
You did create a .env file right?
Do that in the same directory
Just name it
.env
done
done
Save the file and run the code again
Traceback (most recent call last):
File "c:\Users\kamil\Desktop\Python\Worthy-Bot\main.py", line 34, in <module>
bot.run(os.environ.get("TOKEN"))
File "C:\Users\kamil\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 716, in run
return future.result()
File "C:\Users\kamil\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 695, in runner
await self.start(*args, **kwargs)
File "C:\Users\kamil\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 658, in start
await self.login(token)
File "C:\Users\kamil\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 508, in login
raise TypeError(
TypeError: token must be of type str, not NoneType
Did you do this?
Did you create the .env file in the same folder as your py file?
yes
Yes
so you want the token?
yea I wont
Replace that "-" with "TOKEN"
Traceback (most recent call last):
File "c:\Users\kamil\Desktop\Python\Worthy-Bot\main.py", line 34, in <module>
bot.run(os.environ.get("TOKEN"))
File "C:\Users\kamil\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 716, in run
return future.result()
File "C:\Users\kamil\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 695, in runner
await self.start(*args, **kwargs)
File "C:\Users\kamil\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 659, in start
await self.connect(reconnect=reconnect)
File "C:\Users\kamil\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 598, in connect
raise PrivilegedIntentsRequired(exc.shard_id) from None
discord.errors.PrivilegedIntentsRequired: Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.
Run it now
I got this error
You need to head over to the developer portal and enable privileged intents
Yes
Gj
Yo bro
Now I got another problem lol
Ignoring exception in view <Verification timeout=None children=1> for item <Button style=<ButtonStyle.success: 3> url=None disabled=False label='Verify' emoji=None row=None>:
Traceback (most recent call last):
File "C:\Users\kamil\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ui\view.py", line 414, in _scheduled_task
await item.callback(interaction)
File "c:\Users\kamil\Desktop\Python\Worthy-Bot\main.py", line 24, in verify
user = interaction.user
AttributeError: 'Button' object has no attribute 'user'
Ignoring exception in view <Verification timeout=None children=1> for item <Button style=<ButtonStyle.success: 3> url=None disabled=False label='Verify' emoji=None row=None>:
Traceback (most recent call last):
File "C:\Users\kamil\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ui\view.py", line 414, in _scheduled_task
await item.callback(interaction)
File "c:\Users\kamil\Desktop\Python\Worthy-Bot\main.py", line 24, in verify
user = interaction.user
AttributeError: 'Button' object has no attribute 'user'
this is the error
Can we see the button callback function?
looks like u typehinted interaction to a button?
import discord
from discord.ext import commands
import discord.ui
import os
from dotenv import load_dotenv
load_dotenv()
intents = discord.Intents.all()
bot = commands.Bot(command_prefix='.', intents=intents, help_command=None)
@bot.event
async def on_ready():
print('System rebooted.')
bot.add_view(Verification())
class Verification(discord.ui.View):
def __init__(self):
super().__init__(timeout = None)
@discord.ui.button(label="Verify",custom_id = "Verify",style = discord.ButtonStyle.success)
async def verify(self, interaction, button):
role = 1061850690110111774
user = interaction.user
if role not in [y.id for y in user.roles]:
await user.add_roles(user.guild.get_role(role))
await user.send("You have been verified!")
@bot.command()
async def initialize(ctx):
embed = discord.Embed(title = "Verification", description = "Click below to verify.")
await ctx.send(embed = embed, view = Verification())
bot.run(os.environ.get("TOKEN"))
If I'm to guess you probably fipped the order of the arguments
use user = interaction.message.author instead of user = interaction.user
in line 24 maybe that will help idk
it's not a message. it's a button they are clicking so this is invalid. per docs, interaction.user is correct
Where can I find the docs?
thanks
Soo what do I need to do to fix this?
This is my first time doing a discord bot in python
try to swap interaction and button
whats the error show?
Ignoring exception in view <Verification timeout=None children=1> for item <Button style=<ButtonStyle.success: 3> url=None disabled=False label='\u2705' emoji=None row=None>:
Traceback (most recent call last):
File "C:\Users\kamil\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ui\view.py", line 414, in _scheduled_task
await item.callback(interaction)
File "c:\Users\kamil\Desktop\Python\Worthy-Bot\main.py", line 26, in verify
await user.add_roles(user.guild.get_role(role))
File "C:\Users\kamil\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\member.py", line 1007, in add_roles
await req(guild_id, user_id, role.id, reason=reason)
AttributeError: 'NoneType' object has no attribute 'id'
y.id is none existent
if not any(role == _role .id for _role in user.roles)
@autumn totem
logs
File "C:\Users\kamil\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ui\view.py", line 414, in _scheduled_task
await item.callback(interaction)
File "c:\Users\kamil\Desktop\Python\Worthy-Bot\main.py", line 26, in verify
await user.add_roles(user.guild.get_role(role))
File "C:\Users\kamil\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\member.py", line 1007, in add_roles
await req(guild_id, user_id, role.id, reason=reason)
AttributeError: 'NoneType' object has no attribute 'id'
Ignoring exception in view <Verification timeout=None children=1> for item <Button style=<ButtonStyle.success: 3> url=None disabled=False label='\u2705' emoji=None row=None>:
Traceback (most recent call last):
File "C:\Users\kamil\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ui\view.py", line 414, in _scheduled_task
await item.callback(interaction)
File "c:\Users\kamil\Desktop\Python\Worthy-Bot\main.py", line 26, in verify
await user.add_roles(user.guild.get_role(role))
File "C:\Users\kamil\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\member.py", line 1007, in add_roles
await req(guild_id, user_id, role.id, reason=reason)
AttributeError: 'NoneType' object has no attribute 'id'
yh
how do I create timed events so that a command is run by the bot every 10 minutes
Bro ur a genius ong
it was wrong thanks alot bro
yup np
bruh i was so close, dam using the wrong @
How do I add a paragraph between this 2 sentences?
Is there any other way to do this?
duration_minutes = duration_seconds / 60
duration_hours = duration_minutes / 60
duration_days = duration_hours / 24
duration_weeks = duration_days / 7
if duration_seconds < 60:
if duration_seconds == 1:
duration_string = "1 second"
else:
duration_string = f"{duration_seconds} seconds"
elif duration_seconds < 3600:
if duration_minutes == 1:
duration_string = "1 minute"
else:
duration_string = f"{duration_minutes:.2f} minutes"
elif duration_seconds < 86400:
if duration_hours == 1:
duration_string = "1 hour"
else:
duration_string = f"{duration_hours:.2f} hours"
elif duration_seconds < 604800:
if duration_days == 1:
duration_string = "1 day"
else:
duration_string = f"{duration_days:.2f} days"
else:
if duration_weeks == 1:
duration_string = "1 week"
else:
duration_string = f"{duration_weeks:.2f} weeks"```
Pass it into timedelta of the datetime module
It'll convert for you
But it will not check for singular cases and plural cases?
You could do that pretty easily:
duration_string = f"{duration_seconds} second" + ("" if duration_seconds == 1 else "s")
is there a way to create my own function decorator that can check if a given id exists in a command?
Or ("s" if duration_seconds > 1 else "") if that suits your fancy more
second(s)
fixed
how do I check how many times a reaction is made in a message
i think the reaction object has a .count
!d discord.Message.reactions
Reactions to a message. Reactions can be either custom emoji or standard unicode emoji.
Hello! Can you help me? I wrote a discord giveaway bot and it doesn't work.
You also need the reactions intent.
"messsage"
so what instead of it
Well "message" you used 3 s's
oh
Is it better to use "Indefinite" or "None" if the duration is not provided?
Shouldn't really matter if it's user-facing
What is most common to use?
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'async_generator' object has no attribute 'flatten'
Don't copy old code.
i didn't know that one and it isn't working that i copied ๐
users = await new_msg.reactions[0].users().flatten()
what do I need to change this to
Remove flatten
Don't I still need to parse the duration to extract the unit?
If by "parse" you mean just plugging it into timedelta, yes
For example, !mute @user 1h or !mute @user 30m where 1h and 30m are used to represent 1 hour and 30 minutes respectively.
yes you will still have to parse that out
for some reason my discord.py program doesn't have runtime exceptions? there is nothing in the console when a runtime error happens
or am i just on something
Do you have any error handlers?
i have some but not for the ones that arent showing
like if i try adding a string to an int theres no error the bot just says application failed to respond or something
let's see it
People usually do those wrong
async def on_command_error(self, ctx, error):
if isinstance(error, commands.errors.CommandOnCooldown):
embed = discord.Embed(title="Error",
description="You have already used this command. You can use it again in " + seconds_to_time(
error.retry_after) + ".", color=discord.Color.red(),
timestamp=datetime.datetime.now() + datetime.timedelta(seconds=error.retry_after))
embed.set_author(name=ctx.author.name, icon_url=ctx.author.avatar)
await ctx.send(embed=embed)
if isinstance(error, commands.MissingRole):
embed = discord.Embed(title="Error", description="You do not have the roles to use this command.", color=discord.Color.red())
embed.set_author(name=ctx.author.name, icon_url=ctx.author.avatar)
await ctx.send(embed=embed)```
nvm just read the docs
TypeError: object of type 'async_generator' has no len()
mhm and how to pick someone from all users that reacted to a message?
!d discord.Reaction.users
async for ... in users(*, limit=None, after=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.11)") representing the users that have reacted to the message.
The `after` parameter must represent a member and meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.
Changed in version 2.0: `limit` and `after` parameters are now keyword-only.
Examples
Usage...
!d random.choice
random.choice(seq)```
Return a random element from the non-empty sequence *seq*. If *seq* is empty, raises [`IndexError`](https://docs.python.org/3/library/exceptions.html#IndexError "IndexError").
remember that it returns an iterator, not a list
Like this?
if infraction['duration'] is not None:
duration_seconds = infraction['duration']
duration = datetime.timedelta(seconds=duration_seconds)
if duration.days > 0:
if duration.days == 1:
duration_str = f"{duration.days} day"
else:
duration_str = f"{duration.days} days"
elif duration.seconds > 3600:
hours = duration.seconds // 3600
if hours == 1:
duration_str = f"{hours} hour"
else:
duration_str = f"{hours} hours"
elif duration.seconds > 60:
minutes = duration.seconds // 60
if minutes == 1:
duration_str = f"{minutes} minute"
else:
duration_str = f"{minutes} minutes"
else:
seconds = duration.seconds
if seconds == 1:
duration_str = f"{seconds} second"
else:
duration_str = f"{seconds} seconds"
infraction["duration"] = duration_str
else:
infraction["duration"] = "Indefinite"```
Looks about right
Well it doesn't work with:
'duration': None and 'duration': '1800'
Elaborate on what you mean by "doesn't work"
For some reason its having problems with converting when its a number
In this case, '1800'
What sort of problems?
I'm wondering what makes you think "it's having problems" because it could be any number of things
Details, tracebacks, code, expected behaviour vs actual behaviour would all be great
It won't post the embed:
# Add a field for each infraction
infraction_string = ""
if infraction['type'] in ["Ban", "Mute"]:
if infraction['duration'] == "None":
infraction["duration"] = "Indefinite"
else:
duration_seconds = int(infraction['duration']) if infraction['duration'] != "None" else None
if duration_seconds is not None:
datetime.timedelta(minutes=duration_seconds)
minutes = duration.seconds // 60
if minutes == 1:
duration_str = f"{minutes} minute"
elif minutes > 1:
duration_str = f"{minutes} minutes"
infraction["duration"] = duration_str
field_value = f"**Duration:** {infraction['duration']}\n**Reason:** {infraction['reason']}"
else:
field_value = f"**Reason:** {infraction['reason']}"
infraction_string += field_value + "\n\n"
# Create an embed object for the modlogs message
description = f"{member.mention}"
embed = discord.Embed(title=f"{member.name}#{member.discriminator}'s Logs", description=description, color=discord.Color.orange())
# Send the embed message
await ctx.send(embed=embed)```
No
Error handlers?
Nope
!pastebin the whole thing please
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.
Hi. How do I get my Discord bot to connect to a voice channel?
when trying to get the guild of a server from an interaction it gives me this: <member 'guild_id' of 'Interaction' objects>
This is my code: py await interaction.response.send_message(discord.Interaction.guild_id)
show full code please
you are also using discord.Interaction which is a class.
you need to do interaction.guild_id
You can get it to join with await voice_channel.join() iirc
But getting it to speak is a different story
await connect(*, timeout, reconnect, self_deaf=False, self_mute=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
An abstract method called when the client initiates the connection request.
When a connection is requested initially, the library calls the constructor under `__init__` and then calls [`connect()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceProtocol.connect "discord.VoiceProtocol.connect"). If [`connect()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceProtocol.connect "discord.VoiceProtocol.connect") fails at some point then [`disconnect()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceProtocol.disconnect "discord.VoiceProtocol.disconnect") is called.
Within this method, to start the voice connection flow it is recommended to use [`Guild.change_voice_state()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.change_voice_state "discord.Guild.change_voice_state") to start the flow. After which, [`on_voice_server_update()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceProtocol.on_voice_server_update "discord.VoiceProtocol.on_voice_server_update") and [`on_voice_state_update()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_voice_state_update "discord.on_voice_state_update") will be called. The order that these two are called is unspecified.
^
And how can I make the bot share screen and play a video?
no can do
Yes you can, I know a bot that shares screen and shows youtube videos
then they are selfbotting and that is against discord tos
Is there a way for a bot to show live streams?
a bot account canโt so no
Is there a way for a bot to show live streams in a chat or voice channel?
once again, a bot account canโt do that, so no
your only bet is sending a link in chat
Anyone knows a simple but reliable way to load a cog using discord.py?
thatโs about as far as you can get for video
yea switch to disnake
eh
reliable? whats wrong with the load_extension/add_cog mechanism?
I tried it but the whole cog thingy broke down so I just deleted the whole previous code and am restarting from scratch again
are there really no docs on it ?
there are but im too dumb too understand lol
yeah its quite weird that dpy doesnt have an example of combining cogs and extensions
Interesting
aren't they similiar to disnake tho just
def setup(bot):
bot.add_cog(ButtonEvent(bot))
then the load_extensions()
disnake is a fork of discord.py so thats what you would expect, but dpy 2.0 made add_cog and load_extension asynchronous
https://discordpy.readthedocs.io/en/stable/migrating.html#extension-and-cog-loading-unloading-is-now-asynchronous
oh there is an example. why tf is it nested in change logs lmao
ehh it doesnt describe the use of cogs and extensions
yeah but at least it's something lol
Indeed
a typical structure would be each cog in its own file (or package) along with a setup function (making it an "extension"), and then a setup_hook or similar that loads the extension when your bot starts, e.g. ```py
cogs/stuff.py
class Stuff(commands.Cog):
...
async def setup(bot):
await bot.add_cog(Stuff(...))```
# main.py
class MyBot(commands.Bot):
async def setup_hook(self):
await self.load_extension("cogs.stuff")```
very interesting
yeah thanks
The code works but when I try to run a command it gives me thsi error in the terminal :
discord.ext.commands.errors.CommandNotFound: Command "ping" is not found
but the command is present in the cog
I make autosetup, screw doing add_cog for each cog, too wet code
Interesting
I married inspect
Very interesting
How is it present and is the cog added
Seems legit, how do you load extension?
Legit except naming convention, classes follow PascalCase
Oh wait
Or UpperCamelCase those are same things
Unrelated
Ye there's an issue
Interesting
You need to subclass the bot like this
class Bot(commands.Bot):
async def setup_hook(self):
...
bot = Bot(...)```
Not the way you did
And yeah better name variable bot instead of client
messages = {}
@bot.event
async def on_message(message):
if message.author.bot:
return
user_messages = messages.get(message.author.id, [])
user_messages.append(message.content)
user_messages = user_messages[-5:]
messages[message.author.id] = user_messages
if user_messages.count(message.content) > 1:
await message.delete()
await message.channel.send("This message was deleted for being a duplicate.")``` Why isnt this code working?
Yeh no still the same error:
Because for some reason you named your subclass fun and yet your instance is still instance of commands.Bot and not your class
*Simpler terms *
I think code example shows everything
Doesn't it
Interesting
I need to document it
So this should be the same like this?:
Interesting
well I removed the cog var and just put the name of the cog but it still isn't working '-'
when I run the +ping command it just sends this error in the terminal:
EXTENSIONS = ("fun",)
class MyBot(commands.Bot):
async def setup_hook(self):
for ext in EXTENSIONS:
await self.load_extension(ext)
async def on_ready(self):
print("Ready")
bot = MyBot(...)
bot.run(...)```
Very spoonfeeding @tawdry swallow
Ye Very Spoonfeeding lol
@bot.command(pass_context=True)
@commands.has_permissions(administrator=True)
async def clean(ctx, limit: int):
await ctx.channel.purge(limit=limit)
await ctx.send('Cleared by {}'.format(ctx.author.mention))
await ctx.message.delete()
@clean.error
async def clear_error(ctx, error):
if isinstance(error, commands.MissingPermissions):
await ctx.send("You cant do that!")
discord.ext.commands.errors.CommandNotFound: Command "purge" is not found
why
bro ur cmd is literally named clean
and what does your error say?
discord.ext.commands.errors.CommandNotFound: Command "purge" is not found
am i not using discord rewrite?
and what cmd did u just so
#clean
wdym
you do not have a command named purge
Ridiculous
yea
very little sleep past few days
same
how do i handle a timeout error in a wait_for
Normally
!d asyncio.TimeoutError this exception gets raised on a timeout, catch it using except
exception asyncio.TimeoutError```
A deprecated alias of [`TimeoutError`](https://docs.python.org/3/library/exceptions.html#TimeoutError "TimeoutError"), raised when the operation has exceeded the given deadline.
Changed in version 3.11: This class was made an alias of [`TimeoutError`](https://docs.python.org/3/library/exceptions.html#TimeoutError "TimeoutError").
much love my friend
I know, I remember they making the change about mentions in title and wherever, but that just doesn't want to work ๐
mentions in embed is crinj, just use the repr of User
How can I see someone's status after it updates?
on_presence_update
parameters being before, after?
yea
!d discord.on_presence_update
discord.on_presence_update(before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") updates their presence.
This is called when one or more of the following things change:
โข status
โข activity
This requires [`Intents.presences`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.presences "discord.Intents.presences") and [`Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members "discord.Intents.members") to be enabled...
if I did before.status would that show status updates only
or how can I target a certain update
!d discord.Member.activities
The activities that the user is currently doing.
Note
Due to a Discord API limitation, a userโs Spotify activity may not appear if they are listening to a song with a title longer than 128 characters. See GH-1738 for more information.
future: <Task finished name='discord-ui-view-timeout-05636a1ce2879fee8549ffc73c7f17ad' coro=<HelpView_Slash.on_timeout() done, defined at c:\Discord\Maja Projekt\MajaSystem_Test\modules\helpV2\cog.py:62> exception=AttributeError("'str' object has no attribute 'response'")>
Traceback (most recent call last):
File "c:\Discord\Maja Projekt\MajaSystem_Test\modules\helpV2\cog.py", line 65, in on_timeout
await self._help_command.response.edit(view=self)
AttributeError: 'str' object has no attribute 'response'```
class HelpView_Slash(nextcord.ui.View):
def __init__(self, ctx, help_command: "MyHelpCommand_Slash", options: list[nextcord.SelectOption], *, timeout: Optional[float] = 180):
super().__init__(timeout=timeout)
self._help_command = help_command
self.ctx = ctx
self.add_item(HelpDropdown_Slash(self.ctx, help_command, options))
async def on_timeout(self):
# remove dropdown from message on timeout
self.clear_items()
await self._help_command.response.edit(view=self)```
wtf
what is this ?
Huh?
@bot.event
async def on_presence_update(before, after):
print(f"{after} + {before.status}")
print(f"{after} + {after.status}")```
Output when changing my status from online to dnd
cyt#0001 + online
cyt#0001 + dnd
cyt#0001 + online
cyt#0001 + dnd```
Why is it doing it twice
what are u even doing?
This is a dynamic help command
https://paste.nextcord.dev/?id=167437775468384
Full Code here
*Nextcord
!d discord.Interaction.edit_original_response
await edit_original_response(*, content=..., embeds=..., embed=..., attachments=..., view=..., allowed_mentions=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the original interaction response message.
This is a lower level interface to [`InteractionMessage.edit()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionMessage.edit "discord.InteractionMessage.edit") in case you do not want to fetch the message and save an HTTP request.
This method is also the only way to edit the original message if the message sent was ephemeral.
It's just a fork that's not any different than discord.py
See
!d nextcord.Interaction.edit_original_message
await edit_original_message(*, content=..., embeds=..., embed=..., file=..., files=..., attachments=..., view=..., allowed_mentions=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the original interaction response message.
This is a lower level interface to [`InteractionMessage.edit()`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.InteractionMessage.edit "nextcord.InteractionMessage.edit") in case you do not want to fetch the message and save an HTTP request.
This method is also the only way to edit the original message if the message sent was ephemeral.
So where do i have to use it?
?
Instead of self._help_command.response.edit(view=self)?
i suggest you not just copy and paste code. the code you shown literally has
await interaction.edit_original_message(embed=embed)
in it so if you wrote you would know how to edit a message. Take the time to actually learn it, it can be fun
I dont have interaction in there
Only self
how can I get a users status like how mine is lol whenever it updates?
!d discord.on_presence_update
discord.on_presence_update(before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") updates their presence.
This is called when one or more of the following things change:
โข status
โข activity
This requires [`Intents.presences`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.presences "discord.Intents.presences") and [`Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members "discord.Intents.members") to be enabled...
!d discord.Member.activities then this
The activities that the user is currently doing.
Note
Due to a Discord API limitation, a userโs Spotify activity may not appear if they are listening to a song with a title longer than 128 characters. See GH-1738 for more information.
where would I use it to check
ohhh
wait before, after is like a member attribute?
hey everyone,
I just need some help with a feature im unsure of
@spooky.command()
async def remove(ctx, member: discord.Member):
guild = spooky.get_guild(1066633798046986300)
role1 = guild.get_role(1066646265737248908)
role2 = guild.get_role(1066646277397434419)
await ctx.send("What is the reason for removing?")
response = await spooky.wait_for_message('message')
if response.content == 'none' and ctx.author == response.author:
await ctx.send("no reason selected")
await member.remove_roles(role )
await member.edit(nick=None)
dynamic_timestamp = discord.utils.format_dt(datetime.now(), style="R")
remove=discord.Embed(
title="โ โ User Removed โฆ",
description=f"{member.mention} has been removed",
color=discord.Color(0xac0101)
)
remove.set_thumbnail(url=member.avatar)
remove.add_field(
name="Removed by:",
value=f"{ctx.author.mention}"
)
remove.add_field(
name="Date removed:",
value=dynamic_timestamp,
inline=True
await ctx.send(embed=remove)
else:
(literally same thing happens)
await ctx.send(embed=remove)```
I'm trying to make a feature which can remove roles from users, I'm trying to make the bot ask the person using the cmd a question (what is the reason for removing?) the bot should then store that as a variable (response) so it can be used in the embed later. Instead of recognising the users response and proceeding by sending the embed, the bot does nothing
Your issue is you need to use check
can you explain please or give an example in the code? I'm newer to python ^^
msg = await bot.wait_for("message", check=lambda x: x == ctx.author)
thank you!
!d discord.utils.find
discord.utils.find(predicate, iterable, /)```
A helper to return the first element found in the sequence that meets the predicate. For example:
```py
member = discord.utils.find(lambda m: m.name == 'Mighty', channel.guild.members)
``` would find the first [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") whose name is โMightyโ and return it. If an entry is not found, then `None` is returned.
This is different from [`filter()`](https://docs.python.org/3/library/functions.html#filter "(in Python v3.11)") due to the fact it stops the moment it finds a valid entry.
Changed in version 2.0: Both parameters are now positional-only.
Changed in version 2.0: The `iterable` parameter supports [asynchronous iterable](https://docs.python.org/3/glossary.html#term-asynchronous-iterable "(in Python v3.11)")s.
To be precise py activity = discord.utils.find(lambda x: isinstance(x, discord.CustomActivity), after.activities)
anyone know why these couldn't be resolved even though they are installed:
discord.ui, chat_exporter and pytz
discord.ui is a module fromdiscord.py
And datetime already has the same features as pytz
And send the error when you're trying to install and an error occurred
there isn't an error, i think its something to do with my interpreter because they worked fine yesterday
Then I can't tell what's wrong
Venv issue
!venv
Virtual environments are isolated Python environments, which make it easier to keep your system clean and manage dependencies. By default, when activated, only libraries and scripts installed in the virtual environment are accessible, preventing cross-project dependency conflicts, and allowing easy isolation of requirements.
To create a new virtual environment, you can use the standard library venv module: python3 -m venv .venv (replace python3 with python or py on Windows)
Then, to activate the new virtual environment:
Windows (PowerShell): .venv\Scripts\Activate.ps1
or (Command Prompt): .venv\Scripts\activate.bat
MacOS / Linux (Bash): source .venv/bin/activate
Packages can then be installed to the virtual environment using pip, as normal.
For more information, take a read of the documentation. If you run code through your editor, check its documentation on how to make it use your virtual environment. For example, see the VSCode or PyCharm docs.
Tools such as poetry and pipenv can manage the creation of virtual environments as well as project dependencies, making packaging and installing your project easier.
Note: When using PowerShell in Windows, you may need to change the execution policy first. This is only required once per user:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
i dont really understand what i do with venv
nvm i fixed it. i just fixed my interpreter
What way could I create a slash command thats prompt only allows a true or false answer?
Just set bool as type hint