Disnake - отправляет ошибку после нажатия кнопки
всем привет! я хотел сделать команду, чтобы вызывать Порфирьевич. код ну вроде должен работать, он работает. но вот если прям быстро нажать, то будет ошибка disnake.ext.commands.errors.CommandInvokeError: Command raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction
ещё может выдать <disnake.embeds.Embed object at 0x0000021C1F7411B0>(хотя я эмбед даже не использую). пытался решить как-то сам, но не получилось. буду рад, если кто-то поможет, заранее спасибо
сам же код(не бейте):
import disnake
from disnake.ext import commands
import requests
import random
from disnake.ui import Button
class skynet(commands.Cog):
def __init__(self, bot):
self.bot = bot
async def generate_otvet(self, inter: disnake.ApplicationCommandInteraction, text: str):
url = 'https://pelevin.gpt.dobro.ai/generate/'
headers = {
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36',
'Content-Type': 'text/plain;charset=UTF-8',
'Accept': '*/*',
'Origin': 'https://porfirevich.ru',
'Sec-Fetch-Site': 'cross-site',
'Sec-Fetch-Mode': 'cors',
'Sec-Fetch-Dest': 'empty',
'Accept-Language': 'ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7'
}
data = {
'prompt': f'{text}',
'length': random.randint(5, 100)
}
response = requests.post(url, headers=headers, json=data)
if response.status_code == 200:
result = response.json()
await inter.message.edit(content=f"{text}**{result['replies'][0]}**", components=[Button(emoji="?", style=disnake.ButtonStyle.grey, custom_id="rewrite")])
else:
await inter.message.edit(content=f'Ошибочка ¯\_(ツ)_/¯')
@commands.slash_command(dm_permission=False)
async def porfirevich(self, inter: disnake.ApplicationCommandInteraction, text: str):
"""Генерирует текст с помощью Порфирьевича"""
await inter.response.defer()
await self.generate_otvet(inter, text)
@commands.Cog.listener()
async def on_button_click(self, interaction: disnake.MessageInteraction):
await interaction.response.defer()
button_disabled = Button(emoji="<:loading:1182012529598279731>", style=disnake.ButtonStyle.grey, custom_id="rewrite", disabled=True)
await interaction.message.edit(components=[button_disabled])
if interaction.data.custom_id == "rewrite":
original_text = interaction.message.content.split("**")[0]
await self.generate_otvet(interaction, original_text)
def setup(bot):
bot.add_cog(skynet(bot))```
Ответы (2 шт):
requests не предзначен для работы в асинхронных средах. Он блокирует event loop, а вместе с ним и слушатель событий. Используйте асинхронный aiohttp (установляется вместе с disnake, так что ничего делать не надо):
Пример:
import aiohttp
import asyncio
async def main():
async with aiohttp.ClientSession() as session:
async with session.get('http://python.org') as response:
print("Status:", response.status)
print("Content-type:", response.headers['content-type'])
html = await response.text()
print("Body:", html[:15], "...")
asyncio.run(main())
Зачем вы используете ожидание в кнопках? Как по мне не логично, попробуйте изменить ответ на кнопку
@bot.listen("on_button_click")
async def button_lst(inter: disnake.MessageInteraction):
if inter.component.custom_id not in ["rewrite"]:
return
if inter.component.custom_id == 'rewrite':
original_text = interaction.message.content.split("**")[0]
await self.generate_otvet(interaction, original_text)
Должно заработать, будут ошибки пишите в комментарии