This commit is contained in:
2022-07-02 20:15:43 +03:00
committed by Slava
parent bab5d68a88
commit 04fadbab7a
5 changed files with 121 additions and 98 deletions

View File

@@ -1,8 +1,9 @@
import logging import logging
import lib
from os import path, makedirs, rename, remove from os import path, makedirs, rename, remove
from discord.ext import commands
from disnake.ext import commands
import lib
class Audio(commands.Cog): class Audio(commands.Cog):
@@ -34,7 +35,8 @@ class Audio(commands.Cog):
await at.save(f'tmp/{user.id}/{at.filename}') await at.save(f'tmp/{user.id}/{at.filename}')
guess = mimetypes.guess_type(f'tmp/{user.id}/{at.filename}') guess = mimetypes.guess_type(f'tmp/{user.id}/{at.filename}')
if guess[0]: await ctx.reply(f'it`s {guess}')
if guess[0].split('/')[0] == 'audio':
from pymediainfo import MediaInfo from pymediainfo import MediaInfo
file = f'tmp/{user.id}/{at.filename}' file = f'tmp/{user.id}/{at.filename}'
duration = round(MediaInfo.parse(file).tracks[0].duration / 1000) duration = round(MediaInfo.parse(file).tracks[0].duration / 1000)
@@ -50,13 +52,13 @@ class Audio(commands.Cog):
lib.DB.add_audio(ctx.guild.id, user.id, audiolist) lib.DB.add_audio(ctx.guild.id, user.id, audiolist)
rename(f'tmp/{user.id}/{at.filename}', f'audio/{user.id}/{at.filename}') rename(f'tmp/{user.id}/{at.filename}', f'audio/{user.id}/{at.filename}')
else: elif guess[0].split('/')[0] != 'audio':
await ctx.reply(f'Failed to find MIME type of {at.filename}', ephemeral=True) await ctx.reply(f'It not audio {at.filename}\n it`s {guess[0]}')
remove(f'tmp/{user.id}/{at.filename}') remove(f'tmp/{user.id}/{at.filename}')
else: else:
await ctx.reply("Has no Attachment", ephemeral=True) await ctx.reply("Has no Attachment")
else: else:
await ctx.reply(f'You`re not admin. You can add audio only for your own account', ephemeral=True) await ctx.reply(f'You`re not admin. You can add audio only for your own account')
def setup(bot): # an extension must have a setup function def setup(bot): # an extension must have a setup function

View File

