Skip to content

Instantly share code, notes, and snippets.

@moking55
Last active October 6, 2021 12:21
Show Gist options
  • Save moking55/fee839c2f6d67de37c4473214d818a41 to your computer and use it in GitHub Desktop.
Save moking55/fee839c2f6d67de37c4473214d818a41 to your computer and use it in GitHub Desktop.
Simple Discord music bot with voice recognition
from youtube_search import YoutubeSearch
import speech_recognition as sr
import json, discord, youtube_dl
from discord.ext import commands
from discord.utils import get
import asyncio
YTDL_OPTIONS = {
'format':
'bestaudio/best',
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '192',
}],
'noplaylist': True,
'nocheckcertificate': True,
}
FFMPEG_OPTIONS = {'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn'}
bot = commands.Bot(command_prefix='>')
@bot.event
async def on_ready():
print(f"We have logged in as {bot.user}")
await bot.change_presence(
activity=discord.Activity(type=discord.ActivityType.listening,
name=f"{bot.command_prefix}listen"))
print(discord.__version__)
@bot.command()
async def listen(ctx):
# is command author in voice channel
if not ctx.message.author.voice:
await ctx.send('เข้าห้องเสียงเพื่อเปิดเพลงครับ')
return
# get user voice channel id
channel = ctx.message.author.voice.channel
r = sr.Recognizer()
with sr.Microphone() as source, youtube_dl.YoutubeDL(YTDL_OPTIONS) as ydl:
print('Hearing the voice')
await ctx.send("พูดชื่อเพลงที่อยากฟังเลยครับ!")
r.adjust_for_ambient_noise(source, duration=0.2)
try:
audio = r.listen(source)
text = r.recognize_google(audio, language='th')
results = YoutubeSearch(text, max_results=1).to_json()
# Save search results to json
f = open("data.json", "w")
f.write(results)
f.close()
# command is correct
print('Got the voice command')
await ctx.send("ได้รับคำสังแล้วครับ!")
# Decode result to json format
results = json.loads(results)
final_result = "https://youtu.be" + results['videos'][0][
'url_suffix']
# connect to voice channel
voice_client = await channel.connect()
# download youtube file
file = ydl.extract_info(final_result, download=False)
# Final: Play music on voice channel
voice_client.play(discord.FFmpegPCMAudio(str(file['url']), **FFMPEG_OPTIONS))
voice_client.source = discord.PCMVolumeTransformer(voice_client.source, 1)
print('Music playing successfully')
await ctx.send(f"ตอนนี้กำลังเล่นเพลง **{results['videos'][0]['title']}**")
while voice_client.is_playing():
await asyncio.sleep(1)
else:
await voice_client.disconnect()
print("Disconnected")
except Exception as e:
print(e)
print("Voice command cancelled or bot error")
await ctx.send("ไม่ได้ยินเสียงเลยช่วยพูดใหม่ได้ไหมครับ")
@bot.command()
async def stop(ctx):
voice = get(bot.voice_clients, guild=ctx.guild)
if voice.is_playing():
voice.stop()
print("Music stop by user")
await ctx.send('กำลังหยุดเพลง...')
# bot token
bot.run('Token')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment