Files
discord_bot/cogs/audio.py
2022-08-21 22:24:52 +03:00

88 lines
3.8 KiB
Python

import logging
import tempfile
from asyncio import sleep
from os import path, makedirs, rename, remove
from random import randrange
from disnake import FFmpegPCMAudio
from disnake.ext import commands
from lib.DB import read_db, check_exist_audio, add_audio
class Audio(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_ready(self):
logging.info(f'Cog {__name__.split(".")[1]} is ready!.')
@commands.Cog.listener()
async def on_voice_state_update(self, member, before, after):
from lib.Comands import read_json
role = await read_json(member.guild.id, 'tigger_role')
audio = await read_db(member.guild.id, member.id, 'usertracks')
from lib.Comands import list_files
audio_files = await list_files(f'audio/{member.id}')
f = await list_files()
if role is not None and before.channel is None and role in member.roles:
track = randrange(0, len(f) - 1, 1)
audio_source = FFmpegPCMAudio(f'audio/{f[track]}')
if not self.bot.voice_clients:
await sleep(1)
_channel = after.channel
vc = await after.channel.connect()
if not vc.is_playing():
vc.play(audio_source, after=None)
while vc.is_playing():
await sleep(0.5)
await sleep(1)
await vc.disconnect()
@commands.command(name="upload_audio")
async def upload_audio(self, ctx, user=None):
user = user or ctx.author
print(tempfile.tempdir)
if ctx.author.guild_permissions.administrator or user is ctx.author:
if ctx.message.attachments:
from os import error
if not path.isdir(f'audio/{user.id}'):
try:
makedirs(f'audio/{user.id}')
except error as _error:
pass
for at in ctx.message.attachments:
import mimetypes
await at.save(f'{tempfile.tempdir}/{tempfile.mkdtemp(dir=f"tmp/{user.id}")}/{at.filename}')
guess = mimetypes.guess_type(f'{tempfile.tempdir}/{user.id}/{at.filename}')
if guess[0].split('/')[0] == 'audio':
from pymediainfo import MediaInfo
file = f'{tempfile.tempdir}/{user.id}/{at.filename}'
duration = round(MediaInfo.parse(file).tracks[0].duration / 1000)
if duration > 15:
await ctx.reply(f'Audio duration is {duration}, but max is 15')
remove(f'{tempfile.tempdir}/{user.id}/{at.filename}')
else:
a = await read_db(ctx.guild.id, user.id, 'usertracks')
if a:
audiolist = a + ", " + f'{at.filename}'
else:
audiolist = f'{at.filename}'
await check_exist_audio(ctx, ctx.guild.id, user.id, 'usertracks', at.filename)
await add_audio(ctx.guild.id, user.id, audiolist)
rename(f'{tempfile.tempdir}/{user.id}/{at.filename}', f'audio/{user.id}/{at.filename}')
elif guess[0].split('/')[0] != 'audio':
await ctx.reply(f'It not audio {at.filename}\n it`s {guess[0]}')
remove(f'{tempfile.tempdir}/{user.id}/{at.filename}')
else:
await ctx.reply("Has no Attachment")
else:
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
bot.add_cog(Audio(bot)) # adding a cog