@@ -1,12 +1,10 @@
import logging import logging
import dislash import disnake
from disnake import Option, OptionType
from disnake.ext import commands
import lib import lib
import discord
from discord.ext import commands
from dislash import Option, OptionType, slash_command
class General(commands.Cog): class General(commands.Cog):
@@ -36,29 +34,29 @@ class General(commands.Cog):
if bot_role and guest_role: if bot_role and guest_role:
if member.bot == 0: if member.bot == 0:
role = discord.utils.get(member.guild.roles, id=guest_role) role = disnake.utils.get(member.guild.roles, id=guest_role)
else: else:
role = discord.utils.get(member.guild.roles, id=bot_role) role = disnake.utils.get(member.guild.roles, id=bot_role)
logging.info(f"Adding to {member} role {role}") logging.info(f"Adding to {member} role {role}")
await member.add_roles(role) await member.add_roles(role)
@commands.Cog.listener() @commands.Cog.listener()
async def on_member_update(self, before: discord.Member, after: discord.Member): async def on_member_update(self, before: disnake.Member, after: disnake.Member):
sql_update_query = f"""UPDATE "{after.guild.id}" set nick = ? where userid = ?""" sql_update_query = f"""UPDATE "{after.guild.id}" set nick = ? where userid = ?"""
data_tuple = (after.nick, before.id) data_tuple = (after.nick, before.id)
lib.DB.work_with_db(sql_update_query, data_tuple) lib.DB.work_with_db(sql_update_query, data_tuple)
@slash_command( @commands.slash_command(
name="info", name="info",
description="Read list of tracks for user", description="Read list of tracks for user",
options=[ options=[
Option("user", "Specify any user", OptionType.USER), Option("user", "Specify any user", OptionType.user),
] ]
) )
async def info(self, ctx, user=None): async def info(self, inter, user=None):
user = user or ctx.author user = user or inter.author
audio = lib.DB.read_db(ctx.guild.id, user.id) audio = lib.DB.read_db(inter.guild.id, user.id)
rolelist = [r.mention for r in user.roles if r != ctx.guild.default_role] rolelist = [r.mention for r in user.roles if r != inter.guild.default_role]
if rolelist: if rolelist:
roles = "\n".join(rolelist) roles = "\n".join(rolelist)
else: else:
@@ -69,27 +67,26 @@ class General(commands.Cog):
else: else:
audios = "" + "\n".join(sorted(audio.split(", "))) audios = "" + "\n".join(sorted(audio.split(", ")))
emb = discord.Embed( emb = disnake.Embed(
title=f"General information", title=f"General information",
description=f"General information on server about {user}", description=f"General information on server about {user}"
icon=user.avatar_url
) )
emb.set_thumbnail(url=user.avatar_url) emb.set_thumbnail(url=user.avatar.url)
emb.add_field(name="General info", emb.add_field(name="General info",
value=f"Username: {user}\n" value=f"Username: {user}\n"
f"Nickname: {user.nick}\n" f"Nickname: {user.nick}\n"
f"Joined at: {user.joined_at.strftime('%A, %B %d %Y @ %H:%M:%S')}", inline=False) f"Joined at: {user.joined_at.strftime('%A, %B %d %Y @ %H:%M:%S')}", inline=False)
emb.add_field(name="Audio list", value=f"{audios}", inline=True) emb.add_field(name="Audio list", value=f"{audios}", inline=True)
emb.add_field(name="Roles list", value=f"{roles}", inline=True) emb.add_field(name="Roles list", value=f"{roles}", inline=True)
emb.set_footer(text="Information requested by: {}".format(ctx.author.display_name)) emb.set_footer(text="Information requested by: {}".format(inter.author.display_name))
await ctx.reply(embed=emb, ephemeral=True) await inter.response.send_message(embed=emb, ephemeral=True)
@slash_command( @commands.slash_command(
name="set_guest_role", name="set_guest_role",
description="Set Default bot role", description="Set Default bot role",
options=[ options=[
Option("role", "Specify role", OptionType.ROLE, required=True), Option("role", "Specify role", OptionType.role, required=True),
] ]
) )
@commands.has_permissions(administrator=True) @commands.has_permissions(administrator=True)
@@ -101,47 +98,62 @@ class General(commands.Cog):
@commands.has_permissions(administrator=True) @commands.has_permissions(administrator=True)
async def command_set_prefix(self, ctx, prefix: str): async def command_set_prefix(self, ctx, prefix: str):
await lib.Commands.set_prefix(ctx, prefix) await lib.Commands.set_prefix(ctx, prefix)
await ctx.reply(f"Prefix set to: `{prefix}`")
@slash_command( @commands.slash_command(
name="set_prefix", name="set_prefix",
description="Setting up bot prefix", description="Setting up bot prefix",
options=[ options=[
Option("prefix", "Specify prefix", OptionType.STRING, required=True), Option("prefix", "Specify prefix", OptionType.string, required=True),
]
)
@dislash.has_permissions(administrator=True)
async def slash_set_prefix(self, ctx, prefix: str):
await lib.Commands.set_prefix(ctx, prefix)
@slash_set_prefix.error
@command_set_prefix.error
async def set_prefix_error(self, ctx, prefix):
await ctx.reply('You don`t have permissions', ephemeral=True)
@slash_command(
name="set_trigger_role",
description="Setting up role to trigger bot",
options=[
Option("role", "Specify role", OptionType.ROLE, required=True),
] ]
) )
@commands.has_permissions(administrator=True) @commands.has_permissions(administrator=True)
async def set_trigger_role(self, ctx, role): async def slash_set_prefix(self, inter, prefix: str):
await lib.Commands.write_json(ctx.guild.id, "tigger_role", role.id) await lib.Commands.set_prefix(inter, prefix)
await ctx.send(f"Role to trigger set to : `{role.name}`", ephemeral=True) await inter.responce.send_message(f"Prefix set to: `{prefix}`", ephemeral=True)
@slash_command( @slash_set_prefix.error
async def set_prefix_error(self, inter, prefix):
await inter.response.send_message('You don`t have permissions', ephemeral=True)
@commands.slash_command(
name="set_trigger_role",
description="Setting up role to trigger bot",
options=[
Option("role", "Specify role", OptionType.role, required=True),
]
)
@commands.has_permissions(administrator=True)
async def set_trigger_role(self, inter, role):
await lib.Commands.write_json(inter.guild.id, "tigger_role", role.id)
await inter.responce.send(f"Role to trigger set to : `{role.name}`", ephemeral=True)
@commands.slash_command(
name="set_bot_role", name="set_bot_role",
description="Set Default bot role", description="Set Default bot role",
options=[ options=[
Option("role", "Specify role", OptionType.ROLE, required=True), Option("role", "Specify role", OptionType.role, required=True),
] ]
) )
@dislash.has_permissions(administrator=True) @commands.has_permissions(administrator=True)
async def set_bot_role(self, ctx, role): async def set_bot_role(self, ctx, role):
await lib.Commands.write_json(ctx.guild.id, "bot_role", role.id) await lib.Commands.write_json(ctx.guild.id, "bot_role", role.id)
await ctx.send(f"Setted up bot role to: `{role.name}`", ephemeral=True) await ctx.send(f"Setted up bot role to: `{role.name}`", ephemeral=True)
@commands.slash_command()
async def help(self, inter):
embed = disnake.Embed(
title='Help', description='', colour=disnake.Colour.blue())
embed.set_footer(text='Have fun!')
embed.add_field(
name='Prefix',
value=
f'The current prefix for this server is {self.bot.command_prefix}',
inline=True)
await inter.response.send_message(embed=embed)
def setup(bot): # an extension must have a setup function def setup(bot): # an extension must have a setup function
bot.add_cog(General(bot)) # adding a cog bot.add_cog(General(bot)) # adding a cog

