Add autojoin feature

This commit is contained in:
2021-11-02 22:51:30 +01:00
parent eddc557f81
commit cdf848d87d
3 changed files with 78 additions and 28 deletions
+13 -2
View File
@@ -1,3 +1,5 @@
from typing import Optional
import discord import discord
from discord.ext import tasks, commands from discord.ext import tasks, commands
@@ -76,11 +78,20 @@ class InformationCog(commands.Cog, name="Information"):
) )
await ctx.send(fmt) await ctx.send(fmt)
from utils import database
database.AutoJoin.get_channels()
@commands.command(name="help", aliases=["about", "info"], slash_command=True) @commands.command(name="help", aliases=["about", "info"], slash_command=True)
@commands.cooldown(1, 1, commands.BucketType.user) @commands.cooldown(1, 1, commands.BucketType.user)
async def about(self, ctx: Context): async def about(
self,
ctx: Context,
command: Optional[str] = commands.Option(
description="Show help for a command or category"
),
):
"""ChristmasBot command list""" """ChristmasBot command list"""
if None: if command:
entity = self.bot.get_cog(command) or self.bot.get_command(command) entity = self.bot.get_cog(command) or self.bot.get_command(command)
if entity is None: if entity is None:
+45 -26
View File
@@ -1,5 +1,7 @@
import asyncio import asyncio
import re import re
from typing import Optional
from aioredis.client import Redis from aioredis.client import Redis
import discord import discord
@@ -11,6 +13,7 @@ from lavalink.models import AudioTrack, DefaultPlayer
from bot import ChristmasBot from bot import ChristmasBot
from utils.EmbedGenerator import EmbedGenerator from utils.EmbedGenerator import EmbedGenerator
from utils.database import AutoJoin
from context import CustomContext from context import CustomContext
from discord import Embed from discord import Embed
@@ -83,6 +86,46 @@ class Music(commands.Cog):
) )
self.bot.lavalink.add_event_hook(self.track_hook) self.bot.lavalink.add_event_hook(self.track_hook)
await self.async_init()
async def async_init(self):
redis_result = await AutoJoin.get_channels(self.bot._redis_client)
while len(self.bot.lavalink.node_manager.available_nodes) == 0:
await asyncio.sleep(1)
for guild_id, (voicechannel_id, textchannel_id) in redis_result.items():
player = self.bot.lavalink.player_manager.create(guild_id)
player.store('channel', textchannel_id)
voice_channel = await self.bot.fetch_channel(voicechannel_id)
await voice_channel.connect(cls=LavalinkVoiceClient)
if not player.is_playing:
await self.fill_player_queue(
player, self.bot.config["queue_buffer_size"]
)
await player.play()
textchannel = await self.bot.fetch_channel(textchannel_id)
await textchannel.send("Automatically joined the voice channel")
async def fill_player_queue(self, player: DefaultPlayer, buffer: Optional[int] = 1):
pipeline = self.bot._redis_client.pipeline()
for _ in range(buffer):
pipeline.randomkey()
queries = await pipeline.execute()
print(queries)
# Get the results for the query from Lavalink.
for query in queries:
result = await player.node.get_tracks(query)
print(result)
if not result or not result["tracks"]:
continue
track = lavalink.models.AudioTrack(
result["tracks"][0], self.bot.user.id, recommended=False
)
player.add(requester=self.bot.user.id, track=track)
def cog_unload(self): def cog_unload(self):
"""Cog unload handler. This removes any event hooks that were registered.""" """Cog unload handler. This removes any event hooks that were registered."""
@@ -173,38 +216,14 @@ class Music(commands.Cog):
) )
await channel.send(embed=embed) await channel.send(embed=embed)
elif isinstance(event, lavalink.events.TrackEndEvent): elif isinstance(event, lavalink.events.TrackEndEvent):
query = await self.bot._redis_client.randomkey() await self.fill_player_queue(event.player, 1)
result = await event.player.node.get_tracks(query)
if not result or not result["tracks"]:
return
track = lavalink.models.AudioTrack(
result["tracks"][0], self.bot.user.id, recommended=False
)
event.player.add(requester=self.bot.user.id, track=track)
@commands.command(name="connect", aliases=["p", "play", "join"]) @commands.command(name="connect", aliases=["p", "play", "join"])
async def play(self, ctx: CustomContext): async def play(self, ctx: CustomContext):
"""Starts playing Christmas bangers""" """Starts playing Christmas bangers"""
# Get the player for this guild from cache. # Get the player for this guild from cache.
player: DefaultPlayer = self.bot.lavalink.player_manager.get(ctx.guild.id) player: DefaultPlayer = self.bot.lavalink.player_manager.get(ctx.guild.id)
redis_client: Redis = ctx.get_redis() await self.fill_player_queue(player, self.bot.config["queue_buffer_size"])
pipeline = redis_client.pipeline()
for _ in range(self.bot.config["queue_buffer_size"]):
pipeline.randomkey()
queries = await pipeline.execute()
# Get the results for the query from Lavalink.
for query in queries:
result = await player.node.get_tracks(query)
if not result or not result["tracks"]:
continue
track = lavalink.models.AudioTrack(
result["tracks"][0], ctx.author.id, recommended=False
)
player.add(requester=ctx.author.id, track=track)
if not player.is_playing: if not player.is_playing:
await player.play() await player.play()
+20
View File
@@ -0,0 +1,20 @@
from aioredis import Redis
from typing import Sequence
class AutoJoin:
@staticmethod
async def get_channels(redis: Redis) -> Sequence[tuple]:
# return all channels
channels = await redis.hgetall(name="autojoin")
return {key: value.split("-") for key, value in channels.items()}
@staticmethod
async def update_channel(redis: Redis, guild_id, voicechannel_id, textchannel_id):
await redis.hset(
name="autojoin", key=guild_id, value=f"{voicechannel_id}-{textchannel_id}"
)
@staticmethod
async def del_channel(redis: Redis, guild_id):
await redis.hdel("autojoin", guild_id)