musicube/src/bot.py
2021-09-24 23:07:32 +02:00

57 lines
1.4 KiB
Python

import os
import sys
from discord.ext import commands
from dotenv import load_dotenv
from yt import YTDLSource
from error import ErrorHandler
load_dotenv()
class Music(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def stream(self, ctx, *, url):
async with ctx.typing():
player = await YTDLSource.from_url(url, loop=self.bot.loop, stream=True)
ctx.voice_client.play(player, after=lambda e: print(f"Player error: {e}") if e else None)
await ctx.send(f"Now playing: {player.title}")
@commands.command()
async def stop(self, ctx):
await ctx.voice_client.disconnect()
@stream.before_invoke
async def ensure_voice(self, ctx):
if ctx.voice_client is None:
if ctx.author.voice:
await ctx.author.voice.channel.connect()
else:
raise commands.CommandError("Author not connected to a voice channel.")
elif ctx.voice_client.is_playing():
ctx.voice_client.stop()
if __name__ == "__main__":
bot = commands.Bot(command_prefix=commands.when_mentioned_or("!"), description='Relatively simple music bot example')
@bot.event
async def on_ready():
print(f"Logged in as {bot.user} ({bot.user.id})")
print('------')
bot.add_cog(Music(bot))
bot.add_cog(ErrorHandler(bot))
token = os.environ.get("BOT_TOKEN", None)
if not token:
print("No token found in BOT_TOKEN")
sys.exit(1)
bot.run(token)