View File

@@ -1,11 +1,10 @@
import logging import logging
import discord import disnake
from discord.ext import commands from disnake.ext import commands
from dislash import slash_command
class Bot_info(commands.Cog): class Bot_info(commands.Cog, name='Bot Info'):
def __init__(self, bot): def __init__(self, bot):
self.bot = bot # defining bot as global var in class self.bot = bot # defining bot as global var in class
@@ -13,17 +12,21 @@ class Bot_info(commands.Cog):
async def on_ready(self): async def on_ready(self):
logging.info(f'Cog {__name__.split(".")[1]} is ready!.') logging.info(f'Cog {__name__.split(".")[1]} is ready!.')
@slash_command(name="info_bot") # this is for making a command @commands.slash_command(name="info_bot") # this is for making a command
async def info_bot(self, ctx): async def info_bot(self, inter):
# await ctx.send(f'Pong! {round(self.bot.latency * 1000)}') # await ctx.send(f'Pong! {round(self.bot.latency * 1000)}')
emb = discord.Embed( emb = disnake.Embed(
title=f"General information", title=f"General information",
description=f"General information on about bot", description=f"General information on about bot",
) )
# emb.set_thumbnail(self.bot.avatar.url)
emb.add_field(name="Bot ping", value=f'Bot ping: {round(self.bot.latency * 1000)}', inline=True) emb.add_field(name="Bot ping", value=f'Bot ping: {round(self.bot.latency * 1000)}', inline=True)
emb.set_footer(text="Information requested by: {}".format(ctx.author.display_name)) emb.set_footer(text="Information requested by: {}".format(inter.author.display_name))
await inter.response.send_message(embed=emb, ephemeral=True)
await ctx.reply(embed=emb, ephemeral=True)
def setup(bot): # an extension must have a setup function def setup(bot): # an extension must have a setup function

33
lib.py
View File

@@ -90,16 +90,15 @@ class CogsPrepare:
class Commands: class Commands:
@staticmethod @staticmethod
def chech_json(): def check_json():
if not path.isfile('prefix.json'): if not path.isfile('prefix.json'):
with open('prefix.json', 'w+') as f: with open('prefix.json', 'w+', encoding='utf-8') as f:
f.write("") f.write("")
f.close() f.close()
@staticmethod @staticmethod
async def set_prefix(ctx, prefix: str): async def set_prefix(inter, prefix: str):
await Commands.write_json(ctx.guild.id, "prefix", prefix) await Commands.write_json(inter.guild.id, "prefix", prefix)
await ctx.send(f"Prefix set to: `{prefix}`", ephemeral=True)
@staticmethod @staticmethod
def list_files(fold: str): def list_files(fold: str):
@@ -135,7 +134,7 @@ class Commands:
@staticmethod @staticmethod
async def write_json(guild: int, param_name: str, param: str or int): async def write_json(guild: int, param_name: str, param: str or int):
with open('prefix.json', 'r') as _f: with open('prefix.json', 'r', encoding='utf-8') as _f:
try: try:
_json = json.load(_f) _json = json.load(_f)
except json.decoder.JSONDecodeError: except json.decoder.JSONDecodeError:
@@ -148,23 +147,23 @@ class Commands:
_guild = _json[f'{guild}'] _guild = _json[f'{guild}']
_guild.update({f'{param_name}': f'{param}'}) _guild.update({f'{param_name}': f'{param}'})
with open('prefix.json', 'w') as _f: with open('prefix.json', 'w', encoding='utf-8') as _f:
json.dump(_json, _f, indent=4) json.dump(_json, _f, indent=4)
_f.close() _f.close()
@staticmethod @staticmethod
def determine_prefix(bot, msg): def determine_prefix(bot, msg):
guild = msg.guild
with open('prefix.json', 'r', encoding='utf-8') as fp: # Open the JSON with open('prefix.json', 'r', encoding='utf-8') as fp: # Open the JSON
parameter = DEFAULT_PREFIX parameter: str
try: try:
_json = json.load(fp) # Load the custom prefixes from json import load
except error: _json = load(fp) # Load the custom prefixes
except:
_json = {} _json = {}
if guild: # If the guild exists if msg.guild: # If the guild exists
try: try:
parameter = _json[f"{guild.id}"]["prefix"] # Read prefix from json if is setted up parameter = _json[f"{msg.guild.id}"]["prefix"] # Read prefix from json if is setted up
except error: except:
pass parameter = DEFAULT_PREFIX
return parameter print(parameter)
return parameter

