Skip to content

Instantly share code, notes, and snippets.

@yunkai1841
Created September 16, 2021 14:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yunkai1841/c0071e67b906bd5004bbd2aceeb96b55 to your computer and use it in GitHub Desktop.
Save yunkai1841/c0071e67b906bd5004bbd2aceeb96b55 to your computer and use it in GitHub Desktop.
discord music bot
import asyncio
import re
import json
import discord
from discord.ext import commands, tasks
from util import mp3_dl
BOT_TOKEN=""
bot = commands.Bot(command_prefix="!")
@bot.event
async def on_ready():
print(f"Logged in as {bot.user}")
@bot.command()
async def play(ctx: commands.Context, arg):
#check if arg is URL
URL_PATTERN = "https?://[\w/:%#\$&\?\(\)~\.=\+\-]+"
if not re.fullmatch(URL_PATTERN, arg):
ctx.send("""This is not URL
USAGE:
\t!play {YouTube URL}""")
return
await ctx.send(f"Downloading {arg}")
mp3_dl(arg)
await ctx.send(f"Download finish")
ctx.voice_client.play(discord.FFmpegPCMAudio("out.mp3"))
@bot.command()
async def join(ctx: commands.Context, *, arg):
channel = ctx.author.voice.channel
if channel is None:
return await ctx.send("ボイスチャンネルに接続していません")
await channel.connect()
bot.run(BOT_TOKEN)
import youtube_dl as ydl
def mp3_dl(url: str):
ydl_opts = {
'format': 'bestaudio/best',
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '96',
}],
'outtmpl': 'out.%(ext)s',
'noplaylist': True,
}
with ydl.YoutubeDL(ydl_opts) as dl:
dl.download([url])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment