I’m making a discord bot that sends a message with two buttons. Both buttons sends a message with a picture/gif when pressed. One of them works but the other one gives an error:
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction
Here is the full code:
import os
import discord
from discord.ext import commands
from discord.ui import Button
from discord.ui import View
from dotenv import load_dotenv
import random
intents = discord.Intents.default()
intents.message_content = True
load_dotenv()
TOKEN = os.getenv('Sommer_Challenge_2022_TOKEN')
bot = commands.Bot(command_prefix=';', intents=intents, help_command=None)
channel = bot.get_channel(channel id here)
#facts about sea and beach
#fakta om hav og strand
fact1 = ('Verdens længste strand hedder "Praia Do Cassino". Den ligger i brasilien og er 241 km lang.🏖️')
fact2 = ('Havet dækker omkring 71% af jordens overflade.🌊')
fact3 = ('Ca. 73% af folk der besøger stranden, går i vandet.🛀')
fact4 = ('Der udledes omkring 8-10 tons plastik i havet hvert år. Det svarer til ca. 375.000 halvliters plastikflasker.')
fact5 = ('Over 400 milioner amerikanere går på stranden hvert år.')
fact6 = ('Det Røde Hav er det salteste hav i verden. Vandet indenholder ca. 60 gram salt pr. liter.🧂')
fact7 = ('Ca. 94% af dyrelivet findes havet.🐟')
fact8 = ('Man siger at regnskoven er "jordens lunger", men i virkeligheden producere havet mere end 70% af alt ilt.')
fact9 = ('Det er solen som gør vandet blåt. Det samme gælder himlen.☀️')
fact10 = ('Hvert år dræber hajer mellem fem til ti mennesker. Til gengæld dræber mennesker omkring 100 millioner hajer om året.🦈')
fact11 = ('Ved vesterhavet kan man se bunkere fra 2. verdenskrig.')
fact12 = ('Verdens største sandslot har en diameter på 32 meter og har en højde på 21 meter.')
#Scratch games about sea and beach
#Scratch spil om hav og strand
game_button1 = Button(label="Scratch", url='https://scratch.mit.edu/projects/119134771/')
game_button2 = Button(label="Scratch", url='https://scratch.mit.edu/projects/113456625/')
game_button3 = Button(label="Scratch", url='https://scratch.mit.edu/projects/20743182/')
game_button4 = Button(label="Scratch", url='https://scratch.mit.edu/projects/16250800/')
game_button5 = Button(label="Scratch", url='https://scratch.mit.edu/projects/559210446/')
game_button6 = Button(label="Scratch", url='https://scratch.mit.edu/projects/73644874/')
game_button7 = Button(label="Scratch", url='https://scratch.mit.edu/projects/546214248/')
game_button8 = Button(label="Scratch", url='https://scratch.mit.edu/projects/571081880/')
#tells when bot goes online
#fortæller når en bot går online
@bot.event
async def on_ready():
channel = bot.get_channel(channel name here)
await channel.send('Jeg er online!')
print(f'{bot.user.name} has connected to Discord!')
print(f'conected to: {channel}')
@bot.event
async def on_member_join(member):
await member.send(f'Hej {member.mention}, velkommen på stranden. Nyd solen!☀️')
#does stuff when a specific message is recived
#gør ting når en bestemt besked er modtaget
@bot.event
async def on_message(msg):
if msg.author != bot.user:
if msg.content == (';info'):
await msg.channel.send(f'{bot.user.mention} er lavet af "username" i fobindelse med sommer challenge 2022. n Hvis du har nogle spøgsmål eller har brug for hjælp, er du velkommen til at sende en dm til "username". n Kun et af scratch spillene der er givet link til er lavet af "username" n Piratskibet.dk brugernavn: other username')
elif msg.content == (';fact'):
await msg.channel.send(random.choice([fact1, fact2, fact3, fact5, fact6]))
elif msg.content == (';game'):
view = View()
button = random.choice([game_button1, game_button2, game_button3, game_button4, game_button5, game_button6, game_button7, game_button8])
view.add_item(button)
if button != game_button8:
await msg.channel.send(view=view)
else:
await msg.channel.send('Det her spil er lavet af "username"', view=view)
elif 'hello' in msg.content:
msg.channel.send(f'hello {msg.author.mention}!')
elif 'hej' in msg.content:
await msg.channel.send(f'hej {msg.author.mention}!')
elif msg.content == (';choice'):
embed = discord.Embed(title="", description="", color=0xc27c0e)
file = discord.File(r"C:Usersusernamevs-code-filesSommer_challenge_2022sandslot_før_DESTROY.png", filename="sandslot_før_DESTROY.png")
embed.set_image(url="attachment://sandslot_før_DESTROY.png")
embed.set_footer(text="Ødelæg sandslottet?")
button = Button(label="Ødelæg!", style=discord.ButtonStyle.danger)
button2 = Button(label="Lad det være", style=discord.ButtonStyle.success)
view = View()
view.add_item(button)
view.add_item(button2)
async def button2_callback(interaction):
await msg.delete()
embed = discord.Embed(title="", description="", color=0xc27c0e)
file = discord.File(r"C:Usersusernamevs-code-filesSommer_challenge_2022sandslot_don't_destroy.png", filename="sandslot_don't_destroy.png")
embed.set_image(url="attachment://sandslot_don't_destroy.png")
embed.set_footer(text="Ok")
await interaction.response.send_message(file=file, embed=embed, view=None, delete_after=6.25)
async def button_callback(interaction):
await msg.delete()
embed = discord.Embed(title="", description="", color=0xc27c0e)
file = discord.File(r"C:UsersusernamePicturessandslot_destoy.gif", filename="sandcastle_destoy.gif")
embed.set_image(url="attachment://sandcastle_destoy.gif")
embed.set_footer(text="Sandslottet blev ødelagt")
await interaction.response.send_message(file=file, embed=embed, view=None, delete_after=6.25)
button.callback = button_callback
button2.callback = button2_callback
await msg.channel.send(file=file, embed=embed, view=view, delete_after=5)
bot.run(TOKEN)
Why does this happen?
Code:
from dislash import slash_commands from dislash.interactions import * from discord.ext import commands from pyqiwip2p import QiwiP2P from pyqiwip2p.types import QiwiCustomer, QiwiDatetime from discord import Embed import random import string import secrets ... def create_bill(self, amount, lifetime=45): p2p = QiwiP2P(auth_key=self.QIWI_PRIV_KEY) # Random bill id alphabet = string.ascii_letters + string.digits bill_id = ''.join(secrets.choice(alphabet) for i in range(20)) try: p2p.check(bill_id=bill_id).status except TypeError: # If bill_id doesn't exist bill = p2p.bill(bill_id=bill_id, amount=amount, lifetime=lifetime) if p2p.check(bill_id=bill_id).status == "WAITING": return (bill_id, str(bill.pay_url)) # Gegenerate return self.create_bill(amount, lifetime) @slash_commands.command( guild_ids=test_guilds, ... ) async def donate(self, interact): amount = interact.data.get("amount") bill_id, url = self.create_bill(int(amount), 45) await interact.reply(content="OK", embed=Embed(title="Donate Link!", url=url)) ...
And when used, the error is called: discard.errors.Not Found: 404 Not Found (error code: 10062): Unknown interaction
According to tests, I found out that the bug most likely occurs because of the line:
bill = p2p. bill(bill_id=bill_id, amount=amount, lifetime=lifetime)
But I couldn’t find out why it was happening
Now the code looks like this:
... async def donate(self, interact): amount = interact.data.get("amount") await interact.reply("Loading...") bill_id, url = self.create_bill(int(amount), 45) await interact.edit(content="OK", embed=Embed(title="Donate Link!", url=url)) ...
And this code works, but it has 1 minus, when using the ephemeral=True
parameter:
... async def donate(self, interact): amount = interact.data.get("amount") await interact.reply("Loading...", ephemeral=True) bill_id, url = self.create_bill(int(amount), 45) await interact.edit(content="OK", embed=Embed(title="Donate Link!", url=url)) ...
A new error is raised: TypeError: There's nothing to edit. Send a reply first.
Before asking a question, look at these
Before, check you are using the correct library (discord-components
not discord-buttons
) and if your library is in
the newest version
.
How to make buttons inline?
How to make buttons inline?
Your code must be something like
await <discord.abc.Messageable>.send(
You should use a two-dimensional array like below to make buttons inline.
await <discord.abc.Messageable>.send(
How do I remove components?
How do I remove components?
Simple. Edit the message with parameter components
set to []
.
msg = await <discord.abc.Messageable>.send(
interaction = await <discord.ext.commands.Bot or discord.Client>.wait_for(«event»)
await msg.edit(components = [])
await interaction.edit_origin(
How do I ignore the interaction?
How do I ignore the interaction?
Just respond with the type 6
with no other parameters or defer with edit_origin enabled.
There is an event on_button_click
and on_select_option
. You can use this as normal events.
@<discord.ext.commands.Bot or discord.Client>.event
async def on_button_click(interaction):
if interaction.responded:
await interaction.send(content = «Yay!»)
@<discord.ext.commands.Bot or discord.Client>.event
async def on_select_option(interaction):
if interaction.responded:
await interaction.send(content = «Yay!»)
TypeError: send() got an unexpected keyword argument ‘components’
TypeError: send() got an unexpected keyword argument ‘components’
Have you put DiscordComponents(<discord.Client or discord.ext.commands.Bot>)
inside the on_ready
event or initialized the bot with ComponentsBot
?
Handle multiple interacts
Handle multiple interacts
You should put a while on discord.Client.wait_for
to handle multiple clicks
interaction = await <discord.ext.commands.Bot or discord.Client>.wait_for(«event»)
await interaction.send(content = «Wow»)
Disabling the components for specific users
Disabling the components for specific users
This is impossible but you can ignore the interaction by putting a check.
interaction = await <discord.ext.commands.Bot or discord.Client>.wait_for(
check = lambda i: i.user.id == «something»
I get »404 Not Found (error code: 10062): Unknown interaction»
I get »404 Not Found (error code: 10062): Unknown interaction»
Check if you already responded to the interaction.
You send a discord.Emoji
object to the parameter. You can get the custom emoji by doing
<discord.ext.commands.Bot or discord.Client>.get_emoji(849325102746042439)
Can I set my own colors for buttons?
Can I set my own colors for buttons?
Skip to content
Issue
I have an extremely basic script that pops up a message with a button with the command ?place
Upon clicking this button the bot replies Hi to the user who clicked it.
If the button isn’t interacted with for > approx 3 minutes it then starts to return «interaction failed».
after that the button becomes useless. I assume there is some sort of internal timeout i can’t find in the docs. The button does the same thing whether using discord.py (2.0) or pycord. Nothing hits the console. It’s as if the button click isn’t picked up.
Very occasionally the button starts to work again and a host of these errors hit the console:
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction
Ignoring exception in view <View timeout=180.0 children=1> for item <Button style=<ButtonStyle.success: 3> url=None disabled=False label='click me' emoji=None row=None>:
I assume the timeout = 180 is the cause of this issue but is anyone aware of how to stop this timeout and why it’s happening? I can’t see anything in the docs about discord buttons only being usable for 3 mins.
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.members = True
intents.message_content = True
bot = commands.Bot(command_prefix="?", intents=intents)
embed1=discord.Embed(title="Test", description = f"TESTING",color=0xffffff)
print("bot connected")
@ bot.command(name='place')
async def hello(ctx):
view = discord.ui.View()
buttonSign = discord.ui.Button(label = "click me", style= discord.ButtonStyle.green)
async def buttonSign_callback(interaction):
userName = interaction.user.id
embedText = f"test test test"
embed=discord.Embed(title="Test", description = embedText,color=0xffffff)
await interaction.response.send_message(f"Hi <@{userName}>")
buttonSign.callback = buttonSign_callback
view.add_item(item=buttonSign)
await ctx.send(embed = embed1,view = view)
bot.run(TOKEN)
Solution
Explanation
By default, View
s in discord.py 2.0 have a timeout of 180 seconds (3 minutes). You can fix this error by passing in None
as the timeout when creating the view.
Code
@bot.command(name='place')
async def hello(ctx):
view = discord.ui.View(timeout=None)
References
discord.ui.View.timeout
Answered By – TheFungusAmongUs
Answer Checked By – Robin (BugsFixing Admin)
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
У меня есть очень простой скрипт, который выводит сообщение с кнопкой с командой? Place
При нажатии на эту кнопку бот отвечает привет пользователю, который нажал ее.
Если кнопка не используется в течение > примерно 3 минут, она начинает возвращать сообщение «Ошибка взаимодействия».
После этого кнопка становится бесполезной. Я предполагаю, что есть какой-то внутренний тайм-аут, который я не могу найти в документах. Кнопка делает то же самое, используя discord.py (2.0) или pycord. В консоль ничего не попадает. Как будто нажатие кнопки не подхватывается.
Очень редко кнопка снова начинает работать, и в консоль попадает множество этих ошибок:
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction
Ignoring exception in view <View timeout=180.0 children=1> for item <Button style=<ButtonStyle.success: 3> url=None disabled=False label='click me' emoji=None row=None>:
Я предполагаю, что тайм-аут = 180 является причиной этой проблемы, но кто-нибудь знает, как остановить этот тайм-аут и почему это происходит? Я не вижу в документах ничего о кнопках дискорда, которые можно использовать только в течение 3 минут.
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.members = True
intents.message_content = True
bot = commands.Bot(command_prefix="?", intents=intents)
embed1=discord.Embed(title="Test", description = f"TESTING",color=0xffffff)
print("bot connected")
@ bot.command(name='place')
async def hello(ctx):
view = discord.ui.View()
buttonSign = discord.ui.Button(label = "click me", style= discord.ButtonStyle.green)
async def buttonSign_callback(interaction):
userName = interaction.user.id
embedText = f"test test test"
embed=discord.Embed(title="Test", description = embedText,color=0xffffff)
await interaction.response.send_message(f"Hi <@{userName}>")
buttonSign.callback = buttonSign_callback
view.add_item(item=buttonSign)
await ctx.send(embed = embed1,view = view)
bot.run(TOKEN)
1 ответ
Лучший ответ
Объяснение
По умолчанию View
в discord.py 2.0 имеют тайм-аут 180 секунд (3 минуты). Вы можете исправить эту ошибку, передав None
в качестве времени ожидания при создании представления.
Код
@bot.command(name='place')
async def hello(ctx):
view = discord.ui.View(timeout=None)
Ссылки
discord.ui.View.timeout
4
TheFungusAmongUs
20 Май 2022 в 03:12
Когда первый раз нажимаешь на кнопку, в консоли выдает вот это:
Ignoring exception in view <Market timeout=180 children=4> for item <Button style=<ButtonStyle.primary: 1> url=None disabled=False label='Nitro Full' emoji=None row=None>:
Traceback (most recent call last):
File "C:pythonlibsite-packagesdisnakeinteractionsbase.py", line 827, in send_message
await adapter.create_interaction_response(
File "C:pythonlibsite-packagesdisnakewebhookasync_.py", line 214, in request
raise NotFound(response, data)
disnake.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:pythonlibsite-packagesdisnakeuiview.py", line 370, in _scheduled_task
await item.callback(interaction)
File "C:UsersCreativchakDesktopdiscord-botsMikoBotcogsusers.py", line 40, in nitrofull
await interaction.response.send_message(f"Ваша заявка на нитро создана. Канал с администрацией: <#{channel.id}>", ephemeral=True)
File "C:pythonlibsite-packagesdisnakeinteractionsbase.py", line 837, in send_message
raise InteractionTimedOut(self._parent) from e
disnake.errors.InteractionTimedOut: Interaction took more than 3 seconds to be responded to. Please defer it using "interaction.response.defer" on the start of your command. Later you may send a response by editing the deferred message using "interaction.edit_original_message"
Note: This might also be caused by a misconfiguration in the components make sure you do not respond twice in case this is a component.