Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feature: add disk space voice channel #25

Merged
merged 12 commits into from
Jun 27, 2024
36 changes: 35 additions & 1 deletion src/discord/cogs/tasks.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,20 @@
import discord
from discord.ext import tasks, commands
import asyncio
from datetime import timedelta

from utils.custom_logger import logger
from utils.datetime import TimeCalculator
from src.trakt.functions import process_ratings, process_favorites
from config.globals import TRAKT_CHANNEL, TRAKT_USERNAME, ENABLE_DELAY
from src.linux.disk_space import get_disk_space
from config.globals import TRAKT_CHANNEL, TRAKT_USERNAME, ENABLE_DELAY, DISCORD_SERVER_ID

class TasksCog(commands.Cog):
def __init__(self, bot: commands.Bot) -> None:
self.bot = bot
self.trakt_ratings.start()
self.trakt_favorites.start()
self.update_disk_space_channel.start()

# Task to process recent Trakt ratings
@tasks.loop(minutes=60)
Expand All @@ -31,6 +34,37 @@ async def trakt_favorites(self):
except Exception as e:
logger.error(f'Error processing recent Trakt ratings: {e}')

# Task to update the disk space channel
@tasks.loop(hours=12)
async def update_disk_space_channel(self):
try:
space = get_disk_space()
guild_id = DISCORD_SERVER_ID
guild = await self.bot.fetch_guild(guild_id)

if guild is not None:
# Explicitly fetch channels to ensure we have the latest state
channels = await guild.fetch_channels()
# Log all channel names for debugging
logger.debug(f"All channels: {[channel.name for channel in channels]}")

# Look for a channel that starts with "HDD:"
disk_space_channel = next((channel for channel in channels if channel.name.startswith("HDD:")), None)

if disk_space_channel is not None:
logger.info(f"Found existing channel: {disk_space_channel.name}")
await disk_space_channel.edit(name=f"HDD: {space}")
else:
logger.info("No existing HDD: channel found, creating a new one.")
overwrites = {
guild.default_role: discord.PermissionOverwrite(connect=False)
}
await guild.create_voice_channel(name=f"HDD: {space}", overwrites=overwrites)
else:
logger.info(f"Guild with ID {guild_id} not found.")
except Exception as e:
logger.error(f"Failed to update disk space channel: {e}")

@trakt_ratings.before_loop
async def before_trakt_ratings(self):
if ENABLE_DELAY:
Expand Down
36 changes: 36 additions & 0 deletions src/linux/disk_space.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import subprocess

from utils.custom_logger import logger

def get_disk_space() -> str:
target_partition = '/dev/sdb'

try:
result = subprocess.run(['df', '-BG'], capture_output=True, text=True, check=True)
except subprocess.CalledProcessError as e:
return f"Error running df command: {e}"

lines = result.stdout.splitlines()
if len(lines) < 2:
return "Unexpected output format from df command"

for line in lines[1:]:
parts = line.split()
if parts[0] == target_partition:
headers = lines[0].split()
values = line.split()
if "Available" in headers and "1G-blocks" in headers:
available_space_index = headers.index("Available")
total_space_index = headers.index("1G-blocks")
elif "Avail" in headers and "Size" in headers: # Some versions of 'df' abbreviate 'Available' as 'Avail'
available_space_index = headers.index("Avail")
total_space_index = headers.index("Size")
else:
return "Could not find space information in df output"

available_space_gb = values[available_space_index].rstrip('G')
total_space_gb = values[total_space_index].rstrip('G')
logger.info(f"Available space: {available_space_gb} GB, Total space: {total_space_gb} GB")
return f"{available_space_gb}GB / {total_space_gb}GB"

return f"No data found for {target_partition}"
Loading