import discord
from discord.ext import commands
bot = commands.Bot(command_prefix="%", help_command=None, intents=discord.Intents.all())
@bot.event
async def on_ready():
print("Бот готов к работе")
await bot.change_presence(status=discord.Status.online, activity=discord.Game("Помощь - %help")) # Изменяем статус боту
@bot.event
async def on_message(message):
await bot.process_commands(message)
msg = message.content.lower()
greeting_words = ["hello", "hi", "привет"] #вариации приветов
censored_words = ["дурак", "дура", "придурок","говно"] #запрещенные слова
if msg in greeting_words:
await message.channel.send(f"{message.author.mention}, приветствую тебя!")
# Фильтр запрещенных слов
for bad_content in msg.split(" "):
if bad_content in censored_words:
await message.channel.send(f"{message.author.mention}, Полегче, не на базаре же...")
@bot.event
async def on_command_error(ctx, error):
"""Работа с ошибками
"""
print(error)
if isinstance(error, commands.MissingPermissions):
await ctx.send(f"{ctx.author}, у вас недостаточно прав для выполнения данной команды!")
elif isinstance(error, commands.UserInputError):
await ctx.send(embed=discord.Embed(
description=f"Правильное использование команды: `{ctx.prefix}{ctx.command.name}` ({ctx.command.brief})\nExample: {ctx.prefix}{ctx.command.usage}"
))
@bot.command(name="очистить", brief="Очистить чат от сообщений, по умолчанию 10 сообщений", usage="clear <amount=10>")
async def clear(ctx, amount: int=10):
await ctx.channel.purge(limit=amount)
await ctx.send(f"Удалены {amount} сообщений...")
@bot.command(name="кик", brief="Выгнать пользователя с сервера", usage="kick <@user> <reason=None>")
@commands.has_permissions(kick_members=True)
async def kick(ctx, member: discord.Member, *, reason=None):
await ctx.message.delete(delay=1) # Если желаете удалять сообщение после отправки с задержкой
@bot.command(name="бан", brief="Забанить пользователя на сервере", usage="ban <@user> <reason=None>")
@commands.has_permissions(ban_members=True)
async def ban(ctx, member: discord.Member, *, reason=None):
await member.send(f"You was banned on server") # Отправить личное сообщение пользователю
await ctx.send(f"Member {member.mention} was banned on this server")
await member.ban(reason=reason)
@bot.command(name="разбанить", brief="Разбанить пользователя на сервере", usage="unban <user_id>")
@commands.has_permissions(ban_members=True)
async def unban(ctx, user_id: int):
user = await bot.fetch_user(user_id)
await ctx.guild.unban(user)
@bot.command()
async def help(ctx):
"""Команда help
Чтобы не писать тысячу строк одинакового кода, лучше занесем название и описание команд в списки,
и переберм в цикле.
"""
embed = discord.Embed(
title="Команды для использования бота:",
description="Доступные команды:"
)
commands_list = ["clear", "kick", "ban", "unban"]
descriptions_for_commands = ["Очистить чатик", "Выгнать пользователя", "Забанить пользователя", "Разбанить пользователя"]
for command_name, description_command in zip(commands_list, descriptions_for_commands):
embed.add_field(
name=command_name,
value=description_command,
inline=False # Будет выводиться в столбик, если True - в строчку
)
await ctx.send(embed=embed)
@bot.command(name="мут", brief="Запретить пользователю писать (настройте роль и канал)", usage="mute <member>")
async def mute_user(ctx, member: discord.Member):
mute_role = discord.utils.get(ctx.message.guild.roles, name="role name")
await member.add_roles(mute_role)
await ctx.send(f"{ctx.author} gave role mute to {member}")
"""Временный мут
Также вы можете сделать временный мут, для этого используйте модуль asyncio и метод sleep (asyncio.sleep).
Пусть функция принимает параметр time_mute. Поставьте условие if "h" in time_mute:
То есть, если вы пишите: !mute @user 1h, и в переменной time_mute находит букву "h" значит asyncio.sleep(time_mute[:1] * 3600)
"""
@bot.command(name="join", brief="Подключение к голосовому каналу", usage="join")
async def join_to_channel(ctx):
global voice
voice = discord.utils.get(bot.voice_clients, guild=ctx.guild)
channel = ctx.message.author.voice.channel
if voice and voice.is_connected():
await voice.move_to(channel)
else:
voice = await channel.connect()
await ctx.send(f"Bot was connected to the voice channel")
@bot.command(name="leave", brief="Отключение от голосового канала", usage="leave")
async def leave_from_channel(ctx):
global voice
voice = discord.utils.get(bot.voice_clients, guild=ctx.guild)
channel = ctx.message.author.voice.channel
if voice and voice.is_connected():
await voice.disconnect()
else:
voice = await channel.disconnect()
await ctx.send(f"Bot was connected to the voice channel")
bot.run("TOKEN")
[![Ошибка при любой команды][1]][1]
[1]: https://i.stack.imgur.com/k5X3w.png