Ошибка RuntimeWarning после выполнения команды в discord боте
Я пишу discord бота(discord.py) на Python. После выполнения команды /select_faculty я получаю вот такую ошибку:
RuntimeWarning: coroutine 'send_override' was never awaited
ret = await coro(*args, **kwargs)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Вот код:
faculties = {
"grif": 0,
"sliz": 0,
"huff": 0,
"raven": 0
}
who = ""
faculty = ""
question1_emb = discord.Embed(title="Давай пройдём небольшой тест.", colour=discord.Colour.green(),
description="Первый вопрос - какой ты?:")
question2_emb = discord.Embed(title="Второй вопрос:", colour=discord.Colour.orange(),
description="Какое животное тебе нравится больше всего?")
question3_emb = discord.Embed(title="Третий вопрос:", colour=discord.Colour.purple(),
description="Какая стихия нравится тебе больше всего?")
question4_emb = discord.Embed(title="Четвёртый вопрос:", colour=discord.Colour.blue(),
description="Какие комбинации цветов нравятся тебе больше всего?")
question5_emb = discord.Embed(title="Пятый вопрос:", colour=discord.Colour.red(),
description="Какое привидение из Хогвартса нравится тебе больше всего?")
await ctx.message.delete()
await answer.delete()
answer = await member.send(embed=who_emb, components=[
[Button(style=ButtonStyle.green, label="Ученик с жаждой знаний", emoji="??")],
[Button(style=ButtonStyle.blue, label="Мудрый наставник", emoji="?")],
[Button(style=ButtonStyle.red, label="Министр магии", emoji="?⚖️")]
])
response = await bot.wait_for("button_click")
await response.edit_origin()
if response.component.label == "Ученик с жаждой знаний":
who = "apprentice"
await answer.delete()
elif response.component.label == "Мудрый наставник":
who = "mentor"
await answer.delete()
elif response.component.label == "Министр магии":
await ctx.send(embed=discord.Embed(title="Ты не пройдёшь!!!", colour=discord.Colour.red()))
answer = await member.send(embed=question1_emb, components=[
[Button(style=ButtonStyle.red, label="Храбрый"),
Button(style=ButtonStyle.green, label="Хитрый")],
[Button(style=ButtonStyle.gray, label="Упорный"),
Button(style=ButtonStyle.blue, label="Мудрый")]
])
response = await bot.wait_for("button_click")
await response.edit_origin()
if response.component.label == "Храбрый":
faculties["grif"] += 1
elif response.component.label == "Хитрый":
faculties["sliz"] += 1
elif response.component.label == "Упорный":
faculties["huff"] += 1
elif response.component.label == "Мудрый":
faculties["raven"] += 1
await answer.delete()
answer = await member.send(embed=question2_emb, components=[
[Button(style=ButtonStyle.red, label="Лев"),
Button(style=ButtonStyle.green, label="Змея"),
Button(style=ButtonStyle.gray, label="Барсук"),
Button(style=ButtonStyle.blue, label="Орёл")]
])
response = await bot.wait_for("button_click")
await response.edit_origin()
if response.component.label == "Лев":
faculties["grif"] += 1
elif response.component.label == "Змея":
faculties["sliz"] += 1
elif response.component.label == "Барсук":
faculties["huff"] += 1
elif response.component.label == "Орёл":
faculties["raven"] += 1
await answer.delete()
answer = await member.send(embed=question3_emb, components=[
[Button(style=ButtonStyle.red, label="Огонь"),
Button(style=ButtonStyle.green, label="Вода"),
Button(style=ButtonStyle.gray, label="Земля"),
Button(style=ButtonStyle.blue, label="Воздух")]
])
response = await bot.wait_for("button_click")
await response.edit_origin()
if response.component.label == "Огонь":
faculties["grif"] += 1
elif response.component.label == "Вода":
faculties["sliz"] += 1
elif response.component.label == "Земля":
faculties["huff"] += 1
elif response.component.label == "Воздух":
faculties["raven"] += 1
await answer.delete()
answer = await member.send(embed=question4_emb, components=[
[Button(style=ButtonStyle.red, label="Красный и жёлтый"),
Button(style=ButtonStyle.green, label="Зелёный и серебрянный")],
[Button(style=ButtonStyle.gray, label="Жёлтый и чёрный"),
Button(style=ButtonStyle.blue, label="Синий и бронзовый")]
])
response = await bot.wait_for("button_click")
await response.edit_origin()
if response.component.label == "Красный и жёлтый":
faculties["grif"] += 1
elif response.component.label == "Зелёный и серебрянный":
faculties["sliz"] += 1
elif response.component.label == "Жёлтый и чёрный":
faculties["huff"] += 1
elif response.component.label == "Синий и бронзовый":
faculties["raven"] += 1
await answer.delete()
answer = await member.send(embed=question5_emb, components=[
[Button(style=ButtonStyle.red, label="Почти Безголовый Ник"),
Button(style=ButtonStyle.green, label="Кровавый Барон")],
[Button(style=ButtonStyle.gray, label="Толстый Монах"),
Button(style=ButtonStyle.blue, label="Серая Дама")]
])
response = await bot.wait_for("button_click")
await response.edit_origin()
if response.component.label == "Почти Безголовый Ник":
faculties["grif"] += 1
elif response.component.label == "Кровавый Барон":
faculties["sliz"] += 1
elif response.component.label == "Толстый Монах":
faculties["huff"] += 1
elif response.component.label == "Серая Дама":
faculties["raven"] += 1
await answer.delete()
for k, v in faculties.items():
if v == max(faculties.values()):
faculty = k
for role in [role.name for role in ctx.author.roles]:
if role != "@everyone" and role in channel_roles.keys():
user_role = discord.utils.get(ctx.message.author.roles, name=role)
await member.remove_roles(user_role)
await member.add_roles(discord.utils.get(ctx.channel.guild.roles, id=roles[who][faculty]))
Ответы (1 шт):
Автор решения: Be3y4uu_K0T
→ Ссылка
Я использую discord.py 2.0.0a3575+g45d498c и dislash.py 1.4.9. Надеюсь этот код Вам поможет или даст идею хотя бы.
config.py
ds_token = '<token>'
guild_ids = {<guild_id>}
owner_ids = {<your_id>}
bot_prefix = '<command_prefix>'
index.py
from __future__ import annotations
from discord import commands
import discord as ds
import dislash as dl
import asyncio
import config
bot = commands.Bot(commands.when_mentioned_or(config.bot_prefix), owner_ids=config.owner_ids)
slash = dl.InteractionClient(bot, test_guilds=config.guild_ids)
@slash.slash_command()
async def select_faculty(ctx):
questions = [
(
ds.Embed(
title='Давай пройдём небольшой тест.',
colour=ds.Colour.green(),
description='Первый вопрос - какой ты?'
),
[
dl.ActionRow(
dl.Button(
style=dl.ButtonStyle.red,
label='Храбрый',
custom_id='gryffindor'
),
dl.Button(
style=dl.ButtonStyle.green,
label='Хитрый',
custom_id='slytherin'
)
),
dl.ActionRow(
dl.Button(
style=dl.ButtonStyle.gray,
label='Упорный',
custom_id='hufflepuff'
),
dl.Button(
style=dl.ButtonStyle.blurple,
label='Мудрый',
custom_id='ravenclaw'
)
)
],
),
(
ds.Embed(
title='Второй вопрос:',
colour=ds.Colour.orange(),
description='Какое животное тебе нравится больше всего?'
),
[
dl.ActionRow(
dl.Button(
style=dl.ButtonStyle.red,
label='Лев',
custom_id='gryffindor'
),
dl.Button(
style=dl.ButtonStyle.green,
label='Змея',
custom_id='slytherin'
)
),
dl.ActionRow(
dl.Button(
style=dl.ButtonStyle.gray,
label='Барсук',
custom_id='hufflepuff'
),
dl.Button(
style=dl.ButtonStyle.blurple,
label='Орёл',
custom_id='ravenclaw'
)
)
],
),
(
ds.Embed(
title='Третий вопрос:',
colour=ds.Colour.purple(),
description='Какая стихия нравится тебе больше всего?'
),
[
dl.ActionRow(
dl.Button(
style=dl.ButtonStyle.red,
label='Огонь',
custom_id='gryffindor'
),
dl.Button(
style=dl.ButtonStyle.green,
label='Вода',
custom_id='slytherin'
)
),
dl.ActionRow(
dl.Button(
style=dl.ButtonStyle.gray,
label='Земля',
custom_id='hufflepuff'
),
dl.Button(
style=dl.ButtonStyle.blurple,
label='Воздух',
custom_id='ravenclaw'
)
)
],
),
(
ds.Embed(
title='Четвёртый вопрос:',
colour=ds.Colour.blue(),
description='Какие комбинации цветов нравятся тебе больше всего?'
),
[
dl.ActionRow(
dl.Button(
style=dl.ButtonStyle.red,
label='Красный и Жёлтый',
custom_id='gryffindor'
),
dl.Button(
style=dl.ButtonStyle.green,
label='Зелёный и Серебряный',
custom_id='slytherin'
)
),
dl.ActionRow(
dl.Button(
style=dl.ButtonStyle.gray,
label='Жёлтый и Чёрный',
custom_id='hufflepuff'
),
dl.Button(
style=dl.ButtonStyle.blurple,
label='Синий и Бронзовый',
custom_id='ravenclaw'
)
)
],
),
(
ds.Embed(
title='Пятый вопрос:',
colour=ds.Colour.red(),
description='Какое привидение из Хогвартса нравится тебе больше всего?'
),
[
dl.ActionRow(
dl.Button(
style=dl.ButtonStyle.red,
label='Почти Безголовый Ник',
custom_id='gryffindor'
),
dl.Button(
style=dl.ButtonStyle.green,
label='Кровавый Барон',
custom_id='slytherin'
)
),
dl.ActionRow(
dl.Button(
style=dl.ButtonStyle.gray,
label='Толстый Монах',
custom_id='hufflepuff'
),
dl.Button(
style=dl.ButtonStyle.blurple,
label='Серая Дама',
custom_id='ravenclaw'
)
)
],
),
]
message = await ctx.reply(
embed=ds.Embed(
title='Кем ты хочешь стать?',
colour=ds.Colour.green(),
),
components=[
dl.ActionRow(
dl.Button(
style=dl.ButtonStyle.green,
label='Ученик с жаждой знаний',
emoji='??',
custom_id='apprentice'
),
dl.Button(
style=dl.ButtonStyle.blurple,
label='Мудрый наставник',
emoji='?',
custom_id='mentor'
),
dl.Button(
style=dl.ButtonStyle.red,
label='Министр магии',
emoji='?⚖️',
custom_id='impossible'
)
)
]
)
try:
inter = await message.wait_for_button_click(timeout=60)
except asyncio.TimeoutError:
return await message.reply(
embed=ds.Embed(
title='Слииишком долго!',
colour=ds.Colour.red(),
description='Ты долго слишком долго не отвечал.'
)
)
who = inter.component.custom_id
if who == 'impossible':
return await inter.reply(
embed=ds.Embed(
title='Ты не пройдёшь!!!',
colour=ds.Colour.red()
)
)
faculties = {
'gryffindor': 0,
'slytherin': 0,
'hufflepuff': 0,
'ravenclaw': 0,
}
for embed, components in questions:
message = await inter.reply(
embed=embed,
components=components
)
try:
inter = await message.wait_for_button_click(timeout=60)
except asyncio.TimeoutError:
return await message.reply(
embed=ds.Embed(
title='Слииишком долго!',
colour=ds.Colour.red(),
description='Ты долго слишком долго не отвечал.'
)
)
faculties[inter.clicked_button.custom_id] += 1
roles = (
'apprentice_gryffindor',
'apprentice_slytherin',
'apprentice_hufflepuff',
'apprentice_ravenclaw',
'mentor_gryffindor',
'mentor_slytherin',
'mentor_hufflepuff',
'mentor_ravenclaw',
)
await ctx.author.remove_roles(
*(ds.utils.get(ctx.guild.roles, name=role) for role in roles)
)
# OR
# roles = ( # tuple of role id's
# 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
# )
#
# await ctx.author.remove_roles(
# *(ctx.guild.get_role(role) for role in roles)
# )
faculty = max(faculties, key=lambda faculty: faculties[faculty])
role = ds.utils.get(ctx.guild.roles, name=f'{who}_{faculty}')
await ctx.author.add_roles(role)
await inter.reply(
embed=ds.Embed(
title='Твой факультет...',
colour=ds.Colour.green(),
description={
f'{who}_gryffindor': 'Гриффиндор',
f'{who}_slytherin': 'Слизерин',
f'{who}_hufflepuff': 'Пуффендуй',
f'{who}_ravenclaw': 'Когтевран',
}.get(role.name)
)
)
bot.run(config.ds_token, reconnect=True)
UPD:
Изменил под discord.py 1.7.3 и discord-components 2.1.2.
index.py
from __future__ import annotations
from discord_components import (
ComponentsBot,
Interaction,
ButtonStyle,
ActionRow,
Button,
)
from discord.ext import commands
import discord as ds
import asyncio
import config
bot = ComponentsBot(commands.when_mentioned_or(config.bot_prefix), owner_ids=config.owner_ids)
@bot.event
async def on_ready():
print('Bot is ready!')
@bot.command()
async def select_faculty(ctx):
async def wait_button(message):
try:
return await bot.wait_for(
event='button_click',
check=lambda inter: inter.message.id == message.id and inter.user == ctx.author,
timeout=60
)
except asyncio.TimeoutError:
return await message.reply(
embed=ds.Embed(
title='Слииишком долго!',
colour=ds.Colour.red(),
description='Ты долго слишком долго не отвечал.'
)
)
questions = [
(
ds.Embed(
title='Давай пройдём небольшой тест.',
colour=ds.Colour.green(),
description='Первый вопрос - какой ты?'
),
[
ActionRow(
Button(
style=ButtonStyle.red,
label='Храбрый',
custom_id='gryffindor'
),
Button(
style=ButtonStyle.green,
label='Хитрый',
custom_id='slytherin'
)
),
ActionRow(
Button(
style=ButtonStyle.gray,
label='Упорный',
custom_id='hufflepuff'
),
Button(
style=ButtonStyle.blue,
label='Мудрый',
custom_id='ravenclaw'
)
)
],
),
(
ds.Embed(
title='Второй вопрос:',
colour=ds.Colour.orange(),
description='Какое животное тебе нравится больше всего?'
),
[
ActionRow(
Button(
style=ButtonStyle.red,
label='Лев',
custom_id='gryffindor'
),
Button(
style=ButtonStyle.green,
label='Змея',
custom_id='slytherin'
)
),
ActionRow(
Button(
style=ButtonStyle.gray,
label='Барсук',
custom_id='hufflepuff'
),
Button(
style=ButtonStyle.blue,
label='Орёл',
custom_id='ravenclaw'
)
)
],
),
(
ds.Embed(
title='Третий вопрос:',
colour=ds.Colour.purple(),
description='Какая стихия нравится тебе больше всего?'
),
[
ActionRow(
Button(
style=ButtonStyle.red,
label='Огонь',
custom_id='gryffindor'
),
Button(
style=ButtonStyle.green,
label='Вода',
custom_id='slytherin'
)
),
ActionRow(
Button(
style=ButtonStyle.gray,
label='Земля',
custom_id='hufflepuff'
),
Button(
style=ButtonStyle.blue,
label='Воздух',
custom_id='ravenclaw'
)
)
],
),
(
ds.Embed(
title='Четвёртый вопрос:',
colour=ds.Colour.blue(),
description='Какие комбинации цветов нравятся тебе больше всего?'
),
[
ActionRow(
Button(
style=ButtonStyle.red,
label='Красный и Жёлтый',
custom_id='gryffindor'
),
Button(
style=ButtonStyle.green,
label='Зелёный и Серебряный',
custom_id='slytherin'
)
),
ActionRow(
Button(
style=ButtonStyle.gray,
label='Жёлтый и Чёрный',
custom_id='hufflepuff'
),
Button(
style=ButtonStyle.blue,
label='Синий и Бронзовый',
custom_id='ravenclaw'
)
)
],
),
(
ds.Embed(
title='Пятый вопрос:',
colour=ds.Colour.red(),
description='Какое привидение из Хогвартса нравится тебе больше всего?'
),
[
ActionRow(
Button(
style=ButtonStyle.red,
label='Почти Безголовый Ник',
custom_id='gryffindor'
),
Button(
style=ButtonStyle.green,
label='Кровавый Барон',
custom_id='slytherin'
)
),
ActionRow(
Button(
style=ButtonStyle.gray,
label='Толстый Монах',
custom_id='hufflepuff'
),
Button(
style=ButtonStyle.blue,
label='Серая Дама',
custom_id='ravenclaw'
)
)
],
),
]
message = await ctx.reply(
embed=ds.Embed(
title='Кем ты хочешь стать?',
colour=ds.Colour.green(),
),
components=[
ActionRow(
Button(
style=ButtonStyle.green,
label='Ученик с жаждой знаний',
emoji='??',
custom_id='apprentice'
),
Button(
style=ButtonStyle.blue,
label='Мудрый наставник',
emoji='?',
custom_id='mentor'
),
Button(
style=ButtonStyle.red,
label='Министр магии',
emoji='?⚖️',
custom_id='impossible'
)
)
]
)
inter: Interaction = await wait_button(message)
if (who := inter.custom_id) == 'impossible':
return await inter.send(
ephemeral=False,
embed=ds.Embed(
title='Ты не пройдёшь!!!',
colour=ds.Colour.red()
),
)
faculties = {
'gryffindor': 0,
'slytherin': 0,
'hufflepuff': 0,
'ravenclaw': 0,
}
for embed, components in questions:
message = await inter.send(
embed=embed, components=components, ephemeral=False,
)
inter = await wait_button(message)
faculties[inter.custom_id] += 1
roles = (
'apprentice_gryffindor',
'apprentice_slytherin',
'apprentice_hufflepuff',
'apprentice_ravenclaw',
'mentor_gryffindor',
'mentor_slytherin',
'mentor_hufflepuff',
'mentor_ravenclaw',
)
await ctx.author.remove_roles(
*(ds.utils.get(ctx.guild.roles, name=role) for role in roles)
)
# OR
# roles = ( # tuple of role id's
# 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
# )
#
# await ctx.author.remove_roles(
# *(ctx.guild.get_role(role) for role in roles)
# )
faculty = max(faculties, key=lambda faculty: faculties[faculty])
role = ds.utils.get(ctx.guild.roles, name=f'{who}_{faculty}')
await ctx.author.add_roles(role)
await inter.reply(
embed=ds.Embed(
title='Твой факультет...',
colour=ds.Colour.green(),
description={
f'{who}_gryffindor': 'Гриффиндор',
f'{who}_slytherin': 'Слизерин',
f'{who}_hufflepuff': 'Пуффендуй',
f'{who}_ravenclaw': 'Когтевран',
}[role.name]
)
)
bot.run(config.ds_token, reconnect=True)