toitadesBot/main.py
2023-05-08 15:03:50 +02:00

91 lines
2.4 KiB
Python
Executable File

#!/usr/bin/env python
import sys
import yt_dlp
import os
import io
import glob
import re
import discord
from pydub import AudioSegment
from discord.ext import commands
if len(sys.argv) < 2:
print("./main.py TOKEN")
exit(1)
sounds_folder = 'Sounds'
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix='>', intents=intents)
@bot.command()
async def list(ctx):
await ctx.send(listSounds())
@bot.command()
async def play(ctx, arg):
filepath = computePath(arg)
if os.path.isfile(filepath):
with open(filepath, mode='rb') as file:
await ctx.send(file=discord.File(file, filename=arg + ".mp3"))
else:
await ctx.send("connais pas " + arg)
@bot.command()
async def add(ctx, name, url, start, end):
downloadAndCutVideo(url, name, start, end)
await ctx.send("Téléchargé !")
@bot.command()
async def remove(ctx, name):
os.remove(computePath(name))
await ctx.send("salut mon pote !")
def listSounds():
soundLists = "```\n"
for file in glob.glob(sounds_folder + "/" + "*.mp3"):
filename = re.findall('Sounds\/(.*)\.mp3', file)[0]
soundLists += filename + "\n"
soundLists += "```\n"
return soundLists
def downloadAndCutVideo(url, filename, start = -1, end = -1):
if start == -1 and end == -1:
downloadVideo(url, filename)
return
start = int(start)
end = int(end)
tmpFilename = filename + "tmp"
downloadVideo(url, tmpFilename)
song = AudioSegment.from_mp3(computePath(tmpFilename))
if start != -1:
start = start * 1000
if end != -1:
end = end * 1000
cutted_song = song[start:end].export(computePath(filename), format="mp3")
os.remove(computePath(tmpFilename))
def downloadVideo(url, filename):
ydl_opts = {"format": "bestaudio", "outtmpl": sounds_folder + "/" + filename + ".%(ext)s"}
ydl_opts = {
'format': 'm4a/bestaudio/best',
'postprocessors': [{ # Extract audio using ffmpeg
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
}],
"outtmpl": sounds_folder + "/" + filename + ".%(ext)s"
}
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
ydl.download([url])
def computePath(filename):
return sounds_folder + '/' + filename + ".mp3"
bot.run(sys.argv[1])