musicube/src/bot.py

57 lines
1.4 KiB
Python
Raw Normal View History

2021-09-24 21:05:12 +02:00
import os
2021-09-24 21:36:53 +02:00
import sys
from discord.ext import commands
2021-09-24 21:05:12 +02:00
from dotenv import load_dotenv
2021-09-24 21:17:56 +02:00
from yt import YTDLSource
2021-09-24 22:26:49 +02:00
from error import ErrorHandler
2021-09-24 21:17:56 +02:00
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)
2021-09-24 21:36:53 +02:00
ctx.voice_client.play(player, after=lambda e: print(f"Player error: {e}") if e else None)
2021-09-24 21:36:53 +02:00
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()
2021-09-24 22:03:03 +02:00
if __name__ == "__main__":
bot = commands.Bot(command_prefix=commands.when_mentioned_or("!"), description='Relatively simple music bot example')
2021-09-24 22:03:03 +02:00
@bot.event
async def on_ready():
print(f"Logged in as {bot.user} ({bot.user.id})")
print('------')
2021-09-24 22:03:03 +02:00
bot.add_cog(Music(bot))
2021-09-24 22:26:49 +02:00
bot.add_cog(ErrorHandler(bot))
2021-09-24 22:03:03 +02:00
token = os.environ.get("BOT_TOKEN", None)
if not token:
2021-09-24 22:03:28 +02:00
print("No token found in BOT_TOKEN")
2021-09-24 22:03:03 +02:00
sys.exit(1)
2021-09-24 21:05:12 +02:00
2021-09-24 22:03:03 +02:00
bot.run(token)