This commit is contained in:
Alex D
2023-04-24 17:45:20 +03:00
parent 56c1ebefd3
commit 4731006753
18 changed files with 371 additions and 94 deletions
-1
View File
@@ -1 +0,0 @@
# Hyper-tech
+20
View File
@@ -0,0 +1,20 @@
import disnake
from disnake.ext import commands
class AboutCommand(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.slash_command()
async def about(self, ctx: disnake.AppCommandInteraction):
embed = disnake.Embed(title='О боте', description='Многофункциональный бот.', color=0x00ff00)
embed.set_author(name='Hyper Tech')
embed.add_field(name='Автор', value='<@795901895666434070> а так же <@662994219794956298>\n')
embed.add_field(name='Версия', value='v1.01.')
embed.add_field(name='Дата выпуска', value='23.04.2023')
await ctx.send(embed=embed)
def setup(bot):
bot.add_cog(AboutCommand(bot))
+19
View File
@@ -0,0 +1,19 @@
import disnake
from disnake.ext import commands
class AvatarCommand(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.slash_command()
async def avatar(self, ctx: disnake.AppCommandInteraction, member: disnake.Member = None):
if not member:
member = ctx.author
embed = disnake.Embed(title=f'Аватар пользователя: {member}', color=0x00ff00)
embed.set_image(url=member.avatar.url)
await ctx.send(embed=embed)
def setup(bot):
bot.add_cog(AvatarCommand(bot))
+30
View File
@@ -0,0 +1,30 @@
import disnake
from disnake.ext import commands
class BanCommands(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.slash_command(description="Изгоняет указанного участника с сервера навсегда.")
async def ban(self, ctx: disnake.AppCommandInteraction, member: disnake.Member, *, reason=None):
if disnake.utils.get(ctx.author.roles, id=1060542125621649458):
await member.ban(reason=reason)
await ctx.send(f'{member.mention} был забанен. Причина: {reason}')
else:
await ctx.send(f'{ctx.author.mention}, у вас нет роли <@&1060542125621649458>.')
@commands.has_any_role(1060542125621649458)
@commands.slash_command()
async def unban(ctx: disnake.AppCommandInteraction, *, user: disnake.User):
if disnake.utils.get(ctx.author.roles, id=1060542125621649458):
await ctx.guild.unban(user)
if (user.name, user.discriminator) == (user.name, user.discriminator):
await ctx.guild.unban(user)
await ctx.send(f'{user.mention} был разбанен.')
else:
await ctx.send(f'{ctx.author.mention}, у вас нет роли <@&1060542125621649458>.')
def setup(bot):
bot.add_cog(BanCommands(bot))
-22
View File
@@ -1,22 +0,0 @@
import asyncio
import random
import disnake
from disnake.ext import commands
class Coins(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.slash_command(name="монетка", description='Команда, которая возвращает орла или решку.')
async def coins(self, ctx: disnake.ApplicationCommandInteraction):
coin = ["Орел", "Решка"]
result = random.choice(coin)
await ctx.send(f"Орел или решка? Угадайте! Результат будет через 3 секунды...")
await asyncio.sleep(3)
await ctx.edit_original_response(f"Результат: {result}!")
def setup(bot):
bot.add_cog(Coins(bot))
+21
View File
@@ -0,0 +1,21 @@
import asyncio
import random
import disnake
from disnake.ext import commands
class CoinsCommand(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.slash_command()
async def coins(self, ctx: disnake.AppCommandInteraction):
coin = ["Орел", "Решка"]
result = random.choice(coin)
await ctx.send("Орел или решка? Угадайте! Результат будет через 3 секунды...")
await asyncio.sleep(3)
await ctx.edit_original_response(content=f"Результат: {result}!")
def setup(bot):
bot.add_cog(CoinsCommand(bot))
+10 -7
View File
@@ -2,19 +2,22 @@ import disnake
from disnake.ext import commands
class Help1(commands.Cog):
class HelpCommand(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.slash_command()
async def commands(self, ctx):
async def commands(self, ctx: disnake.AppCommandInteraction):
embed = disnake.Embed(title="Помощь по командам", description="Вот список всех моих команд и их описания:")
embed.add_field(name="$help", value="Показывает список всех доступных команд.")
embed.add_field(name="$ping", value="Проверка работоспособности бота.")
embed.add_field(name="$coins", value="Игра Орел и Решка.")
embed.add_field(name="$mute", value="Выдает мут участнику на определенное время.")
embed.add_field(name="/help", value="Показывает список всех доступных команд.")
embed.add_field(name="/ping", value="Проверка работоспособности бота.")
embed.add_field(name="/coins", value="Игра Орел и Решка.")
embed.add_field(name="/ball", value="Даёт верные ответы на все ваши вопросы.")
embed.add_field(name="/math", value="Можно решить любые математические примеры.")
embed.add_field(name="/ticket", value="Создает тикет")
embed.add_field(name="/dog", value="Показывает фото случайной собаки.")
await ctx.send(embed=embed)
def setup(bot):
bot.add_cog(Help1(bot))
bot.add_cog(HelpCommand(bot))
+20
View File
@@ -0,0 +1,20 @@
import disnake
import requests
from disnake.ext import commands
class DogCommands(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.slash_command()
async def dog(self, ctx: disnake.AppCommandInteraction):
response = requests.get('https://dog.ceo/api/breeds/image/random')
img_url = response.json()['message']
embed = disnake.Embed(title='Случайная собака', color=0x00ff00)
embed.set_image(url=img_url)
await ctx.send(embed=embed)
def setup(bot):
bot.add_cog(DogCommands(bot))
+5 -5
View File
@@ -1,14 +1,14 @@
import random
import disnake
from disnake.ext import commands
class MagicBall(commands.Cog):
class MagicBallCommand(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.slash_command()
async def ask_a_ball(self, ctx, *, question):
@commands.slash_command(description="Даёт верные ответы на все ваши вопросы.")
async def ball(self, ctx: disnake.AppCommandInteraction, *, question):
answers = [
"Я не знаю.",
"Да.",
@@ -20,4 +20,4 @@ class MagicBall(commands.Cog):
def setup(bot):
bot.add_cog(MagicBall(bot))
bot.add_cog(MagicBallCommand(bot))
+19
View File
@@ -0,0 +1,19 @@
import disnake
from disnake.ext import commands
class MathCommands(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.slash_command()
async def math(self, ctx: disnake.AppCommandInteraction, *, equation):
try:
result = eval(equation)
await ctx.send(f'Задача: {equation} = {result}')
except:
await ctx.send('Ошибка при выполнении вычислений.')
def setup(bot):
bot.add_cog(MathCommands(bot))
-15
View File
@@ -1,15 +0,0 @@
from disnake.ext import commands
class Ping(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.has_any_role(1091637465858715648)
@commands.slash_command()
async def ping(self, interaction):
await interaction.response.send_message("Понг!")
def setup(bot):
bot.add_cog(Ping(bot))
+22
View File
@@ -0,0 +1,22 @@
import disnake
from disnake.ext import commands
class PingCommands(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.has_any_role(1091637465858715648)
@commands.slash_command()
async def ping(self, ctx: disnake.AppCommandInteraction):
if disnake.utils.get(ctx.author.roles, id=1091637465858715648):
if ctx.channel.id == 1060544039767789639:
await ctx.send("Понг!")
else:
await ctx.send('Вы не можете использовать эту команду в текущем канале.')
else:
await ctx.send(f'{ctx.author.mention}, у вас нет роли <@&1060541642450411560>.')
def setup(bot):
bot.add_cog(PingCommands(bot))
-32
View File
@@ -1,32 +0,0 @@
import asyncio
import disnake
from disnake.ext import commands
class Mute(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.slash_command()
@commands.has_permissions(manage_roles=True)
async def mute(self, ctx, member: disnake.Member, time: int, *, reason=None):
guild = ctx.guild
muted_role = disnake.utils.get(guild.roles, name="Muted")
if not muted_role:
muted_role = await guild.create_role(name="Muted")
# Проверка роли на каждый чат
for channel in guild.channels:
await channel.set_permissions(muted_role, speak=False, send_messages=False)
await member.add_roles(muted_role, reason=reason)
await ctx.send(f"{member.mention} был замучен на {time} секунд. Причина: {reason}.")
await asyncio.sleep(time)
await member.remove_roles(muted_role)
await ctx.send(f"{member.mention} больше не замучен.")
def setup(bot):
bot.add_cog(Mute(bot))
+50
View File
@@ -0,0 +1,50 @@
import asyncio
import disnake
from disnake.ext import commands
class MuteCommands(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.slash_command(description="Заглушает по всему серверу на указанное время.")
@commands.has_permissions(manage_roles=True)
async def mute(self, ctx: disnake.AppCommandInteraction, member: disnake.Member, time: int, *, reason=None):
if disnake.utils.get(ctx.author.roles, id=1060541642450411560):
guild = ctx.guild
mutedRole = disnake.utils.get(guild.roles, name="Muted")
if not mutedRole:
mutedRole = await guild.create_role(name="Muted")
# Проверка роли на каждый чат
for channel in guild.channels:
await channel.set_permissions(mutedRole, speak=False, send_messages=False)
await member.add_roles(mutedRole, reason=reason)
await ctx.send(f"{member.mention} был замучен на {time} секунд. Причина: {reason}.")
await asyncio.sleep(time)
await member.remove_roles(mutedRole)
await ctx.send(f"{member.mention} больше не замучен.")
else:
await ctx.send(f'{ctx.author.mention}, у вас нет роли <@&1060541642450411560>.')
@commands.slash_command(description="Снимает мут с указанного пользователя.")
@commands.has_permissions(manage_roles=True)
async def unmute(self, ctx: disnake.AppCommandInteraction, member: disnake.Member):
if disnake.utils.get(ctx.author.roles, id=1060541642450411560):
mutedRole = disnake.utils.get(ctx.guild.roles, name="Muted")
if mutedRole not in member.roles:
await ctx.send(f"{member.mention} не замучен.")
return
await member.remove_roles(mutedRole)
await ctx.send(f"{member.mention} больше не замучен.")
else:
await ctx.send(f'{ctx.author.mention}, у вас нет роли <@&1060541642450411560>.')
def setup(bot):
bot.add_cog(MuteCommands(bot))
+39
View File
@@ -0,0 +1,39 @@
import disnake
from disnake.ext import commands
class TicketsCommand(commands.Cog):
def __init__(self, bot):
self.bot = bot
ticket_channel = None
@commands.slash_command()
@commands.has_permissions(manage_channels=True)
async def ticket(self, ctx: disnake.AppCommandInteraction):
global ticket_channel
overwrites = {
ctx.guild.default_role: disnake.PermissionOverwrite(read_messages=False),
ctx.author: disnake.PermissionOverwrite(read_messages=True),
ctx.guild.me: disnake.PermissionOverwrite(read_messages=True)
}
try:
ticket_channel = await ctx.guild.create_text_channel(name=f'ticket-{ctx.author.display_name}',
overwrites=overwrites)
await ctx.send(f'{ctx.author.mention}, тикет создан: {ticket_channel.mention}')
except:
await ctx.send('Ошибка при создании канала. Пожалуйста, попробуйте позже.')
@commands.slash_command()
@commands.has_permissions(manage_channels=True)
async def close_ticket(self, ctx: disnake.AppCommandInteraction):
global ticket_channel
if ticket_channel:
await ticket_channel.delete()
await ctx.send('Тикет закрыт.')
else:
await ctx.send('Тикет не был создан.')
def setup(bot):
bot.add_cog(TicketsCommand(bot))
+115 -11
View File
@@ -1,5 +1,6 @@
import json
import os
import settings
import disnake
from disnake.ext import commands
@@ -13,32 +14,135 @@ async def on_ready():
@bot.command()
@commands.has_guild_permissions(
administrator=True) # administrator=True - значит что использовать команду может человек только с правом администратора
async def setmoderator(ctx, member: disnake.Member):
async def secret(ctx):
await ctx.message.delete()
await ctx.send(f'Привет, {ctx.author.mention}. Это тайное сообщение!')
@bot.command()
async def news(ctx):
# Ваш код для получения новостей
page_news = [
{'title': 'В России началась вакцинация от COVID-19', 'description': 'Правительство России объявило о начале '
'кампании по вакцинации людей от '
'COVID-19.'},
{'title': 'Космический корабль SpaceX вернулся на Землю', 'description': 'Космический корабль SpaceX Crew '
'Dragon вернулся на Землю после '
'успешного запуска в космос.'},
{'title': 'Главный тренер "Манчестер Юнайтед" уволен', 'description': 'Главный тренер "Манчестер Юнайтед" был '
'уволен после непродолжительной карьеры'
' в этой команде.'}
]
# Создание встроенного сообщения с новостями
embed = disnake.Embed(title='Новости', color=0xff8800)
for i, new in enumerate(page_news):
embed.add_field(name=f'{i + 1}. {new["title"]}', value=f'{new["description"]}\n\u200b', inline=False)
# Отправка сообщения с встроенным сообщением
await ctx.send(embed=embed)
@bot.command()
@commands.has_guild_permissions(administrator=True)
async def set_moderator(ctx: disnake.AppCommandInteraction, member: disnake.Member):
member = member or ctx.message.author
guild = bot.get_guild(1060537877982887957)
role = guild.get_role(1060541642450411560)
await member.add_roles(role)
await ctx.send(f"Пользователю {member.mention} была выдана роль {role.mention}")
@bot.command()
@commands.has_guild_permissions(
administrator=True) # administrator=True - значит что использовать команду может человек только с правом администратора
async def dellmoderator(ctx, member: disnake.Member, moder_level: int):
@commands.has_guild_permissions(administrator=True)
async def dellmoderator(ctx: disnake.AppCommandInteraction, member: disnake.Member):
member = member or ctx.message.author
guild = bot.get_guild(1060537877982887957)
role = guild.get_role(1060541642450411560)
await member.remove_roles(role)
await ctx.send(f"Пользователю {member.mention} была снята роль {role.mention}")
def save_data(user, data):
with open(f'./users/{user.id}.json', 'w') as file:
json.dump(data, file)
# Функция загрузки данных пользователя из файла JSON
def load_data(user):
try:
with open(f'./users/{user.id}.json', 'r') as file:
return json.load(file)
except FileNotFoundError:
return None
# Создание команды регистрации
@bot.command()
async def register(ctx: disnake.AppCommandInteraction, name):
# Проверка, был ли пользователь уже зарегистрирован
data = load_data(ctx.author)
if data is not None:
await ctx.send('Вы уже зарегистрированы')
return
# Создание данных пользователя и сохранение их в файл JSON
data = {'name': name, 'coins': 0}
save_data(ctx.author, data)
await ctx.send(f'{ctx.author.mention}, вы были зарегистрированы')
# Создание команды для просмотра баланса
@bot.command()
async def balance(ctx):
# Загрузка данных пользователя из файла JSON
data = load_data(ctx.author)
# Проверка, зарегистрирован ли пользователь
if data is None:
await ctx.send(f'{ctx.author.mention}, вы не зарегистрированы')
return
await ctx.send(f'{ctx.author.mention}, ваш текущий баланс: {data["coins"]}')
@bot.command()
async def pay(ctx: disnake.AppCommandInteraction, recipient: disnake.User, amount: int):
# Загрузка данных отправителя из файла JSON
sender_data = load_data(ctx.author)
# Проверка, зарегистрирован ли отправитель
if sender_data is None:
await ctx.send(f'{ctx.author.mention}, вы не зарегистрированы')
return
# Проверка, что у отправителя достаточно средств
if sender_data['coins'] < amount:
await ctx.send(f'{ctx.author.mention}, недостаточно средств')
return
# Загрузка данных получателя из файла JSON
recipient_data = load_data(recipient)
# Проверка, зарегистрирован ли получатель
if recipient_data is None:
await ctx.send(f'{recipient.mention} не зарегистрирован')
return
# Обновление баланса отправителя и получателя
sender_data['coins'] -= amount
recipient_data['coins'] += amount
# Сохранение данных отправителя и получателя в файлах JSON
save_data(ctx.author, sender_data)
save_data(recipient, recipient_data)
await ctx.send(f'{ctx.author.mention} перевел {recipient.mention} {amount} монет!')
for filename in os.listdir("./cogs"):
if filename.endswith(".py"):
bot.load_extension(f"cogs.{filename[:-3]}")
bot.run(settings.discord_token)
bot.run("MTA5ODk5MzExMjI5NjE5NDA3MA.GUj8WN.16iwjYtaouRXbsfJhCi1U7fa75ehLFb7YRbEnU")
-1
View File
@@ -1 +0,0 @@
discord_token = "MTA5ODk5MzExMjI5NjE5NDA3MA.GUj8WN.16iwjYtaouRXbsfJhCi1U7fa75ehLFb7YRbEnU"
+1
View File
@@ -0,0 +1 @@
{"name": "localhost", "coins": 0}