#discord-bots
1 messages · Page 347 of 1
if you are developing the bot then u need to be familiar what features you are using and wether it requires any external permissions
!rule 5 it seems like you are creating a self bot as the headers aren't correct
5. Do not provide or request help on projects that may violate terms of service, or that may be deemed inappropriate, malicious, or illegal.
PS C:\Users\newca\Desktop\HavenCore> & c:/Users/newca/Desktop/HavenCore/.venv/Scripts/python.exe c:/Users/newca/Desktop/HavenCore/main.py
& : The term 'c:/Users/newca/Desktop/HavenCore/.venv/Scripts/python.exe' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included,
verify that the path is correct and try again.
At line:1 char:3
- & c:/Users/newca/Desktop/HavenCore/.venv/Scripts/python.exe c:/Users/ ...
-
+ CategoryInfo : ObjectNotFound: (c:/Users/newca/...ipts/python.exe:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException
How do i fix?
put py in front of all of that
also you can just do py main.py
which software should i use to do python?
VS
File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/aiohttp/connector.py", line 544, in connect
proto = await self._create_connection(req, traces, timeout)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/aiohttp/connector.py", line 911, in _create_connection
_, proto = await self._create_direct_connection(req, traces, timeout)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/aiohttp/connector.py", line 1235, in _create_direct_connection
raise last_exc
File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/aiohttp/connector.py", line 1204, in _create_direct_connection
transp, proto = await self._wrap_create_connection(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/aiohttp/connector.py", line 994, in _wrap_create_connection
raise ClientConnectorCertificateError(req.connection_key, exc) from exc
aiohttp.client_exceptions.ClientConnectorCertificateError: Cannot connect to host discord.com:443 ssl:True [SSLCertVerificationError: (1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1000)')]
what do i do
#discord-bots message see mac part
how to make an option optional in a / command
Give the argument a default value
wdym, like how would i code that?
ty
!e like normal functions
# 10 is the default value for 'arg'
def func(arg: int = 10):
print(arg)
func()
@naive briar :white_check_mark: Your 3.12 eval job has completed with return code 0.
10
i've done it like that and im getting an error regarding my two option ones
Did u imported
yep
@bot.tree.command(name="deploy", description="We're going on a deployment!")
@app_commands.describe(host="How long? Give me a date in which it will end please. [DD/MM/YYYY]", co_host="Why do you need this?", start_time="", overseer="")
async def deploy(interaction: discord.Interaction, host: str, co_host: str, start_time : Optional[str], overseer : Optional[str],) -> None:```
import is long before this but
that's my code ignore if it looks a bit odd, it's borrowed from another one of my commands
^
What is the error tho
nvm i think i fixed it
yeah it's called add dyno and then ?kick ?ban ?unban 💀
Discord's UI has them all
Hello, is anyone else having problem with installing discord components?
Hello which VPS you guys suggest?
Want to run Python 3.10 code 7-24 continously,
my issue not discord bot related but kinda same, working with API's Trading stuff
That package is outdated. Most Discord wrappers also already have their own components implementation anyways
The popular ones, anyway
So, how can I add buttons or something else
What library are you using?
3.12.2
No, I mean your Discord library, like discord.py or something
thanks broo
hello bot developrs
can yall check whether your discord application ID and your bot's public ID are the same or not
to check your discord application ID, go to discord.dev > application > general info > application ID
asking this cuz im not sure whether making my discord application ID public would be a good idea or not
An ID in of itself is pretty useless
You'd need atleast the client secret too to actually cause any harm.
umm yeah i suppose but would it be a good idea to share anyway?
and does discord have any official writing on this? i couldnt find 1 myself
It wouldn't matter much since like I said above you'd need both the ID and the client secret.
I cant add a discord users thumbnail to an embed
Error:
^^^^^^^^^^^^^^^^^
AttributeError: 'Member' object has no attribute 'avatar_url'```
My Code:
thumbnail_url = member.avatar_url if member.avatar else discord.Embed.Empty
embed = discord.Embed(
title='User Joined',
description=f'{member.mention} has joined the server.',
color=discord.Color.green()
)
embed.set_thumbnail(url=thumbnail_url)```
how do i add slash commands to my bot?
With discord.app_commands
You can watch videos from UwU channel, which explain well how to use them
user.avatar_url is very outdated and removed. Now it's user.avatar.url
thnak you
Can someone help me start and explain how to make a discord bot?
many youtube tutorials
Python.
Dms
Alr.
I am trying to do an anti fake account system
My Error: in on_member_join delta = (now - created).days ~~~~^~~~~~~~~ TypeError: can't subtract offset-naive and offset-aware datetimes
Code: ```py
@bot.event
async def on_member_join(member):
created = member.created_at
now = datetime.now()
delta = (now - created).days
if delta < 30:
antialtlogs = bot.get_channel(1221086723132358697)
alt = discord.Embed(timestamp=datetime.utcnow(), title=":name_badge: Ενα καινουργιος λογαργιασμος προσπαθησε να μπει στον The Society :name_badge:", colour = discord.Colour.red())
alt.add_field(name=":capital_abcd:User's name:", value=f"{member.name}")
alt.add_field(name=":watch:Creation date:", value=f"{member.created_at.strftime('%d %B %Y')}")
alt.add_field(name=":label:User's Account:", value=f"{member.mention}")
await antialtlogs.send(embed=alt)
Does somebody know how to fix it?
datetime.now(timezone.utc)
Unrelated to discord bots btw
Since installing Python is unrelated to Discord bots, it's a question for #python-discussion or #1035199133436354600
whats that
Stop spamming Discord's API, wait a few hours and fix whatever is spamming the API during that time
And that way of hiding the token is trash, better reset your token now
def send_embed_to_webhook(user_id, badge_id, badge_name):
embed = {
"title": RobloxAPIs.RobloxGetUsername(user_id),
"url": f"https://www.roblox.com/badges/{badge_id}/badge",
"description": f"{RobloxAPIs.RobloxGetUsername(user_id)} has earned the badge: {badge_name}",
"color": 0x00b0f4,
"timestamp": datetime.datetime.now(datetime.timezone.utc).isoformat(),
"image": {
"url": RobloxAPIs.RobloxGetBadgeImage(badge_id)
},
"thumbnail": {
"url": RobloxAPIs.RobloxGetUserProfileImage(user_id)
}
}
payload = {
"content": "||<@&1220868554669424651>||",
"embeds": [embed]
}
headers = {
'Content-Type': 'application/json'
}
response = requests.post(webhook_url, json=payload, headers=headers)
print(f"Webhook status code: {response.status_code}")
if response.status_code != 204:
print(f"Failed to send embed for user {user_id}. Status code:", response.status_code)
I'm trying to trigger a webhook when something changes on another website. Printing the data works fine, but when attempting to send the webhook, it doesn't go through, despite receiving a 204 status code any help would be appreciated
Why does my bot sometimes say The application did not respond and then throw an error with 404 Not Found?
It happens to all commands sometimes for no reason at all.
Traceback (most recent call last):
File "C:\Users\blaul\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\nextcord\application_command.py", line 918, in invoke_callback_with_hooks
await self(interaction, *args, **kwargs)
File "c:\Users\blaul\Desktop\admin helper\main.py", line 631, in help
await ctx.send(embed=embed)
File "C:\Users\blaul\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\nextcord\interactions.py", line 540, in send
return await self.response.send_message(
File "C:\Users\blaul\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\nextcord\interactions.py", line 896, in send_message
await adapter.create_interaction_response(
File "C:\Users\blaul\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\nextcord\webhook\async_.py", line 195, in request
raise NotFound(response, data)
nextcord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction
The above exception was the direct cause of the following exception:
nextcord.errors.ApplicationInvokeError: Command raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction
If you try to use the command again it works like it should but sometimes it just throws that error so is there some way to fix that?
i tried this and it seems to work perfectly fine
You need to respond within 3 seconds or the interaction will expire. Defer the interaction to avoid this
see it still works it just doesn’t work like half of the time like 1/3 of the time
🤔
how do you call a custom guild emoji in discord.py
so you need id of an emoji
then you use bot.get_emoji(id)
and what it returns, you pass it to .add_reaction()
wait how do you get an emoji id
you put \ before emoji in discord chat
then it outputs something like this !this
and the 470903994118832130 is the id
This is a python script of a Discord Bot I developed for my users, basically I am working on a Automation project on discord my ultimate goal is to develop discord bot which helps my client to perform auto operations like Auto Posting/Auto Comment ... without getting banned or suspend by discord , Insha-Allah soon this project will be completed I want your feed back guys related to this short video about code. Thanks
whats the permission called to remove the perms of someone using the everyone ping ?
!d discord.Permissions.mention_everyone
Returns True if a user’s @everyone or @here will mention everyone in the text channel.
thanks!
How to get message id from message link ?
this is the message link
267624335836053506 343944376055103488 1221412309164097626
those numbers are as follows:
guild id
channel id
message id
how to get the author of a person that created a channel?
from on_guild_channel_create event
!d discord.on_guild_channel_create
discord.on_guild_channel_delete(channel)``````py
discord.on_guild_channel_create(channel)```
Called whenever a guild channel is deleted or created.
Note that you can get the guild from [`guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.GuildChannel.guild).
This requires [`Intents.guilds`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.guilds) to be enabled.
!d discord.on_message
discord.on_message(message)```
Called when a [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message) is created and sent.
This requires [`Intents.messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.messages) to be enabled.
Warning
Your bot’s own messages and private messages are sent through this event. This can lead cases of ‘recursion’ depending on how your bot was programmed. If you want the bot to not reply to itself, consider checking the user IDs. Note that [`Bot`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot) does not have this problem.
!d discord.Message.guild
The guild that the message belongs to, if applicable.
how to get the author of a person that created a channel?
from on_guild_channel_create event

you would have to do that via audit logs there is not actual .author or .creator property
fetch the message and check the .guild property
most likely you will get Forbidden error cause bot will not be in the guild, then you know its not the guild you want
like i said, you check .guild property if it fetches
you can either hardcode the guild id you want it to be or check it from context
!d discord.Message.guild
The guild that the message belongs to, if applicable.
if something.guild is not None:
# do something :P
(probably)
How could I make a command only available to the owner of the guild
my bot is public]
so it is in many6 servers
i cant put an id
!d discord.Guild.owner_id
The guild owner’s ID. Use Guild.owner instead.
this is just an example
you wanna fetch by message_id not channel_id i belive thats just bad variable name
what about slash commands
if only you were to check the guide i linked
Look around the sections
ah i see
well you got channel out of nowhere
What could it be? 😼
show code
(which doesn't exist)
you need to get a channel
yea i know now xd

doesnt have to be a channel
yea
well if you are checking by channel
yes
is message.channel_mentions not suitable? based on the source code, it only returns channels/threads that are part of the message's guild (assuming they're already cached)
https://github.com/Rapptz/discord.py/blob/v2.3.2/discord/message.py#L1900-L1905
discord/message.py lines 1900 to 1905
@utils.cached_slot_property('_cs_channel_mentions')
def channel_mentions(self) -> List[Union[GuildChannel, Thread]]:
if self.guild is None:
return []
it = filter(None, map(self.guild._resolve_channel, self.raw_channel_mentions))
return utils._unique(it)```
in what cases can guild.owner return None?
according to source, it relies on .get_member() which requires the Member object to be cached
https://github.com/Rapptz/discord.py/blob/v2.3.2/discord/guild.py#L995-L998
discord/guild.py lines 995 to 998
@property
def owner(self) -> Optional[Member]:
"""Optional[:class:`Member`]: The member that owns the guild."""
return self.get_member(self.owner_id) # type: ignore```
ah, well its returning None everytime 😔
do you have Intents.members enabled? that's needed for dpy to automatically cache members
await fetch_member(member_id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member) from a guild ID, and a member ID.
Note
This method is an API call. If you have [`Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members) and member cache enabled, consider [`get_member()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.get_member) instead.
Changed in version 2.0: `member_id` parameter is now positional-only.
I've already requested once but they said "the feature isnt innovative enough"
and how do I get the ID of the guild owner since guild.owner is returning None
!d discord.Guild.owner_id
The guild owner’s ID. Use Guild.owner instead.
lol it just says "use guild.owner instead"
💀 little do they know
wait wouldnt the logic be same then? like that wont work either?
let me see
owner_id is always available since its part of the guild payload
oh gotcha
i wonder why dpy doesnt yet have try_* or getch_* methods, maybe its to reduce library bloat?
I'm using disnake which does have only getch_user
ah cool
i guess its not that hard to write your own helper functions to do the same thing, e.g. py async def try_member(guild: discord.Guild, id: int) -> discord.Member | None: return guild.get_member(id) or await guild.fetch_member(id)
that is true
it would actually always return a Member
o derp ye
Is it your intention to try to delete the message every loop?
even if the ID is invalid?
then it throws error
ah ok
None type
oh wait, you're trying to detect channel mentions that for the same guild?
in that case yeah you'll probably want to manually get the channel
!d discord.Message.raw_channel_mentions does the same regex stuff btw
A property that returns an array of channel IDs matched with the syntax of <#channel_id> in the message content.
i think you'll also want to consider matching channel links in the format https://discord.com/channels/GUILD_ID/CHANNEL_ID[/MESSAGE_ID] or similar
yeah you should check for both
if any(channel_id not in message.guild.channels for channel_id in message.channel_mentions):
await message.delete()
smt like that id say
yeah something like that, except with raw_channel_mentions so you get the channel IDs that dont exist in the guild
wdym by that
channel_mentions doesnt return external channels?
!d discord.Message.channel_mentions
A list of abc.GuildChannel or Thread that were mentioned. If the message is in a private message then the list is always empty.
according to source code, it doesnt (guild._resolve_channel() only checks its own channel cache, not the caches from other guilds)
please read
don't copy paste every code you see
if any(guild.get_channel(channel_id) is None for channel_id in message.raw_channel_mentions):
await message.delete()
or
yeah that would be it
cant think of a better way
guild.get_channel() is O(1) so you can use that instead
forgot discordpy caches every bit of data
well, you need to define the guild variable
or replace it with message.guild
doesnt redirect to nowhere
canary maybe?
not to be an asshole, but that's quite a simple python task to be fair
they already have a lot of mod tools, you're just asking something too specific
automod
you can somewhat delete adverts
but if you want extra mod tools, then code it yourself
it's a free platform that doesn't charge you, you really can't complain
if they had to implement every user edge case they would run out of money in less than a day
Discord moment
anyone created slack bots before?
This is a Discord bot channel. But probably
just ask
Though not here
What do you think about
invite_match = re.search(r"(?:https?://)?(?:[a-zA-Z0-9-]+\.)?(discord(?:app)?\.com|discord\.gg)/?(?:invite/)?([a-zA-Z0-9-]+)", message.content)```
import config
import discord
from discord.ext import commands
from discord import app_commands
import math
app = commands.Bot(command_prefix=".", intents= discord.Intents.all())
@app.event
async def on_ready():
print("hi")
try:
synced = await app.tree.sync()
print(f"sync{len(synced)} command")
except Exception as e:
print(e)
@app_commands.command(name="taschenrechnen", description="taschenrechner1")
@app_commands.choices(choices=[
app_commands.Choice(name="+", value="+"),
app_commands.Choice(name="-", value="-")
])
async def taschenrechner( i: discord.Interaction,zahl1: int, choices:app_commands.Choice[str],zahl2: int):
if choices.value == "+":
await i.response.send_message(zahl1 + zahl2)
elif choices.value == "-":
await i.response.send_message(zahl1 - zahl2)
app.run(config.token)```
why it dont sync my command
i have application commands on and all that
@app_commands.command() doesnt add your command to your tree, use @app.tree.command() instead
!d discord.app_commands.CommandTree.command
@command(*, name=..., description=..., nsfw=False, guild=..., guilds=..., auto_locale_strings=True, extras=...)```
A decorator that creates an application command from a regular function directly under this tree.
How do I call a command within a command using app_commands and cogs? I dont see 'invoke' as an option, I only see if for discord.ext.commands.Bot.invoke. In the discord api I do read there is a discord.app_commands.CommandInvokeError but for some reason not a discord.app_commands.Invoke .The sudo code I made is below. It prints out the print(command.name) without an issue just need the last line.
@app_commands.command(name = "test", description="Test")
async def test(self, interaction: discord.Interaction) -> None:
commands = self.get_app_commands()
for command in commands:
if command.name == 'roster':
print(command.name)
await self.invoke(command.name)
I don't think bots can invoke app commands
you could manually call the function through command.callback, but i would prefer to refactor the command into a function that you can reuse in other commands
just wondering if a command ive made is breach of TOS,
@commands.command(name="nuke", description="Nukes the channel command was used in.")
@has_permissions(manage_channels=True)
@commands.cooldown(1, 30, commands.BucketType.guild)
async def nuke(self, ctx):
newchannel = await ctx.channel.clone()
await newchannel.edit(position=ctx.channel.position)
await ctx.channel.delete()
await newchannel.send(f"Channel nuked by `{ctx.author.name}`.")```
If someone were to invite the bot to nuke their own server, I guess not 🥴
Thumbnail Previously Showing, but within the last week disappeared with no code changes
Python Version: 3.8.10
Here is my Python code that previously was showing the Thumbnail with the rest of the embed fields, haven't made any code changes since the last time it was implemented in my discord bot.
set_headshot = f"https://aaa.com/headshots/aaa/latest/1040x760/{player_id}.png" # URL Redacted
print(set_headshot)
embed = discord.Embed(title=f"{player_name} - Season Stats ({season})", color=0x4286f4)
current_time = dt.now().strftime('%Y-%m-%d %H:%M:%S')
embed.set_thumbnail(url=set_headshot)
embed.set_footer(text=f"Made by Fire, the Lit Mage • Timestamp: {current_time}", icon_url="https://s3-us-west-2.amazonaws.com/sportshub2-uploads-prod/files/sites/556/2022/11/17094810/basketball-gif-6.gif")
for stat, value in relevant_stats.items():
embed.add_field(name=stat, value=value, inline=True)
# Create a view with interactable buttons
view = discord.ui.View(timeout=None)
prizepick_button = discord.ui.Button(style=discord.ButtonStyle.green, label="PrizePick Bets", custom_id=f"{player_id}_ppbets_{re.sub(r' ','$$',player_name)}")
prizepick_button.callback = prizepick_click
view.add_item(prizepick_button)
processing_in_progress = False
await ctx.send(embed=embed, view=view)```
When I print the url of where the image is and I manually go there it loads the image I am expecting to see as the thumbnail that was previously there. My only assumption is that some new restriction was added into the discord.py package where if I have too many embed fields or something else it restricts the thumbnail coming through. Now when I open dev tools inside Discord it doesn't even show the Thumbnail content within the embed when searching for it. The total embed fields that I am adding into the embed is 22 fields.
import discord
from discord.ext import commands
from discord import app_commands
import sqlite3
conn = sqlite3.connect('database.db')
c = conn.cursor()
class reactionrole(commands.Cog):
def __init__(self, bot):
self.bot = bot
@app_commands.command()
async def reactionroleadd(interaction: discord.Interaction, role: discord.Role, emoji: str , message_id: str):
await interaction.response.send_message("hi")
c.execute("INSERT INTO reactionaldb VALUES (?,?,?)",(message_id,str(role.id),emoji))
conn.commit()
conn.close()
You forgot the self argument
Damm
How can a make a error handler for this
async def is_owner(inter: discord.Interaction) -> bool:
if inter.user.id == inter.guild.owner.id:
return True
else:
await inter.response.send_message("You need to be the owner to use this command", ephemeral=True)
When check returns False
CheckFailed error is raised
And you Can handle it as any other error in error handler
Show the error
2024-03-25 07:39:57 ERROR asyncio Task exception was never retrieved
future: <Task finished name='CommandTree-invoker' coro=<CommandTree._from_interaction.<locals>.wrapper() done, defined at /Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/app_commands/tree.py:1087> exception=AttributeError("'NoneType' object has no attribute 'id'")>
Traceback (most recent call last):
File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/app_commands/tree.py", line 1089, in wrapper
await self._call(interaction)
File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/app_commands/tree.py", line 1248, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/app_commands/commands.py", line 849, in _invoke_with_namespace
if not await self._check_can_run(interaction):
File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/app_commands/commands.py", line 987, in _check_can_run
return await async_all(f(interaction) for f in predicates)
File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/utils.py", line 705, in async_all
elem = await elem
File "/Users/zagzag/Library/Mobile Documents/com~apple~CloudDocs/zagzag/zagzag.py", line 460, in is_owner
if inter.user.id == inter.guild.owner.id:
AttributeError: 'NoneType' object has no attribute 'id'
this raises if the user is not an owner
if it is the owner
it works
Use owner_id instead
guild.owner_id?
Ye
ok
this matches literally any discord link
https://discord.com/balls lmao
@client.event
async def on_member_join(member):
channel = client.get_channel(welcome_channel)
embed = discord.Embed(
description=f'Welcome to the official GAM3 discord server **{member.mention}**!',
color=0x000000,
timestamp=datetime.datetime.now(),
)
await channel.send(embed=embed)
how can i add it to also auto role? I tried
role = discord.utils.get(member.guild.roles, name='Role Name')
await member.add_roles(role
but it gives me an error
which error does it raise?
Traceback (most recent call last):
File "C:\Users\c0d3\Desktop\gam3-discord_bot\bot-venv\Lib\site-packages\discord\client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "c:\Users\c0d3\Desktop\gam3-discord_bot\main.py", line 26, in on_member_join
await member.add_roles(role)
File "C:\Users\c0d3\Desktop\gam3-discord_bot\bot-venv\Lib\site-packages\discord\member.py", line 1051, in add_roles
await req(guild_id, user_id, role.id, reason=reason)
^^^^^^^
AttributeError: 'NoneType' object has no attribute 'id'```
role = discord.utils.get(member.guild.roles, name='Role Name')
await member.add_roles(role)``` was it directly in your code like this?
@client.event
async def on_member_join(member):
channel = client.get_channel(welcome_channel)
embed = discord.Embed(
description=f'Welcome to the official GAM3 discord server **{member.mention}**!',
color=0x000000,
timestamp=datetime.datetime.now(),
)
role = discord.utils.get(member.guild.roles, name='Member
')
await member.add_roles(role)
await channel.send(embed=embed)
else, you can use something like: py role = member.guild.get_role(#roleid)
Traceback (most recent call last):
File "C:\Users\c0d3\Desktop\gam3-discord_bot\bot-venv\Lib\site-packages\discord\client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "c:\Users\c0d3\Desktop\gam3-discord_bot\main.py", line 26, in on_member_join
await member.add_roles(role)
File "C:\Users\c0d3\Desktop\gam3-discord_bot\bot-venv\Lib\site-packages\discord\member.py", line 1051, in add_roles
await req(guild_id, user_id, role.id, reason=reason)
File "C:\Users\c0d3\Desktop\gam3-discord_bot\bot-venv\Lib\site-packages\discord\http.py", line 739, in request
raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
its role has admin
You cannot edit the roles of the members with higher role hierarchy
so i need to add that perm?
What permission?

Maybe I wasn't clear
Just move one of the bot's role to a very high position
ohhh
Unless you're testing the bot on yourself as the guild owner or something
That probably won't work, though I didn't test anything roles related for a long time
nono i have test alt
Oh nice
You actually can 😏 but you can't give/take roles that are higher or equal to your top role
can I monetize a discord bot?
I coded one back in 2020 & haven't touched Python ever since
i guess?
What are the benefits of coding one apart from enjoyment?
see some famous bots like mee6, draftbot or dyno can be monetized
usage
yeah discord has built in stuff for monetization now
im trying to display a ticket count in the ticket name but it keeps saying that count is None even tho ive set its defualt value to 1 in the databse
cur.execute(f"SELECT * FROM ticket_count")
y = cur.fetchone()```
client.get_user(494483880410349595) returning None, its my own userid
ticket closing button doesnt work, if i restart the bot it works once but on the next ticket i get that error
where are you doing this
.get_ methods are cache lookups so it'll return None if the cache isn't populated
makes sense, i am doing it after bot starts, it sends an embed and i want to include the avatar of this user
can you show your code
any ideas?
there is no attribute pool for the bot object
are u sure u don't have multiple instances of bot or some instances you are sourcing from other files or modules
might wanna check if the pool has been set in the first place
emb=discord.Embed(title=item_name, url=item_url, description=f"# {price}\nPosted: {time_posted}\nSeller: [{seller_name}]({seller_url})\nCondition: {condition}", color=0x00ff00)
# emb.set_author(name=client.get_user(494483880410349595).name, icon_url=client.get_user(494483880410349595).display_avatar)
emb.set_author(name="speckly")
emb.set_footer(text=catFact)
emb.set_image(url=item_img)
if interaction:
await interaction.followup.send_message(catFact)
else:
CHANNEL = client.get_channel(channel_id)
await CHANNEL.send(embed=emb)
the last line here also throws this
raise RuntimeError(
RuntimeError: Timeout context manager should be used inside a task
for context, the above is cb callback of another thread, the callback contains some blocking code such as using a webdriver
task = QueryThread(target=asyncio.run, args=[client.cb(delay, item, interaction.channel_id)], name=item, cid=cid)
task.start()
wait what exactly is this supposed to do
sends a message every x amount of seconds
and please for the love of god do this instead of whatever i just had to read ```py
emb = discord.Embed(
title = ...,
description = ...,
...
)
can you show me the whole command code?
or is this a loop?
like show me the surrounding code
# this line
await ctx.send(embed = embed)
# is surrounded by
@bot.command(name = 'embed')
async def send_embed(ctx):
embed = discord.Embed(
description = "this is an embed",
color = discord.Color.green()
)
await ctx.send(embed = embed)
await asyncio.sleep(5)
await ctx.send("Waited 5 seconds after sending the embed. :+1:")```
i am outside so i only have this for now, the command is create_thread
lovely pfp btw
alr i'll take a look
thanks
also something to mention: use commands.Bot instead of discord.Client
lemme find it
do i just replace that in the subclass?
i think so
but dont change anything yet
worried things will break yeah
it wont magically solve the problem
remind me the issue again, because i replied to the cat fact code and ended up in a create_thread func 😭
oh dont look at cat_fact and its callback, they were tests
the issue was that create_thread works but at the very end when the message is going to be sent whether it is interaction response or channel.send it raises this
have you responded to the reaction before?
i tried using the same event loop with another async thread function, which is probably old practice, but it blocks all incoming commands, the messages do send fine
ie. have you done something like this? py await interaction.response.defer() await interaction.response.send_message(...)
(they can be any .response.)
ooh defer sounds useful actually but its not the issue i think, im mostly using channel.send()
ah ok, whats channel?
like where are you getting it from
because if you are going to use interactions you should probably just use .send_message
client.get_channel(channel_id)
dont bother
use interactions instead
await interaction.response.send_message(embed = emb)```
try that and let me know how it goes
how did it go
I know it's something related to commas where do I have put the comma
@viscid hornet sorry for ping :>
hellooo
... WHERE message_id == ? AND role_id
Did you forget the == ? for role_id?
I'm very confused about the variables
whats the code
hi i just got home, no
await interaction.followup.send(embed=emb)
raise RuntimeError(
RuntimeError: Timeout context manager should be used inside a task
wheres the runtime error being raised from
show full traceback
File "C:\Users\Dell\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 1038, in _bootstrap_inner
self.run()
File "C:\Users\Dell\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 975, in run
self._target(*self._args, **self._kwargs)
File "C:\Users\Dell\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 190, in run
return runner.run(main)
^^^^^^^^^^^^^^^^
File "C:\Users\Dell\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 118, in run
return self._loop.run_until_complete(task)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Dell\AppData\Local\Programs\Python\Python311\Lib\asyncio\base_events.py", line 653, in run_until_complete
return future.result()
^^^^^^^^^^^^^^^
File "C:\Users\Dell\OD\Documents\compooting\Kurokami\bot.py", line 42, in cb
await query_cb(item_name, interaction)
File "C:\Users\Dell\OD\Documents\compooting\Kurokami\bot.py", line 128, in query_cb
await interaction.followup.send(embed=emb)
File "C:\Users\Dell\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\webhook\async_.py", line 1805, in send
data = await adapter.execute_webhook(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Dell\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\webhook\async_.py", line 177, in request
async with session.request(
File "C:\Users\Dell\AppData\Local\Programs\Python\Python311\Lib\site-packages\aiohttp\client.py", line 1141, in __aenter__
self._resp = await self._coro
^^^^^^^^^^^^^^^^
File "C:\Users\Dell\AppData\Local\Programs\Python\Python311\Lib\site-packages\aiohttp\client.py", line 467, in _request
with timer:
File "C:\Users\Dell\AppData\Local\Programs\Python\Python311\Lib\site-packages\aiohttp\helpers.py", line 701, in __enter__
raise RuntimeError(
RuntimeError: Timeout context manager should be used inside a task
so this line is the error py await interaction.followup.send(embed=emb)
wait wtf
try .response.send_message(...)
instead
wont that work only once
how many times are you going to send this
many many many many many many many many many many times, in fact i am worried that the interaction will expire
while True:
s = time.time()
await query_cb(item_name, interaction)
print(f"{threading.current_thread().name}, time taken: {time.time() - s}")
await asyncio.sleep(delay)
until thread gets stopped
😭
why not add it to like a list of items and then show a progress bar instead?
that might be a good idea
ngl i feel like i bit off more than i can chew
make a help thread there and list your issue
im sorry but i cant help 😭
sorry for wasting your time ❤️
i was literally writing tasks code as we were speaking
"no me, not you" - dpy to threading
this error
@commands.command(name="reload", hidden=True)
async def reload(self, ctx, *, cog: str = None):
"""Reload a cog."""
if cog is None:
await ctx.send("Please specify a cog to reload or 'all' to reload all cogs.")
return
if cog.lower() == "all":
for extension in self.client.extensions:
try:
await self.client.reload_extension(extension)
await ctx.send(f"Cog `{extension}` reloaded successfully.")
except commands.ExtensionError as e:
await ctx.send(f"Failed to reload cog `{extension}`: {e}")
else:
try:
await self.client.reload_extension(cog)
await ctx.send(f"Cog `{cog}` reloaded successfully.")
except commands.ExtensionError as e:
await ctx.send(f"Failed to reload cog `{cog}`: {e}")
You need to have the extension already loaded before reloading it 🫠
i did load them while starting the bot
this cmds used to work before idk what happen today
i m using setup hook
to load them
I don't think the error would lie to you
why do u think i m lieing to u
async def setup_hook(self):
for file in EXTENSIONS:
await self.load_extension(file)
print(file, "activated!")
here it is i loaded them
I said the error, but alright
EXTENSIONS = [
"cogs.events",
"cogs.tools",
"cogs.moderation",
"cogs.owner",
"cogs.fun",
"cogs.General",
"cogs.tech_news",
"cogs.utility",
]
ye but i m not understanding
it says cogsa arent loaded but i did load them
while running the bot
do they mean to be loaded again?
the more interesting thing is
i can use all thoes cmds in owner.py
and when i try to reload the cogs it says its not loaded
then how tf m i even using thoes all cmds?
@vapid parcel
@sturdy fractal
else:
try:
await self.client.reload_extension(cog)
await ctx.send(f"Cog `{cog}` reloaded successfully.")
except commands.ExtensionError as e:
await ctx.send(f"Failed to reload cog `{cog}`: {e}")```
you need to reload "cogs.{cog}" instead of just cog
so
await self.client.reload_extension(f"cogs.{cog}")
or u can just do !!reload cogs.owner too
i have install ffmpeg and path it but i still get this err here:https://srcb.in/EsAAHMCH90
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\player.py", line 183, in _spawn_process
raise ClientException(executable + ' was not found.') from None
discord.errors.ClientException: ffmpeg was not found.?[0m
oo this way
lemme try it
idk how it was working back yesterday
help here
Does anyone know how to make my bot send a message to a user when a message reaches 3 reactions?
Worked?
i tried this and the messages send just fine now, but these looping tasks block commands, one of the tasks is this line which takes about 40 seconds to complete, during these 40 seconds, all commands are blocked and are executed only after this function returns (and dont work because interaction expired)
new_results = await kurokami.main({"i": item_name, "p": 1, "o": new_filename, "t": False, "s": False, "c": last_file_path})
class Query():
def __init__(self, name, cid, delay: float):
self.name = name
self.channel = cid
self.delay = delay
@tasks.loop(seconds=120) # BUG: Should be self.delay
async def cb(self):
s = time.time()
await self.query_cb()
print(f"{self.name}, time taken: {time.time() - s}")
thread = Query(name=item, cid=cid, delay=delay)
thread.cb.start()
yes thx u
yeah because ure still using threads no?
tasks are async functions and don't block
not using threads anymore, using only 1 main thread
then i wonder why blocking is occuring
Hii I'm a beginner here
embed=discord.Embed (title="Sample Embed",
discord.Embed.set_author(name=user.name)
description="Hello world", color=0xFF5733)
await interaction.response.send_message(embed=embed)```
can anyone tell me how to set the author name as the one who excuted the command
name=interaction.user.name
oh, how to set the pfp of the person too, in icon_url
it tells me that it is an invalid syntax
honestly don't know much about threading, sorry
set_author is a method of discord.Embed so you should have one line for creating embed and another calling this method
ss the code and send
embed=discord.Embed(title="Sample Embed",
description="Hello world",
color=0xFF5733)
embed.set_author(name=interaction.user.name)
icon_url=interaction.user.display_avatar
what library is that?
set_author(name=interaction.user.name, icon_url=interaction.user.display_avatar)
no I'm talking about the code sent by @hot sparrow
oh
my own
if I'm not wrong, display_avatar was changed in dpy 2.0
its a web scraper with selenium
so you're not using dpy?
yes the discord api wrapper ure using
i tried this but it still doesnt work
discord.py==2.3.2```
no sorry it works

how to set the colour of the embed with a desired hex code?
other hex codes rather than discord's own available colours
yes alright
isnt it right in front of you
color=0xFF5733
this can be changed to any 24 bit hex
okay thank you
help !!
is there anything wrong with this?
embed=discord.Embed (title="Sample Embed",
embed.set_author(name=interaction.user.name, icon_url=interaction.user.display_avatar)
description="Hello world",
color=0xFF5733)
await interaction.response.send_message(embed=embed)```
Why is there a embed.set_author in the embed constructor
i have install ffmpeg and path it but i still get this err here:https://srcb.in/EsAAHMCH90
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\player.py", line 183, in _spawn_process
raise ClientException(executable + ' was not found.') from None
discord.errors.ClientException: ffmpeg was not found.?[0m
wait you can make embeds like that?
No
async def embed
Hmmmm
I thought I was tweakin
You want make a function that creates an embed?
no not me
yo anyone got any clue why i have to await my with opens lmao ?
@bot.command()
async def download(ctx, url):
r = requests.get(url)
filename = url.split("/")[-1]
try:
with open(filename, "wb") as f:
f.write(r.content)
pass
await ctx.send(f"File '{filename}' downloaded successfully.")
except FileNotFoundError:
await ctx.send(f"File '{filename}' not found.")
except Exception as e:
await ctx.send(f"An error occurred while downloading '{filename}': {e}")
i dont see you awaiting any with open
oop sorry completely forgot to send my error:
C:\Users\notsl\Desktop\rat\main.py:352: RuntimeWarning: coroutine 'Command.__call__' was never awaited
with open(filename, "wb") as f:
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
so would awaiting it fix my issue ?
most likely you have a command named open
oh fuck me
which is overriding the open function
youre right
ive been confused for literally so long
tysm lmao i feel so stupid 🙏
if you want to keep the name you can use name="open" inside decorator
and change the function name
Where can I host a bot 24/7 for free? Like on which platform?
your computer
The user runs a command called !host.
The bot then ask for information. How do you store the user input and use it in the code?
what type of information?
E.g.
User does !host
Bot: Event Number:
User answers: 1222
Bot: Date
User answers: 20/03/2024
Smth like that.
i would use a database
In the end both posts in a channel:
Ladies and gentlemen,
User is hosting an event on date at time.
oh like that?
Yh
ok one second
The channel it posts is different to where the user uses command.
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix='>', intents=discord.Intents.all())
@bot.command()
async def host(ctx, eventnumber, date):
eventchan = ctx.get_channel(1234567890) # your channel id
await eventchan.send(f'Ladies and gentlemen,\n**{ctx.author.name}** is hosting and event on {date}')
thats how i would do it
Alright, next question.
go on
So here is a message the bot posts in a channel:
Ladies and Gentlemen,
React to which you can attend.
The bot should auto add reactions 1,2,3,4,5,6 etc
And then if a user reacts
It should add them to the sheet behind the number
So if I reacted to one
Ladies and Gentlemen,
React to which you can attend.
- @thorn beacon
That's how it should look like
Same for unreacting.
that would have to be used as a @bot.event
A user first does !schedule command
i havent coded a discord bot in a while so i would have no idea how to any of that unless i went and looked at an old bot
Ah alr. Would you be able to check an old bot?
Not many are experienced in this.
i mean im about to make one soon so i could
So my options for help are limited.
it would be a hot second though
Alr
this is actually kinda complicated, when do you need this bot by?
I have a bot, just this functionality is needed and the command.
Probs by like 5 days time or so.
by when?
ok can i get back to you in two days or so? im kinda busy tomorrow, so it will either be tonight or then
ok accept my friend request and can you invite me to a server with the bot?
Sure.
thanks!
is it gine to still be using @commands.hybrid_command in 2024?
yes?
I maked my discord bot and it's not replying in server. I made 2 commands and 1 trigger, trigger is working but commands not and trigger was working on dm only
Give me solution plz
!msg 1145245248247836713 hi it isnt working
can anyone help?
async def msg(ctx, user_id: int, *, message: str):
print("Command triggered.")
print("User ID:", user_id)
print("Message:", message)
try:
user = await bot.fetch_user(user_id)
print("User:", user)
if user:
embed = discord.Embed(title="New Message", description=message, color=0xffcc00)
embed.set_author(name=ctx.author.display_name, icon_url=ctx.author.avatar_url)
await user.send(embed=embed)
await ctx.send(f"📬 Message sent to **{user.display_name}** successfully!")
else:
await ctx.send("❌ User not found!")
except discord.Forbidden:
await ctx.send("❌ Unable to send message to the user!")```
What about it isn't working? Please be more specific
it isnt responding
Do you have an error handler or logging setup?
nope
can u fix it
I can't fix anything if I don't know what even is the problem
u may try it
use buttons
reactions are outdated af anyway
Bold claim
if you want hybrid commands, yeah
for things like what they're suggesting, yes they're outdated
why would you want like 5 reaction checks when you can just have a view with 5 buttons and add some logic so people can't pick the same spot
it's get_user and not fetch_user
You can add reactions and process them dynamically
Not just hard code them. But yeah, buttons are probably the easier way anyway
How would that work to my need?
quoted from R. Danny (dpy's discord bot):
"These are official examples for button from the repository. Note that buttons is only available in discord.py v2.0.
Confirm Prompt: https://github.com/Rapptz/discord.py/blob/master/examples/views/confirm.py
Counter: https://github.com/Rapptz/discord.py/blob/master/examples/views/counter.py
Ephemeral Messages: https://github.com/Rapptz/discord.py/blob/master/examples/views/ephemeral.py
Link Button: https://github.com/Rapptz/discord.py/blob/master/examples/views/link.py
Tic Tac Toe: https://github.com/Rapptz/discord.py/blob/master/examples/views/tic_tac_toe.py"
the gist is you have a view and then add things to that view called items
i say items because you can have a range of things, like select menus, buttons and more
check out the links and lmk if you need extra help
enable it in developer portal
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
im so good
!intents
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.
There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.
Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.
(in the code also :P)
damn ty
Why did bro ping me 😭
4fun

how many rules can a discord bot add for automod for a server?
!d discord.Message.embeds
A list of embeds the message has. If Intents.message_content is not enabled this will always be an empty list unless the bot is mentioned or the message is a direct message.
# Check embeds for the star symbol
for embed in message.embeds:
if '★' in embed.description or '★' in embed.title:
await message.channel.send('yooo!')
for field in embed.fields:
if '★' in field.name or '★' in field.value:
await message.channel.send('yooo!')
await bot.process_commands(message)
What's the error here
any errors?
if so send that first
i made a response to normal and embed message but bot not responding to embed but responding to normal text
import discord
from discord.ext import commands
intents = discord.Intents.all()
bot = commands.Bot(command_prefix='', intents=intents)
@bot.event
async def on_ready():
print('Logged in as {0.user}'.format(bot))
@bot.event
async def on_message(message):
if '★' in message.content:
await message.channel.send('yooo!')
for embed in message.embeds:
if '★' in embed.title or '★' in embed.description:
await message.channel.send('yooo!')
for field in embed.fields:
if '★' in field.name or '★' in field.value:
await message.channel.send('yooo!')
await bot.process_commands(message)
bot.run('your_token_here')
why bot not responding to embed text
can u show what the embed looks like?
using carl bot /embed
and in description sending ★
do u have message intent enabled in dev portal?
its responding to normal message so obviously it's enabled
whats the prefix?
u put an empty string there
no need of prefix it need to check if embed has start on it or not
ik, but have u tested it by using a prefixed cmd?
did u try removing that last line? bot.process_commands()?
hm, add if message.embeds: then indent the for loop and other things, thats better practice
also does the bot have neccessary perms in that channel ?
i changed code but still not responding to embeds
it is responding to normal text tho
import discord
from discord.ext import commands
intents = discord.Intents.all()
bot = commands.Bot(command_prefix='', intents=intents)
@bot.event
async def on_ready():
print('Logged in as {0.user}'.format(bot))
@bot.event
async def on_message(message):
if '★' in message.content:
await message.channel.send('yooo!')
if message.embeds:
for embed in message.embeds:
if '★' in embed.title or '★' in embed.description:
await message.channel.send('yooo!')
for field in embed.fields:
if '★' in field.name or '★' in field.value:
await message.channel.send('yooo!')
await bot.process_commands(message)
bot.run('your_token_here')
he has admin perms
can u send ss of how the embed looks
the star is in the title or the field?
title
are u sure its not set_author?
wait 1 sec let me check
!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.
There i put 1 in footer and dec
but not responding
its responding to normal text tho
the code looks fine
try printing things in between to check
like this ```py
if message.embeds:
print("Embeds found")
[30;1m2024-03-27 15:35:29[0m [34;1mINFO [0m [35mdiscord.client[0m logging in using static token
[30;1m2024-03-27 15:35:31[0m [34;1mINFO [0m [35mdiscord.gateway[0m Shard ID None has connected to Gateway (Session ID: 790b1b74a2d28cebd65e4b333a492522).
Logged in as Lucario.#4360
Received message:
Received message: ★
Star symbol found in message content
Received message: yooo!
[30;1m2024-03-27 15:36:34[0m [31mERROR [0m [35mdiscord.ext.commands.bot[0m Ignoring exception in command None
[31mdiscord.ext.commands.errors.CommandNotFound: Command "★" is not found[0m```
so its not detecting embeds?
does it print "embeds found" like the msg i prev sent
import discord
from discord.ext import commands
intents = discord.Intents.all()
bot = commands.Bot(command_prefix='', intents=intents)
@bot.event
async def on_ready():
print('Logged in as {0.user}'.format(bot))
@bot.event
async def on_message(message):
print('Received message:', message.content)
if '★' in message.content:
print('Star symbol found in message content')
await message.channel.send('yooo!')
if message.embeds:
print('Embeds found in message')
for embed in message.embeds:
print('Checking embed:', embed.title)
if '★' in embed.title or '★' in embed.description:
print('Star symbol found in embed title or description')
await message.channel.send('yooo!')
for field in embed.fields:
if '★' in field.name or '★' in field.value:
print('Star symbol found in embed field:', field.name)
await message.channel.send('yooo!')
await bot.process_commands(message)
bot.run('your_token_here')
hm
try changing ur intente ```py
intents = discord.Intents.default()
intents.messages = True
bot = commands.Bot(command_prefix='', intents=intents)
after login it has a message received as null look up
no intent for embed?
no
Ok let me try
!d discord.Intents
class discord.Intents(value=0, **kwargs)```
Wraps up a Discord gateway intent flag.
Similar to [`Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions), the properties provided are two way. You can set and retrieve individual bits using the properties as if they were regular bools.
To construct an object you can pass keyword arguments denoting the flags to enable or disable.
This is used to disable certain gateway features that are unnecessary to run your bot. To make use of this, it is passed to the `intents` keyword argument of [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client).
New in version 1.5.
bot responding / detecting nothing
@app_commands.describe(flight_number = "Enter number after AA.", departure = "Departure Airport.", date = "Enter Date.", time = "Enter Time.", aircraft = "Enter Aircraft.", arrival = "Enter Arrival.", gate = "Enter Gate.")
async def boards(interaction: discord.Interaction, flight_number: str, departure: str, date: str, time: str, aircraft: str, arrival: str, gate: str):```
Whats wrong here?
Well, what's wrong with it?
Did you sync the tree?
A hands-on guide to Discord.py
@commands.is_owner()
async def sync(ctx: commands.Context) -> None:
"""Sync commands"""
synced = await ctx.bot.tree.sync()
await ctx.send(f"Synced {len(synced)} commands globally")
@bot.tree.command(name="boards", description="The bot to manage flight schedules.")
@app_commands.describe(flight_number = "Enter number after AA.", departure = "Departure Airport.", date = "Enter Date.", time = "Enter Time.", aircraft = "Enter Aircraft.", arrival = "Enter Arrival.", gate = "Enter Gate.")```
Like this? @naive briar
Sure
What doesn't work? Please be specific
The /boards
When searching the slash cmd in discord.
do u get the message synced x commands globally?
if so u might wanna close and restart discord if it still doesn't show up
It works now thanks. I have another issue though.
My goal is to open a channel when a user does /boards and then post the buttons there
So I did.
async def dep(interaction:discord.Interaction)
guild = interaction.guild
channel = guild.create_channel etc.
How do I send messages in this new channel via bots?
how can i make a discord bot use my live audio and stream it
why isnt it editing the embed?
someone know how to update this list of commands?
i've tried await client.tree.sync() but it did not changed anything
^^
channel = await guild.create_text_channel(f"{interaction.user.name}-flight", category = category, overwrites = overwrites)
Why does an error pop up?
The target variable is None. And None has no attribute named id 🫠
discord/guild.py lines 1238 to 1243
for target, perm in overwrites.items():
if not isinstance(perm, PermissionOverwrite):
raise TypeError(f'Expected PermissionOverwrite received {perm.__class__.__name__}')
allow, deny = perm.pair()
payload = {'allow': allow.value, 'deny': deny.value, 'id': target.id}```
looks like your overwrites contains None value
Ah
sorry, but idk if I got it
turning discord off and then turning it on again
ooooh got it
guys, i'm kinda old, why people are using interaction: discord.Interaction with await interaction.response.send_message()
instead await ctx.send?
for slash commands, discord.py/disnake/nextcord/py-cord all do it slightly differently, and the former is mostly associated with dpy slash commands
interactions allow you (with other things) to answer commands with ephemeral messages (blue and only visible by you)
their similarities/differences are a result of dpy getting forked at around the time where 2.0 alpha only had interactions for message components (buttons and selects) before it was temporarily discontinued
hello
I need help with python
I can make an OOP system using different file to create a discord bot?
@hushed galleon
you can use cogs
like every commands has it owns class?
no, but you can group commands in cogs
if you want, you can create a cog for every command but that's really useless
example
like i have balance, balance has many commands, like addbalance, removebalance, balance ect...
import discord
from discord.ext import commands
class Ticket(commands.Cog):
def __init__(self, client):
self.client = client
@app_commands.command(name = "open")
async def open_ticket_command(self, interaction):
await interaction.guild.create_text_channel(name = f"ticket-{interaction.user.name}")
await interaction.response.send_message("ticket created", ephemeral = True)
async def setup(client):
await client.add_cog(Ticket(client))```
short example
@sharp dome
okay so I can make like
Balance(commands.Cog):
def __init__(self, client, user_data_manager: UserDataManager):
pass
# addbalance
# removebalance
# balance
this is like only for understanding it
alr
on the "on_ready"??
yeah
love yu
👍
Whats wrong in following code:
,"2️⃣":{"role_id":1200803662268743770, "limit":1}
,"3️⃣":{"role_id":1200803740660277318, "limit":1}
,"4️⃣":{"role_id":1200803835359264788, "limit":1}
,"5️⃣":{"role_id":1200804092394622976, "limit":4}
,"6️⃣":{"role_id":1200804194748223521, "limit":1}
,"7️⃣":{"role_id":1200804273982820423, "limit":2}}
reaction_counts = {emoji:0 for emoji in emojis_roles.keys}
for emoji in emojis_roles.keys():
await reaction.add_reaction(emoji)
@bot.event
async def on_reaction_add(reaction, user):
emoji = reaction.emoji
if emoji in emojis_roles:
role_id = emojis_roles["role_id"]
role = discord.utils.get(user.guild.roles, id=role_id)
if role:
if role not in user.roles:
limit = emojis_roles[emoji]["limit"]
if reaction_counts[emoji] >= limit:
await reaction.remove(user)
else:
reaction_counts[emoji] += 1
@bot.event
async def on_reaction_remove(reaction, user):
emoji = reaction.emoji
if emoji in emojis_roles:
reaction_counts -= 1```
My goal is for the bot to add reaction to a message in the channel.
Only users with the role for each emoji, can react. The limit is also set. But the error shows up. Let me capture it rq.
help
Added None cog,
@bot.event
async def on_ready():
print(f"Logged in as {bot.user}")
try:
cog = await bot.add_cog(AddBalance(bot, user_data_manager))
print(f"Added {cog} cog")
except Exception as e:
print(f"Failed to add AddBalance cog: {e}")
try:
synced = await bot.tree.sync()
print(f"Synced {synced} commands")
except Exception as e:
print(f"Failed to sync commands: {e}")
class Balance(commands.Cog):
def __init__(self, bot, user_data_manager: user_data.UserDataManager):
self.bot = bot
self.user_data_manager = user_data_manager
@commands.command(
name="add_balance",
description="Add balance to a user",
)
async def add_balance(self):
what did i do wrong?
import discord
from discord.ext import commands
Can someone help me? I want to set a limit of users as well as a role restriction per emoji. Of one of those requirements fail, it removed the users reaction from the message.
,"2️⃣":{"role_id":1200803662268743770, "limit":1}
,"3️⃣":{"role_id":1200803740660277318, "limit":1}
,"4️⃣":{"role_id":1200803835359264788, "limit":1}
,"5️⃣":{"role_id":1200804092394622976, "limit":4}
,"6️⃣":{"role_id":1200804194748223521, "limit":1}
,"7️⃣":{"role_id":1200804273982820423, "limit":2}}
reaction_counts = {emoji:0 for emoji in emojis_roles.keys()}```
What I have so far.
This adds the reaction to the message.
@vestal acorn @hushed galleon help my bestie out
The cmds don't bother me rn.
what you talking about?, i need help with my bot xd
Oh
Still not solved.
a long long time...
just use if statements
!d discord.on_reaction_add
discord.on_reaction_add(reaction, user)```
Called when a message has a reaction added to it. Similar to [`on_message_edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_message_edit), if the message is not found in the internal message cache, then this event will not be called. Consider using [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_raw_reaction_add) instead.
Note
To get the [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message) being reacted, access it via [`Reaction.message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Reaction.message).
This requires [`Intents.reactions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.reactions) to be enabled.
Note
This doesn’t require [`Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members) within a guild context, but due to Discord not providing updated user information in a direct message it’s required for direct messages to receive this event. Consider using [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_raw_reaction_add) if you need this and do not otherwise want to enable the members intent.
Hello everyone, I have a problem with the Python ticket bot and I would like to add it to VPS Ubuntu so that it works in the background. Can anyone help me?
Using Pycord, is there any way to use async with typing() during any bridge command?
@app_commands.command()
async def reactionroleadd(self,interaction: discord.Interaction, role: discord.Role, emoji: str , message_id: str):
c.execute("INSERT INTO reactionaldb VALUES (?,?,?)",(message_id,str(role.id),emoji))
conn.commit()
await interaction.response.send_message("done",ephemeral=True)```
I want the bot to react with the emoji to the message whose id is taken
you can just use a process manager like systemd, create a service, enable it, then start it, could do something like ```ini
[Unit]
Description=Your Bot Name
After=network-online.target
[Service]
Type=simple
WorkingDirectory=/dir/to/your/bot/path
ExecStartPre=source /dir/to/your/bot/path/.venv/bin/activate # assuming you use venv
ExecStart=python /dir/to/your/bot/path/main.py
User=your-user
Restart=always
[Install]
WantedBy=multi-user.target
anyone have a working twitch bot? That does notifications for when someone goes live?
The twitch api is so confusing and if anyone has a working one then that would be great.
please use buttons, they were made for a reason 🙏🏽
rephrase
the cog was added, bot.add_cog doesnt return anything
what do they need help with
okey, I have done a python file named user_commands which has the cog, of any commands releted to the user, it that correct, seems correct?
yeah, whats the issue?
none, I'm new using python after I have been spent my life on Java
I might make stupid mistakes
spending a lifetime on java is criminal. thank you for reforming 🙏🏽
thats alright, errors happen
okay is it possible to make the box bigger on the bot msg
what box
Afaik no
what
As far as I know you can't
oh alr, thanks
It would only resize itself depending on the amount
of content in the embed
that has an author name at the top if thats what you’re asking
oh so thats whats making it bigger?
yep. you have to create an embed object first with all your desired attributes (title, description, etc) and then do .set_author(name = …) on that object
so:
embed = discord.Embed(
description = “hi”
)
embed.set_author(name = “hello”)
(no formatting bc im on my iphone)
yea I thought about it, but he changed the idea lol
How would you make a bot react to a message if u have the message's link
what would i use to get all the members who reacted to a message
import discord
from discord.ext import commands
import datetime
welcome_channel = 1221421626202001470
intents = discord.Intents.default()
intents.message_content = True
client = commands.Bot("~", intents=intents)
@client.event
async def on_connect():
print("connected")
@client.event
async def on_member_join(member):
channel = client.get_channel(welcome_channel)
embed = discord.Embed(
description=f'Welcome to the official GAM3 discord server **{member.mention}**!',
color=0x000000,
timestamp=datetime.datetime.now(),
)
channel.send(embed=embed)
why is this not posting?
!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) 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) abc.
Changed in version 2.0: `limit` and `after` parameters are now keyword-only.
Examples
Usage...
if you meant why isn't it sending to the welcome_channel, its because you didnt await channel.send and because you didnt enable members intents for on_member_join to work
where do i have to add those
add what
you can enable members intents by just doing intents.members = True and enabling them in the discord developer portal
for awaiting, you just await them for channel.send
@sharp dome ask abt timed reactions
I'm making a discord embed which need to edit it self after some time
but in python the timer task like java doesn't exists, and the way i do it's pretty wrong
async def run(self, interaction):
if self.seconds > 0:
await interaction.response.send_message(embed=self.create_embed())
self.seconds -= 1
else:
await interaction.edit_original_response(embed=self.create_embed())
async def schedule_task(self, interaction):
start_time = time.time()
seconds = self.seconds
while time.time() - start_time < seconds:
await self.run(interaction)
time.sleep(1)
@golden portal @viscid hornet @slate swan
!d discord.ext.tasks
No documentation found for the requested symbol.
@sharp dome
I Made a Discord Bot, It Sends Messages with the Button, I Close and Open the Bot, Button Doesn't Work
still not usefull
it's doesn't created a loop
what?
well, you can't respond to an interaction more than once
what? show your current code please
it should go from 5 to 0, it just printed 4
its supposed to change the message after the timer is done
@tasks.loop(seconds=5)
async def run(self, interaction):
if self.seconds > 0:
if not self.has_message_sent:
self.seconds_left = f"<t:{int(time.time() + self.seconds)}:R>"
self.message = await interaction.response.send_message(embed=self.create_embed())
self.has_message_sent = True
self.seconds -= 1
print(self.seconds)
else:
self.upgrade()
await self.message.edit(embed=self.create_embed())
self.ended = True
I suppose a tasks loop isn't what you want in this case then, disregard.
what do I need
what would we use then
ong python sucks, it doesn't have basic timer task 😭
its better than java
no
a timer task is, when the tasks run for a certain time, and it's what I need.
but python doesn't have it, it has a timer task that delays the task
like "do this 10 times every 10 seconds"?
no, "do this for 5 seconds"
so "do this 5 times every 1 second"
every 1 second it does something for 5 seconds of it life
exactly, something like this
ok lemme try
how would i define reaction
You don't, you get them from somewhere, like a message
nothing it does it 1 time
☝️ ☝️ ☝️
the print stantment
async def task(self):
for i in range(5):
await asyncio.sleep(1)
print(i)
4
Try setting the flush argument of print to True
why it's does it 1 time...
Huh
!e
import asyncio
async def something():
for i in range(5):
await asyncio.sleep(0) # testing only
print(i)
asyncio.run(something())
@naive briar :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | 0
002 | 1
003 | 2
004 | 3
005 | 4

why slepp 0?
Don't waste time
mine crash
Traceback (most recent call last):
File "C:\Users\xntro\PycharmProjects\ps99casino\.venv\Lib\site-packages\discord\app_commands\commands.py", line 827, in _do_call
return await self._callback(self.binding, interaction, **params) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\xntro\PycharmProjects\ps99casino\game_modes_commands.py", line 42, in upgrader
asyncio.run(upgrade_game_mode.task(interaction))
File "C:\Python312\Lib\asyncio\runners.py", line 190, in run
raise RuntimeError(
RuntimeError: asyncio.run() cannot be called from a running event loop
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\xntro\PycharmProjects\ps99casino\.venv\Lib\site-packages\discord\app_commands\tree.py", line 1248, in _call
await command._invoke_with_namespace(interaction, namespace)
File "C:\Users\xntro\PycharmProjects\ps99casino\.venv\Lib\site-packages\discord\app_commands\commands.py", line 853, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\xntro\PycharmProjects\ps99casino\.venv\Lib\site-packages\discord\app_commands\commands.py", line 846, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'upgrader' raised an exception: RuntimeError: asyncio.run() cannot be called from a running event loop
C:\Users\xntro\PycharmProjects\ps99casino\.venv\Lib\site-packages\discord\app_commands\tree.py:1252: RuntimeWarning: coroutine 'UpgradeGameMode.task' was never awaited
await self.on_error(interaction, e)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback```
Don't do that, I'm just testing. Should've done it in #bot-commands
ok, how to edit an sent message?
the message it can be sent by anybody
So it need to know which one to edit
message = await ctx.send(“hello”)
await message.edit(“hi”)
for interactions, use .response.edit_message
I have done it works perctly!
what type are you using
lemme see the solution rq
await interaction.response.send_message(embed=self.create_embed())
await interaction.edit_original_response(embed=self.create_embed())
like easy lol
you cant react to a message if you have the link? you’d need to extract the message ID from the link (usually after the last “/“ in a url) and then perform a fetch message on that ID to get the message content, and from there, you can get the message object and do whatever on that
amazing, well done 👍🏽
Can u give an example I'm a begginer
Someone said i need channel id too
also pro tip, you can get the original message by doing await interaction.original_message() because .send_message() doesnt return anything
yes, the channel ID is necessary for you to send messages in that channel
you can always do await message.channel.send(…) to keep things readable and small
Do i need channel id to react?
i think i’m slow but how to fetch a users global display name change , I assumed its with on user update but i’m getting frustrated
https://discord.com/channels/<guild_id>/<channel_id>/<message_id>
Discord is the easiest way to communicate over voice, video, and text. Chat, hang out, and stay close with your friends and communities.
you need the message object to add the reaction
await message.add_reaction(…)
How to you get the message object then 😭
do you have any recommendations for a python host with administration permission?
i just said: fetch it from the ID in the URL
your computer
otherwise idk
most decent VPSs cost money
theres no good free ones and all the free ones have a drawback
Oh
OH
Like split the message link
yep, you got the right idea! 👍🏽
i showed you the url format
I thought ur redirecting me somewhere but u failed
idk how to do it in regex but you can do it in python by splitting at ‘/‘ and then taking the last object with index -1
😭😭
idk why its bringing up a URL, that doesnt exist
Can u fetch channel id if u have message id
channel id is in the url as well
No if I don't have message link but I have message id
it goes /guild_id/channel_id/message_id
Is there a way
yeah thats message.channel
and then to get the ID of that channel, add a .id to the end
No I don't have the message object I only have the message's id
so fetch the message
i think its bot.fetch_message
So I can fetch a message by its id and store it in a variable
And do variable.channel.id
And it'll give me the channel id
Am i wrong
yes
perfectly correct
yep, exactly that
I see ty
question
yep
there is the fileds where the user can put their own choice, but i wan there will be 2 choice to put how to do it
hmm okay…
like for coinflip
/coinflip side: heads:tails
yep
something like that you will see heads and tails on the menu when you the slash command
use autocorrects
like this
let me find the link one sec
@app_commands.command()
async def reactionroleadd(self,interaction: discord.Interaction, role: discord.Role, emoji: str , message_id: str):
message = bot.fetch_message(int(message_id))
await message.add_reaction(emoji)
c.execute("INSERT INTO reactionaldb VALUES (?,?,?)",(message_id,str(role.id),emoji))
conn.commit()
await interaction.response.send_message("done",ephemeral=True)```
@viscid hornet
Do it have to be
message = await channel.fetch_message(...)
no its bot.fetch_message
i said that
get_message then
that doesnt exist either
wait wtf
you need a channel to get the message obj
:blobabouttocry:
ohhhh that makes more sense
indexing through all the trillions of messages would be a pain ngl 😭
Oh my bad i forgot something was in main file
Yeah
assuming your cog looks like py class Cog(commands.Cog): def __init__(self, bot): self.bot = bot
class reactionrole(commands.Cog):
def __init__(self, bot):
self.bot = bot
@app_commands.command()
async def reactionroleadd(self,interaction: discord.Interaction, role: discord.Role, emoji: str , message_id: str):
message = bot.fetch_message(int(message_id))
await message.add_reaction(emoji)
c.execute("INSERT INTO reactionaldb VALUES (?,?,?)",(message_id,str(role.id),emoji))
conn.commit()
await interaction.response.send_message("done",ephemeral=True)
```
I've already done that
self.bot.fetch_message?
as the other person said, fetch_message doesnt exist
Get message?
nope
ok so you have the link
a message link like this py [#discord-bots message](/guild/267624335836053506/channel/343944376055103488/)
Yeah tried that doens't work either
guild id: 267624335836053506
channel id: 343944376055103488
message id: 1223305209703305379
In the slash command I'm talking the id
There isn't a way to get message by id?
you use the channel ID in self.bot.get_channel() and then you can message from there
I'll come after completing by dinner
i figured it out but its a bit complicated because you need the channel ID as well py channel = await self.bot.get_channel(channel_id) await channel.fetch_message(message_id)
so?
oh shit i forgot
i went on my laptop and my mind instantly went black
@sharp dome this was one of the examples for an autocomplete ```py
@app_commands.command(...)
async def foo(interaction: discord.Interaction, bar: str):
...
@foo.autocomplete('bar')
async def autocomplete_callback(interaction: discord.Interaction, current: str):
# Do stuff with the "current" parameter, e.g. querying it search results...
# Then return a list of app_commands.Choice
return [
app_commands.Choice(name='Option 1', value='Option 1')
]```
i found a better way, using an Enum, it auto put on the option
how to add button to an embed?
use a view
example?, the button has some code on it to be handled
wdym by an enum
@app_commands.command(
name="coinflip",
description="Flip a coin",
)
async def coinflip(self, interaction, side: CoinSide, amount: str):
class CoinSide(Enum):
Heads = "Heads"
Tails = "Tails"
see, enum!
what the fuck am i looking at
class ConfirmOrCancel(ui.View):
def __init__(self):
super().__init__(timeout = None)
self.selected = False
@ui.button(label = "Yes", style = BS.green)
async def confirm(self, interaction: Interaction, button: discord.Button):
self.selected = True
for item in self.children:
item.disabled = True
if item.label == button.label:
item.style = BS.green
else:
item.style = BS.grey
await interaction.response.edit_message(
view = self, embed = discord.Embed(
title = "Confirming Decision...",
description = "You have selected `Yes` so we will be updating your diary. Give us a moment.",
color = discord.Color.green()
)
)
@ui.button(label = "No", style = BS.red)
async def cancel(self, interaction: Interaction, button: discord.Button):
for item in self.children:
item.disabled = True
if item.label == button.label:
item.style = BS.green
else:
item.style = BS.grey
await interaction.response.edit_message(
view = self, embed = discord.Embed(
title = "Cancelling Decision...",
description = "You have selected `No` so we will be aborting the process of updating your diary. Give us a moment.",
color = discord.Color.red()
)
)```
ok
how did you use an enum?
like an enum lol
show code
if side not in [CoinSide.Heads, CoinSide.Tails]:
await interaction.response.send_message("invalid side. Must be heads or tails", ephemeral=True)
return
if side is CoinSide.Heads:
# do something
how does the autocomplete work though?
i meant show the autocomplete code
this is wrong
whats wrong with it?
what library I need to have?
[2024-03-29 18:04:20] [ERROR ] discord.ui.view: Ignoring exception in view <Confirm timeout=None children=1> for item <Button style=<ButtonStyle.success: 3> url=None disabled=False label='Confirm' emoji=None row=None>
Traceback (most recent call last):
File "C:\Users\xntro\PycharmProjects\ps99casino\.venv\Lib\site-packages\discord\ui\view.py", line 427, in _scheduled_task
await item.callback(interaction)
File "C:\Users\xntro\PycharmProjects\ps99casino\game_modes\game_modes_commands.py", line 106, in confirm
await interaction.response.send_message(embed=create_embed_coinflip)
^^^^^^^^^^^^^^^^^^^^
AttributeError: 'Button' object has no attribute 'response'
like
show your code
its regular discord
class Confirm(discord.ui.View):
def __init__(self, user_data: user_data_manager, amount_to_float: float):
super().__init__(timeout=None)
self.user_data = user_data
self.amount_to_float = amount_to_float
@discord.ui.button(label="Confirm", style=discord.ButtonStyle.green)
async def confirm(self, button, interaction):
user = self.user_data.get_user(interaction.user.id)
create_embed_coinflip = discord.Embed(
title=":white_check_mark: Coinflip Created",
description=(
":gems: **Gems**: {}\n"
":gems: **New Balance**: {}\n"
":crown~1: **Channel**: <#{}>"
).format(
number_converter.number_to_suffix(self.amount_to_float),
number_converter.number_to_suffix(user.balance - self.amount_to_float),
cfg.FLIP_COIN_CHANNEL_ID),
color=discord.Color.purple())
create_embed_coinflip.set_footer(text=f"{cfg.BOT_NAME} - Coinflip Created")
self.user_data.remove_balance(interaction.user.id, self.amount_to_float)
self.user_data.add_wagered(interaction.user.id, self.amount_to_float)
await interaction.response.send_message(embed=create_embed_coinflip)
why the fuck are they in that order
its interaction then button

