Merge pull request #10 from strNophix/redis-storage

Redis storage
This commit is contained in:
2021-11-04 22:20:59 +01:00
committed by GitHub
5 changed files with 29 additions and 23 deletions
+3 -4
View File
@@ -1,11 +1,9 @@
import asyncio
from aioredis.client import Redis from aioredis.client import Redis
import discord import discord
from discord import ActivityType from discord import ActivityType
from discord.colour import Color from discord.colour import Color
from discord.ext import commands, tasks from discord.ext import commands, tasks
import sys import sys
from signal import SIGINT, SIGTERM
import json import json
from typing import Any, Dict, List, Sequence from typing import Any, Dict, List, Sequence
from discord import Message from discord import Message
@@ -38,7 +36,6 @@ class ChristmasBot(commands.Bot):
self.initial_cog_names: List[str] = self.config.get("cogs", []) self.initial_cog_names: List[str] = self.config.get("cogs", [])
self.colors: Dict[str, Color] = self.process_colours(config.get("colors", [])) self.colors: Dict[str, Color] = self.process_colours(config.get("colors", []))
self._redis_client: Redis = aioredis.from_url( self._redis_client: Redis = aioredis.from_url(
self.config["redis_url"], encoding="utf-8", decode_responses=True self.config["redis_url"], encoding="utf-8", decode_responses=True
) )
@@ -110,6 +107,9 @@ class ChristmasBot(commands.Bot):
await self.change_presence(activity=activity) await self.change_presence(activity=activity)
config = json.load(open("config.json", "r", encoding="utf-8"))
redis_prefix = config["redis_prefix"]
if __name__ == "__main__": if __name__ == "__main__":
try: try:
import uvloop import uvloop
@@ -119,6 +119,5 @@ if __name__ == "__main__":
except ModuleNotFoundError: except ModuleNotFoundError:
pass pass
config = json.load(open("config.json", "r", encoding="utf-8"))
token = config.pop("token") token = config.pop("token")
ChristmasBot(config).run(token, reconnect=True) ChristmasBot(config).run(token, reconnect=True)
+2 -2
View File
@@ -11,6 +11,7 @@ import lavalink
from bot import ChristmasBot from bot import ChristmasBot
from utils.EmbedGenerator import EmbedGenerator from utils.EmbedGenerator import EmbedGenerator
from utils.paginator import HelpPaginator from utils.paginator import HelpPaginator
from utils.database import AutoJoin
class InformationCog(commands.Cog, name="Information"): class InformationCog(commands.Cog, name="Information"):
@@ -78,8 +79,7 @@ class InformationCog(commands.Cog, name="Information"):
) )
await ctx.send(fmt) await ctx.send(fmt)
from utils import database AutoJoin.get_channels()
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)
+4 -9
View File
@@ -2,8 +2,6 @@ import asyncio
import re import re
from typing import Optional from typing import Optional
from aioredis.client import Redis
import discord import discord
from discord.channel import TextChannel from discord.channel import TextChannel
from discord.ext.commands.context import Context from discord.ext.commands.context import Context
@@ -17,6 +15,8 @@ from utils.database import AutoJoin
from context import CustomContext from context import CustomContext
from discord import Embed from discord import Embed
from utils.database import Playlist
url_rx = re.compile(r"https?://(?:www\.)?.+") url_rx = re.compile(r"https?://(?:www\.)?.+")
@@ -96,7 +96,7 @@ class Music(commands.Cog):
for guild_id, (voicechannel_id, textchannel_id) in redis_result.items(): for guild_id, (voicechannel_id, textchannel_id) in redis_result.items():
player = self.bot.lavalink.player_manager.create(guild_id) player = self.bot.lavalink.player_manager.create(guild_id)
player.store('channel', textchannel_id) player.store("channel", textchannel_id)
voice_channel = await self.bot.fetch_channel(voicechannel_id) voice_channel = await self.bot.fetch_channel(voicechannel_id)
await voice_channel.connect(cls=LavalinkVoiceClient) await voice_channel.connect(cls=LavalinkVoiceClient)
if not player.is_playing: if not player.is_playing:
@@ -109,12 +109,7 @@ class Music(commands.Cog):
await textchannel.send("Automatically joined the voice channel") await textchannel.send("Automatically joined the voice channel")
async def fill_player_queue(self, player: DefaultPlayer, buffer: Optional[int] = 1): async def fill_player_queue(self, player: DefaultPlayer, buffer: Optional[int] = 1):
pipeline = self.bot._redis_client.pipeline() queries = await Playlist.random(self.bot._redis_client, buffer)
for _ in range(buffer):
pipeline.randomkey()
queries = await pipeline.execute()
print(queries)
# Get the results for the query from Lavalink. # Get the results for the query from Lavalink.
for query in queries: for query in queries:
result = await player.node.get_tracks(query) result = await player.node.get_tracks(query)
+2 -1
View File
@@ -3,6 +3,7 @@
"owner_ids": [194545408960102400, 190875175460405249], "owner_ids": [194545408960102400, 190875175460405249],
"prefixes": ["ck!"], "prefixes": ["ck!"],
"redis_url": "", "redis_url": "",
"redis_prefix": "",
"lavalink": { "lavalink": {
"host": "", "host": "",
"port": 2333, "port": 2333,
@@ -19,5 +20,5 @@
}, },
"cogs": ["cogs.owner", "cogs.settings", "cogs.information", "cogs.music"], "cogs": ["cogs.owner", "cogs.settings", "cogs.information", "cogs.music"],
"slash_command_guilds": [], "slash_command_guilds": [],
"queue_buffer_size": 5 "queue_buffer_size": 5,
} }
+18 -7
View File
@@ -1,20 +1,31 @@
from aioredis import Redis from aioredis import Redis
from typing import Sequence from typing import Dict, List, Optional
from bot import redis_prefix
class AutoJoin: class AutoJoin:
@staticmethod @staticmethod
async def get_channels(redis: Redis) -> Sequence[tuple]: async def get_channels(redis: Redis) -> Dict[str, str]:
# return all channels # return all channels
channels = await redis.hgetall(name="autojoin") channels = await redis.hgetall(f"{redis_prefix}:autojoin")
return {key: value.split("-") for key, value in channels.items()} return {key: value.split("-") for key, value in channels.items()}
@staticmethod @staticmethod
async def update_channel(redis: Redis, guild_id, voicechannel_id, textchannel_id): async def update_channel(
redis: Redis, guild_id: int, voice_channel_id: int, text_channel_id: int
):
await redis.hset( await redis.hset(
name="autojoin", key=guild_id, value=f"{voicechannel_id}-{textchannel_id}" f"{redis_prefix}:autojoin",
guild_id,
f"{voice_channel_id}-{text_channel_id}",
) )
@staticmethod @staticmethod
async def del_channel(redis: Redis, guild_id): async def del_channel(redis: Redis, guild_id: int):
await redis.hdel("autojoin", guild_id) await redis.hdel(f"{redis_prefix}:autojoin", guild_id)
class Playlist:
@staticmethod
async def random(redis: Redis, amount: Optional[int] = 1) -> List[str]:
return await redis.srandmember(f"{redis_prefix}:playlist", amount)