discord_components
Выдает ошибку
Traceback (most recent call last):
File "C:\\grant.py", line 2, in <module>
from discord_components import *
ModuleNotFoundError: No module named 'discord_components'
6 раз всё переустановил, обновил, удалил и заново сказал, перезапустил ПК и ничего.
Код:
import discord
from discord_components import *
from discord.ext import commands
from datetime import datetime
intents = discord.Intents.all()
intents.members = True
intents.voice_states = True
intents.messages = True
intents.guilds = True
bot = commands.AutoShardedBot(command_prefix='!', intents=intents)
@bot.event
async def on_ready():
print(f'{bot.user.name} старт успешный!')
activity = discord.Activity(type=discord.ActivityType.playing, name="GrantTopia")
await bot.change_presence(status=discord.Status.dnd, activity=activity)
for command in bot.commands:
print(f'Зарегистрированная команда: {command}')
@bot.command(name='test')
async def test(ctx):
await ctx.send('Тестирование!')
# Команда для создания Embed сообщения
@bot.command(name='add_embed')
async def add_embed(ctx):
"""Открывает меню для ввода заголовка и описания Embed."""
modal = Modal(
title="Создать Embed",
components=[
InputText(label="Заголовок", placeholder="Введите заголовок...", custom_id="title"),
InputText(label="Описание", placeholder="Введите описание...", style=InputTextStyle.paragraph, custom_id="description")
]
)
await ctx.send("Пожалуйста, заполните форму ниже.", components=[Button(style=ButtonStyle.primary, label="Открыть форму", custom_id="open_modal")])
interaction = await wait_for_component(bot, components=[Button(custom_id="open_modal")], timeout=None)
await interaction.respond_with_modal(modal)
timed_out = False
try:
modal_interaction: Interaction = await wait_for_modal(bot, timeout=120) # Ждем 120 секунд на ввод данных
except TimeoutError:
timed_out = True
if timed_out:
await interaction.followup.send("Время ожидания истекло. Попробуйте снова.")
return
title = modal_interaction.text_values['title']
description = modal_interaction.text_values['description']
embed = discord.Embed(
title=title,
description=description,
color=discord.Color.blurple()
)
await interaction.followup.send(embed=embed)
@bot.listen('on_member_join')
async def on_member_join_1(member):
role = discord.utils.get(member.guild.roles, name="? Участник")
if role is not None:
await member.add_roles(role)
registration_date = member.created_at.strftime("%d-%m-%Y %H:%M:%S")
embed = discord.Embed(title=f"Добро пожаловать, {member.mention}!", description=f"Рад тебя видеть на сервере!", color=0xf13443)
embed.set_thumbnail(url=member.avatar)
embed.add_field(name="Информация о пользователе", value=f"Имя: {member.mention}!\nID: {member.id}.\nДата регистрации в Discord: {registration_date}", inline=False)
embed.set_footer(text="GrantTopia • All rights reserved © 2025")
channel = bot.get_channel(1234576722666717274)
await channel.send(embed=embed)
@bot.listen('on_voice_state_update')
async def on_voice_state_update_one(member, before, after):
try:
current_date = datetime.now().strftime("%d-%m-%Y %H:%M:%S")
if before.channel is None and after.channel is not None:
voice_channel = after.channel
embed = discord.Embed(title=f" ", color=0xf13443)
embed.set_thumbnail(url=member.avatar.url)
embed.add_field(name=f" ", value=f"**{member.mention} присоединился к голосовому каналу** {voice_channel.mention}", inline=False)
embed.set_footer(text=f"GrantTopia • All rights reserved © 2025 • {current_date}")
channel = bot.get_channel(СЕКРЕТ)
await channel.send(embed=embed)
except Exception as e:
print(f"Ошибка в on_voice_state_update: {e}")
@bot.listen('on_voice_state_update')
async def on_voice_state_update_two(member, before, after):
try:
current_date = datetime.now().strftime("%d-%m-%Y %H:%M:%S")
if before.channel and not after.channel:
channel = before.channel
voice_channel = before.channel
embed = discord.Embed(title=f" ", color=0xf13443)
embed.set_thumbnail(url=member.avatar.url)
embed.add_field(name=f"", value=f"**{member.mention} покинул голосовой канал ** {voice_channel.mention}", inline=False)
embed.set_footer(text=f"GrantTopia • All rights reserved © 2025 • {current_date}")
channel = bot.get_channel(1235153941205880914)
await channel.send(embed=embed)
except Exception as e:
print(f"Ошибка в on_voice_state_update: {e}")
@bot.listen('on_member_update')
async def on_member_update_1(before, after):
current_date = datetime.now().strftime("%d-%m-%Y %H:%M:%S")
if before.roles != after.roles:
added_roles = [role for role in after.roles if role not in before.roles]
removed_roles = [role for role in before.roles if role not in after.roles]
message = f"**{after.mention} изменение в ролях**:\n"
if added_roles:
message += f"Добавлены роли: {', '.join([role.mention for role in added_roles])}\n"
if removed_roles:
message += f"Удалены роли: {', '.join([role.mention for role in removed_roles])}"
embed = discord.Embed(title=f" ", color=0xf13443)
embed.set_thumbnail(url=after.avatar.url)
embed.add_field(name=f"", value=f"{message}", inline=False)
embed.set_footer(text=f"GrantTopia • All rights reserved © 2025 • {current_date}")
channel = bot.get_channel(СЕКРЕТ) #
await channel.send(embed=embed)
@bot.listen('on_message_edit')
async def on_message_edit_1(before, after):
if before.content != after.content:
log_channel = bot.get_channel(1235153048368844840)
embed = discord.Embed(title="Изменённое сообщение", description=f"Автор: {before.author.mention}\n**До:** {before.content}\n**После:** {after.content}", color=0xff0000)
await log_channel.send(embed=embed)
LOG_CHANNEL_ID = СЕКРЕТ
@bot.listen('on_message_delete')
async def on_message_delete_1(message):
# Проверяем, что сообщение было удалено на сервере
if message.guild is not None:
# Получаем журнал аудита сервера
async for entry in message.guild.audit_logs(action=discord.AuditLogAction.message_delete, limit=1):
if entry.target != message.author:
deleted_by = entry.user # Получаем пользователя, который удалил сообщение
reason = entry.reason # Получаем причину удаления (если указана)
# Формируем и отправляем сообщение в канал логирования
log_channel = bot.get_channel(LOG_CHANNEL_ID)
embed = discord.Embed(title="Удалённое сообщение", description=f"Автор: {message.author.mention}\nСодержание: {message.content}", color=0xffff00)
embed.add_field(name="Удалил:", value=f"{deleted_by.mention} ({deleted_by})", inline=False)
if reason:
embed.add_field(name="Причина:", value=reason, inline=False)
await log_channel.send(embed=embed)
break # Прерываем цикл, если нашли нужную запись
else:
# Если запись в журнале аудита не найдена, добавляем информацию о невозможности определить, кто удалил сообщение
log_channel = bot.get_channel(LOG_CHANNEL_ID)
embed = discord.Embed(title="Удалённое сообщение", description=f"Автор: {message.author.mention}\nСодержание: {message.content}", color=0xffff00)
embed.add_field(name="Удалил:", value="Не удалось определить", inline=False)
await log_channel.send(embed=embed)
bot.run('СЕКРЕТ')
введите сюда код