43
test.py
View File

@@ -1,26 +1,28 @@
import json
import logging import logging
import sys import sys
import threading import threading
import discord
import disnake
from disnake import OptionChoice, OptionType, Option
from disnake.ext import commands
import lib import lib
from os import path
from discord.ext import commands
from dislash import InteractionClient, Option, OptionType, OptionChoice
bot_owner = 386629192743256065 bot_owner = 386629192743256065
lib.Commands.check_json()
lib.Commands.chech_json() intents = disnake.Intents(messages=True, guilds=True, message_content=True)
intents = discord.Intents.default()
intents.members = True intents.members = True
bot = commands.Bot(command_prefix=lib.Commands.determine_prefix, guild_subscriptions=True, intents=intents)
inter_client = InteractionClient(bot, sync_commands=True) bot = commands.Bot(command_prefix=lib.Commands.determine_prefix,
intents=intents,
status=disnake.Status.idle,
reload=True,
test_guilds=[929446191270330410, 987120286933602354])
threading.current_thread().name = "main" threading.current_thread().name = "main"
logging.basicConfig(stream=sys.stdout, filemode='w', level='INFO', logging.basicConfig(stream=sys.stdout, filemode='w', level='INFO',
format='%(asctime)s - %(levelname)s - %(threadName)s - %(message)s') format='%(asctime)s - %(levelname)s - %(threadName)s - %(message)s')
for filename in lib.CogsPrepare.cog_list(): for filename in lib.CogsPrepare.cog_list():
try: try:
bot.load_extension(f'cogs.{filename}') bot.load_extension(f'cogs.{filename}')
@@ -42,14 +44,19 @@ async def on_ready():
logging.info('We have logged in as {0.user}'.format(bot)) logging.info('We have logged in as {0.user}'.format(bot))
@inter_client.slash_command( @bot.command()
async def hello(inter):
await inter.response.reply('hello')
@bot.slash_command(
name="cog", name="cog",
description="Work with cogs", description="Work with cogs",
options=[ options=[
Option( Option(
"what_do", "what_do",
description="Specify what do with cogs", description="Specify what do with cogs",
type=OptionType.STRING, type=OptionType.string,
required=True, required=True,
choices=[ choices=[
OptionChoice("load", "load"), OptionChoice("load", "load"),
@@ -59,13 +66,13 @@ async def on_ready():
) )
] ]
) )
async def slash_cogs(ctx, what_do): async def slash_cogs(inter, what_do):
if ctx.author.id == bot_owner: if inter.author.id == bot_owner:
await lib.CogsPrepare.work_with_cogs(what_do, bot) await lib.CogsPrepare.work_with_cogs(what_do, bot)
await ctx.reply(f'Cogs are {what_do}ed', ephemeral=True) await inter.response.send_message(f'Cogs are {what_do}ed', ephemeral=True)
else: else:
await ctx.reply('You`re not bot owner', ephemeral=True) await inter.response.send_message('You`re not bot owner', ephemeral=True)
bot.run('OTQ3OTUzOTAxNzgzNjIxNjYy.GTXbMv.KrztaTO7-ivsPEAVjsyikSQ-GP-ANwULmDraig') bot.run('OTQ3OTUzOTAxNzgzNjIxNjYy.GTXbMv.KrztaTO7-ivsPEAVjsyikSQ-GP-ANwULmDraig')