From 6204e339fc89ba6b81a3b4c7d359b2e07147a9ac Mon Sep 17 00:00:00 2001 From: pacnpal <183241239+pacnpal@users.noreply.github.com> Date: Thu, 14 Nov 2024 17:46:45 +0000 Subject: [PATCH 01/49] first --- README.md | 166 +++++++++++ video_archiver/__init__.py | 4 + video_archiver/ffmpeg_manager.py | 270 +++++++++++++++++ video_archiver/info.json | 22 ++ video_archiver/utils.py | 205 +++++++++++++ video_archiver/video_archiver.py | 494 +++++++++++++++++++++++++++++++ 6 files changed, 1161 insertions(+) create mode 100644 README.md create mode 100644 video_archiver/__init__.py create mode 100644 video_archiver/ffmpeg_manager.py create mode 100644 video_archiver/info.json create mode 100644 video_archiver/utils.py create mode 100644 video_archiver/video_archiver.py diff --git a/README.md b/README.md new file mode 100644 index 0000000..a8f1fd7 --- /dev/null +++ b/README.md @@ -0,0 +1,166 @@ +# VideoArchiver Cog for Red-DiscordBot + +A powerful video archiving cog that automatically downloads and reposts videos from monitored channels, with support for GPU-accelerated compression, multi-video processing, and role-based permissions. + +## Features + +- **Hardware-Accelerated Video Processing**: + - NVIDIA GPU support using NVENC + - AMD GPU support using AMF + - Intel GPU support using QuickSync + - ARM64/aarch64 support with V4L2 M2M encoder + - Multi-core CPU optimization +- **Smart Video Processing**: + - Intelligent quality preservation + - Only compresses when needed + - Concurrent video processing + - Default 8MB file size limit +- **Role-Based Access**: + - Restrict archiving to specific roles + - Default allows all users + - Per-guild role configuration +- **Wide Platform Support**: + - Support for multiple video platforms via [yt-dlp](https://github.com/yt-dlp/yt-dlp) + - Configurable site whitelist + - Automatic quality selection + +## Quick Installation + +1. Install the cog: +``` +[p]repo add video-archiver https://github.com/yourusername/discord-video-bot +[p]cog install video-archiver video_archiver +[p]load video_archiver +``` + +The required dependencies will be installed automatically. If you need to install them manually: +```bash +python -m pip install -U yt-dlp>=2024.11.4 ffmpeg-python>=0.2.0 requests>=2.32.3 +``` + +### Important: Keeping yt-dlp Updated + +The cog relies on [yt-dlp](https://github.com/yt-dlp/yt-dlp) for video downloading. Video platforms frequently update their sites, which may break video downloading if yt-dlp is outdated. To ensure continued functionality, regularly update yt-dlp: + +```bash +[p]pipinstall --upgrade yt-dlp + +# Or manually: +python -m pip install -U yt-dlp +``` + +**Note**: Before submitting any GitHub issues related to video downloading, please ensure you have updated yt-dlp to the latest version first, as most downloading issues can be resolved by updating. + +## Configuration + +The cog supports both slash commands and traditional prefix commands. Use whichever style you prefer. + +### Channel Setup +``` +/videoarchiver setchannel #archive-channel # Set archive channel +/videoarchiver setnotification #notify-channel # Set notification channel +/videoarchiver setlogchannel #log-channel # Set log channel for errors/notifications +/videoarchiver addmonitor #videos-channel # Add channel to monitor +/videoarchiver removemonitor #channel # Remove monitored channel + +# Legacy commands also supported: +[p]videoarchiver setchannel #channel +[p]videoarchiver setnotification #channel +etc. +``` + +### Role Management +``` +/videoarchiver addrole @role # Add role that can trigger archiving +/videoarchiver removerole @role # Remove role from allowed list +/videoarchiver listroles # List all allowed roles (empty = all allowed) +``` + +### Video Settings +``` +/videoarchiver setformat mp4 # Set video format +/videoarchiver setquality 1080 # Set max quality (pixels) +/videoarchiver setmaxsize 8 # Set max size (MB, default 8MB) +/videoarchiver toggledelete # Toggle file cleanup +``` + +### Message Settings +``` +/videoarchiver setduration 24 # Set message duration (hours) +/videoarchiver settemplate "Archived video from {author}\nOriginal: {original_message}" +/videoarchiver enablesites # Configure allowed sites +``` + +## Architecture Support + +The cog supports multiple architectures: +- x86_64/amd64 +- ARM64/aarch64 +- ARMv7 (32-bit) +- Apple Silicon (M1/M2) + +Hardware acceleration is automatically configured based on your system: +- x86_64: Full GPU support (NVIDIA, AMD, Intel) +- ARM64: V4L2 M2M hardware encoding when available +- All platforms: Multi-core CPU optimization + +## Troubleshooting + +1. **Permission Issues**: + - Bot needs "Manage Messages" permission + - Bot needs "Attach Files" permission + - Bot needs "Read Message History" permission + - Bot needs "Use Application Commands" for slash commands + +2. **Video Processing Issues**: + - Ensure FFmpeg is properly installed + - Check GPU drivers are up to date + - Verify file permissions in the downloads directory + - Update yt-dlp if videos fail to download + +3. **Role Issues**: + - Verify role hierarchy (bot's role must be higher than managed roles) + - Check if roles are properly configured + +4. **Performance Issues**: + - Check available disk space + - Monitor system resource usage + +## Support + +For support: +1. First, check the [Troubleshooting](#troubleshooting) section above +2. Update yt-dlp to the latest version: + ```bash + [p]pipinstall --upgrade yt-dlp + # Or manually: + python -m pip install -U yt-dlp + ``` +3. If the issue persists after updating yt-dlp: + - Join the Red-DiscordBot server and ask in the #support channel + - Open an issue on GitHub with: + - Your Red-Bot version + - The output of `[p]pipinstall list` + - Steps to reproduce the issue + - Any error messages + +## Contributing + +Contributions are welcome! Please feel free to submit a Pull Request. + +Before submitting an issue: +1. Update yt-dlp to the latest version first: + ```bash + [p]pipinstall --upgrade yt-dlp + # Or manually: + python -m pip install -U yt-dlp + ``` +2. If the issue persists after updating yt-dlp, please include: + - Your Red-Bot version + - The output of `[p]pipinstall list` + - Steps to reproduce the issue + - Any error messages + +## License + +This cog is licensed under the MIT License - see the [LICENSE](../LICENSE) file for details. diff --git a/video_archiver/__init__.py b/video_archiver/__init__.py new file mode 100644 index 0000000..7c68e10 --- /dev/null +++ b/video_archiver/__init__.py @@ -0,0 +1,4 @@ +from .video_archiver import VideoArchiver + +async def setup(bot): + await bot.add_cog(VideoArchiver(bot)) diff --git a/video_archiver/ffmpeg_manager.py b/video_archiver/ffmpeg_manager.py new file mode 100644 index 0000000..246f4be --- /dev/null +++ b/video_archiver/ffmpeg_manager.py @@ -0,0 +1,270 @@ +import os +import sys +import platform +import subprocess +import logging +import shutil +import requests +import zipfile +import tarfile +from pathlib import Path +import stat +import multiprocessing +import ffmpeg + +logger = logging.getLogger('VideoArchiver') + +class FFmpegManager: + FFMPEG_URLS = { + 'Windows': { + 'x86_64': { + 'url': 'https://github.com/BtbN/FFmpeg-Builds/releases/download/latest/ffmpeg-master-latest-win64-gpl.zip', + 'bin_name': 'ffmpeg.exe' + } + }, + 'Linux': { + 'x86_64': { + 'url': 'https://github.com/BtbN/FFmpeg-Builds/releases/download/latest/ffmpeg-master-latest-linux64-gpl.tar.xz', + 'bin_name': 'ffmpeg' + }, + 'aarch64': { # ARM64 + 'url': 'https://github.com/BtbN/FFmpeg-Builds/releases/download/latest/ffmpeg-master-latest-linuxarm64-gpl.tar.xz', + 'bin_name': 'ffmpeg' + }, + 'armv7l': { # ARM32 + 'url': 'https://github.com/BtbN/FFmpeg-Builds/releases/download/latest/ffmpeg-master-latest-linuxarm32-gpl.tar.xz', + 'bin_name': 'ffmpeg' + } + }, + 'Darwin': { # macOS + 'x86_64': { + 'url': 'https://evermeet.cx/ffmpeg/getrelease/zip', + 'bin_name': 'ffmpeg' + }, + 'arm64': { # Apple Silicon + 'url': 'https://evermeet.cx/ffmpeg/getrelease/zip', + 'bin_name': 'ffmpeg' + } + } + } + + def __init__(self): + self.base_path = Path(__file__).parent / 'bin' + self.base_path.mkdir(exist_ok=True) + + # Get system architecture + self.system = platform.system() + self.machine = platform.machine().lower() + if self.machine == 'arm64': + self.machine = 'aarch64' # Normalize ARM64 naming + + # Try to use system FFmpeg first + system_ffmpeg = shutil.which('ffmpeg') + if system_ffmpeg: + self.ffmpeg_path = Path(system_ffmpeg) + logger.info(f"Using system FFmpeg: {self.ffmpeg_path}") + else: + # Fall back to downloaded FFmpeg + try: + arch_config = self.FFMPEG_URLS[self.system][self.machine] + self.ffmpeg_path = self.base_path / arch_config['bin_name'] + except KeyError: + raise Exception(f"Unsupported system/architecture: {self.system}/{self.machine}") + + self._gpu_info = self._detect_gpu() + self._cpu_cores = multiprocessing.cpu_count() + + if not system_ffmpeg: + self._ensure_ffmpeg() + + def _detect_gpu(self) -> dict: + """Detect available GPU and its capabilities""" + gpu_info = { + 'nvidia': False, + 'amd': False, + 'intel': False, + 'arm': False + } + + try: + if self.system == 'Linux': + # Check for NVIDIA GPU + nvidia_smi = subprocess.run(['nvidia-smi'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) + if nvidia_smi.returncode == 0: + gpu_info['nvidia'] = True + + # Check for AMD GPU + if os.path.exists('/dev/dri/renderD128'): + gpu_info['amd'] = True + + # Check for Intel GPU + lspci = subprocess.run(['lspci'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) + if b'VGA' in lspci.stdout and b'Intel' in lspci.stdout: + gpu_info['intel'] = True + + # Check for ARM GPU + if self.machine in ['aarch64', 'armv7l']: + gpu_info['arm'] = True + + elif self.system == 'Windows': + # Check for any GPU using dxdiag + dxdiag = subprocess.run(['dxdiag', '/t', 'temp_dxdiag.txt'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) + if os.path.exists('temp_dxdiag.txt'): + with open('temp_dxdiag.txt', 'r') as f: + content = f.read().lower() + if 'nvidia' in content: + gpu_info['nvidia'] = True + if 'amd' in content or 'radeon' in content: + gpu_info['amd'] = True + if 'intel' in content: + gpu_info['intel'] = True + os.remove('temp_dxdiag.txt') + + except Exception as e: + logger.warning(f"GPU detection failed: {str(e)}") + + return gpu_info + + def _get_optimal_ffmpeg_params(self, input_path: str, target_size_bytes: int) -> dict: + """Get optimal FFmpeg parameters based on hardware and video size""" + params = { + 'c:v': 'libx264', # Default to CPU encoding + 'threads': str(self._cpu_cores), # Use all CPU cores + 'preset': 'medium', + 'crf': '23', # Default quality + 'maxrate': None, + 'bufsize': None, + 'movflags': '+faststart', # Optimize for web playback + 'profile:v': 'high', # High profile for better quality + 'level': '4.1', # Compatibility level + 'pix_fmt': 'yuv420p' # Standard pixel format + } + + # Check if GPU encoding is possible + if self._gpu_info['nvidia']: + params.update({ + 'c:v': 'h264_nvenc', + 'preset': 'p4', # High quality NVENC preset + 'rc:v': 'vbr', # Variable bitrate for better quality + 'cq:v': '19', # Quality level for NVENC + 'spatial-aq': '1', # Enable spatial adaptive quantization + 'temporal-aq': '1', # Enable temporal adaptive quantization + 'b_ref_mode': 'middle' # Better quality for B-frames + }) + elif self._gpu_info['amd']: + params.update({ + 'c:v': 'h264_amf', + 'quality': 'quality', + 'rc': 'vbr_peak', + 'enforce_hrd': '1', + 'vbaq': '1', # Enable adaptive quantization + 'preanalysis': '1' + }) + elif self._gpu_info['intel']: + params.update({ + 'c:v': 'h264_qsv', + 'preset': 'veryslow', # Best quality for QSV + 'look_ahead': '1', + 'global_quality': '23' + }) + elif self._gpu_info['arm']: + # Use OpenMAX (OMX) on supported ARM devices + if os.path.exists('/dev/video-codec'): + params.update({ + 'c:v': 'h264_v4l2m2m', # V4L2 M2M encoder + 'extra_hw_frames': '10' + }) + else: + # Fall back to optimized CPU encoding for ARM + params.update({ + 'c:v': 'libx264', + 'preset': 'medium', + 'tune': 'fastdecode' + }) + + # Get input file size and probe info + input_size = os.path.getsize(input_path) + probe = ffmpeg.probe(input_path) + duration = float(probe['format']['duration']) + + # Only add bitrate constraints if compression is needed + if input_size > target_size_bytes: + # Calculate target bitrate (bits/second) + target_bitrate = int((target_size_bytes * 8) / duration * 0.95) # 95% of target size + + params['maxrate'] = f"{target_bitrate}" + params['bufsize'] = f"{target_bitrate * 2}" + + # Adjust quality settings based on compression ratio + ratio = input_size / target_size_bytes + if ratio > 4: + params['crf'] = '28' if params['c:v'] == 'libx264' else '23' + params['preset'] = 'faster' + elif ratio > 2: + params['crf'] = '26' if params['c:v'] == 'libx264' else '21' + params['preset'] = 'medium' + else: + params['crf'] = '23' if params['c:v'] == 'libx264' else '19' + params['preset'] = 'slow' + + # Audio settings + params.update({ + 'c:a': 'aac', + 'b:a': '192k', # High quality audio + 'ar': '48000' # Standard sample rate + }) + + return params + + def _ensure_ffmpeg(self): + """Ensure FFmpeg is available, downloading if necessary""" + if not self.ffmpeg_path.exists(): + self._download_ffmpeg() + + # Make binary executable on Unix systems + if self.system != 'Windows': + self.ffmpeg_path.chmod(self.ffmpeg_path.stat().st_mode | stat.S_IEXEC) + + def _download_ffmpeg(self): + """Download and extract FFmpeg binary""" + try: + arch_config = self.FFMPEG_URLS[self.system][self.machine] + except KeyError: + raise Exception(f"Unsupported system/architecture: {self.system}/{self.machine}") + + url = arch_config['url'] + archive_path = self.base_path / f"ffmpeg_archive{'.zip' if self.system == 'Windows' else '.tar.xz'}" + + # Download archive + response = requests.get(url, stream=True) + response.raise_for_status() + with open(archive_path, 'wb') as f: + for chunk in response.iter_content(chunk_size=8192): + f.write(chunk) + + # Extract archive + if self.system == 'Windows': + with zipfile.ZipFile(archive_path, 'r') as zip_ref: + ffmpeg_files = [f for f in zip_ref.namelist() if arch_config['bin_name'] in f] + if ffmpeg_files: + zip_ref.extract(ffmpeg_files[0], self.base_path) + os.rename(self.base_path / ffmpeg_files[0], self.ffmpeg_path) + else: + with tarfile.open(archive_path, 'r:xz') as tar_ref: + ffmpeg_files = [f for f in tar_ref.getnames() if arch_config['bin_name'] in f] + if ffmpeg_files: + tar_ref.extract(ffmpeg_files[0], self.base_path) + os.rename(self.base_path / ffmpeg_files[0], self.ffmpeg_path) + + # Cleanup + archive_path.unlink() + + def get_ffmpeg_path(self) -> str: + """Get path to FFmpeg binary""" + if not self.ffmpeg_path.exists(): + raise Exception("FFmpeg is not available") + return str(self.ffmpeg_path) + + def get_compression_params(self, input_path: str, target_size_mb: int) -> dict: + """Get optimal compression parameters for the given input file""" + return self._get_optimal_ffmpeg_params(input_path, target_size_mb * 1024 * 1024) diff --git a/video_archiver/info.json b/video_archiver/info.json new file mode 100644 index 0000000..c3c9067 --- /dev/null +++ b/video_archiver/info.json @@ -0,0 +1,22 @@ +{ + "name": "VideoArchiver", + "author": ["Cline"], + "description": "A powerful Discord video archiver cog that automatically downloads and reposts videos from monitored channels. Features include:\n- GPU-accelerated video compression (NVIDIA, AMD, Intel)\n- Multi-core CPU utilization\n- Concurrent multi-video processing\n- Intelligent quality preservation\n- Support for multiple video sites\n- Customizable archive messages\n- Automatic cleanup", + "short": "Archive videos from Discord channels with GPU-accelerated compression", + "tags": [ + "video", + "archive", + "download", + "compression", + "media" + ], + "requirements": [ + "yt-dlp>=2023.12.30", + "ffmpeg-python>=0.2.0", + "requests>=2.31.0" + ], + "min_bot_version": "3.5.0", + "hidden": false, + "disabled": false, + "type": "COG" +} diff --git a/video_archiver/utils.py b/video_archiver/utils.py new file mode 100644 index 0000000..89caed0 --- /dev/null +++ b/video_archiver/utils.py @@ -0,0 +1,205 @@ +import os +import shutil +import logging +import asyncio +from pathlib import Path +from typing import Dict, List, Optional, Tuple, Set +import yt_dlp +import ffmpeg +from datetime import datetime, timedelta +from concurrent.futures import ThreadPoolExecutor +from .ffmpeg_manager import FFmpegManager + +logging.basicConfig( + level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s" +) +logger = logging.getLogger("VideoArchiver") + +# Initialize FFmpeg manager +ffmpeg_mgr = FFmpegManager() + +# Global thread pool for concurrent downloads +download_pool = ThreadPoolExecutor(max_workers=3) + +class VideoDownloader: + def __init__(self, download_path: str, video_format: str, max_quality: int, max_file_size: int, enabled_sites: Optional[List[str]] = None): + self.download_path = download_path + self.video_format = video_format + self.max_quality = max_quality + self.max_file_size = max_file_size + self.enabled_sites = enabled_sites + self.url_patterns = self._get_url_patterns() + + # Configure yt-dlp options + self.ydl_opts = { + 'format': f'bestvideo[height<={max_quality}]+bestaudio/best[height<={max_quality}]', + 'outtmpl': os.path.join(download_path, '%(title)s.%(ext)s'), + 'merge_output_format': video_format, + 'quiet': True, + 'no_warnings': True, + 'extract_flat': False, + 'concurrent_fragment_downloads': 3, + 'postprocessor_hooks': [self._check_file_size], + 'progress_hooks': [self._progress_hook], + 'ffmpeg_location': ffmpeg_mgr.get_ffmpeg_path(), + } + + def _get_url_patterns(self) -> List[str]: + """Get URL patterns for supported sites""" + patterns = [] + with yt_dlp.YoutubeDL() as ydl: + for extractor in ydl._ies: + if hasattr(extractor, '_VALID_URL') and extractor._VALID_URL: + if not self.enabled_sites or any(site.lower() in extractor.IE_NAME.lower() for site in self.enabled_sites): + patterns.append(extractor._VALID_URL) + return patterns + + def _check_file_size(self, info): + """Check if file size is within limits""" + if info.get('filepath') and os.path.exists(info['filepath']): + size = os.path.getsize(info['filepath']) + if size > (self.max_file_size * 1024 * 1024): + logger.info(f"File exceeds size limit, will compress: {info['filepath']}") + + def _progress_hook(self, d): + """Handle download progress""" + if d['status'] == 'finished': + logger.info(f"Download completed: {d['filename']}") + + async def download_video(self, url: str) -> Tuple[bool, str, str]: + """Download and process a video""" + try: + # Configure yt-dlp for this download + ydl_opts = self.ydl_opts.copy() + + with yt_dlp.YoutubeDL(ydl_opts) as ydl: + # Run download in executor to prevent blocking + info = await asyncio.get_event_loop().run_in_executor( + download_pool, lambda: ydl.extract_info(url, download=True) + ) + + if info is None: + return False, "", "Failed to extract video information" + + file_path = os.path.join(self.download_path, ydl.prepare_filename(info)) + + if not os.path.exists(file_path): + return False, "", "Download completed but file not found" + + # Check file size and compress if needed + file_size = os.path.getsize(file_path) + if file_size > (self.max_file_size * 1024 * 1024): + logger.info(f"Compressing video: {file_path}") + try: + # Get optimal compression parameters + params = ffmpeg_mgr.get_compression_params(file_path, self.max_file_size) + output_path = file_path + ".compressed." + self.video_format + + # Configure ffmpeg with optimal parameters + stream = ffmpeg.input(file_path) + stream = ffmpeg.output(stream, output_path, **params) + + # Run compression in executor + await asyncio.get_event_loop().run_in_executor( + None, + lambda: ffmpeg.run( + stream, + capture_stdout=True, + capture_stderr=True, + overwrite_output=True, + ), + ) + + if os.path.exists(output_path): + compressed_size = os.path.getsize(output_path) + if compressed_size <= (self.max_file_size * 1024 * 1024): + os.remove(file_path) # Remove original + return True, output_path, "" + else: + os.remove(output_path) + return False, "", "Failed to compress to target size" + except Exception as e: + logger.error(f"Compression error: {str(e)}") + return False, "", f"Compression error: {str(e)}" + + return True, file_path, "" + + except Exception as e: + logger.error(f"Download error: {str(e)}") + return False, "", str(e) + + def is_supported_url(self, url: str) -> bool: + """Check if URL is supported""" + try: + with yt_dlp.YoutubeDL() as ydl: + # Try to extract info without downloading + ie = ydl.extract_info(url, download=False, process=False) + return ie is not None + except: + return False + + +class MessageManager: + def __init__(self, message_duration: int, message_template: str): + self.message_duration = message_duration + self.message_template = message_template + self.scheduled_deletions: Dict[int, asyncio.Task] = {} + + def format_archive_message(self, author: str, url: str, original_message: str) -> str: + return self.message_template.format( + author=author, url=url, original_message=original_message + ) + + async def schedule_message_deletion(self, message_id: int, delete_func) -> None: + if self.message_duration <= 0: + return + + if message_id in self.scheduled_deletions: + self.scheduled_deletions[message_id].cancel() + + async def delete_later(): + await asyncio.sleep(self.message_duration * 3600) # Convert hours to seconds + try: + await delete_func() + except Exception as e: + logger.error(f"Failed to delete message {message_id}: {str(e)}") + finally: + self.scheduled_deletions.pop(message_id, None) + + self.scheduled_deletions[message_id] = asyncio.create_task(delete_later()) + + +def secure_delete_file(file_path: str, passes: int = 3) -> bool: + if not os.path.exists(file_path): + return True + + try: + file_size = os.path.getsize(file_path) + for _ in range(passes): + with open(file_path, "wb") as f: + f.write(os.urandom(file_size)) + f.flush() + os.fsync(f.fileno()) + + os.remove(file_path) + + if os.path.exists(file_path) or Path(file_path).exists(): + os.unlink(file_path) + + return not (os.path.exists(file_path) or Path(file_path).exists()) + + except Exception as e: + logger.error(f"Error during secure delete: {str(e)}") + return False + + +def cleanup_downloads(download_path: str) -> None: + try: + if os.path.exists(download_path): + for file_path in Path(download_path).glob("*"): + secure_delete_file(str(file_path)) + + shutil.rmtree(download_path, ignore_errors=True) + Path(download_path).mkdir(parents=True, exist_ok=True) + except Exception as e: + logger.error(f"Error during cleanup: {str(e)}") diff --git a/video_archiver/video_archiver.py b/video_archiver/video_archiver.py new file mode 100644 index 0000000..47166ec --- /dev/null +++ b/video_archiver/video_archiver.py @@ -0,0 +1,494 @@ +import os +import re +import discord +from redbot.core import commands, Config +from redbot.core.bot import Red +from redbot.core.utils.chat_formatting import box +from discord import app_commands +import logging +from pathlib import Path +import yt_dlp +import shutil +import asyncio +from typing import Optional, List, Set, Dict +import sys + +# Add cog directory to path for local imports +cog_path = Path(__file__).parent +if str(cog_path) not in sys.path: + sys.path.append(str(cog_path)) + +# Import local utils +from utils import VideoDownloader, secure_delete_file, cleanup_downloads, MessageManager +from ffmpeg_manager import FFmpegManager + +# Configure logging +logging.basicConfig( + level=logging.INFO, + format='%(asctime)s - %(name)s - %(levelname)s - %(message)s' +) +logger = logging.getLogger('VideoArchiver') + +class VideoArchiver(commands.Cog): + """Archive videos from Discord channels""" + + default_guild = { + "archive_channel": None, + "notification_channel": None, + "log_channel": None, # Added log channel + "monitored_channels": [], + "allowed_roles": [], # Added role management + "video_format": "mp4", + "video_quality": 1080, + "max_file_size": 8, # Changed to 8MB default + "delete_after_repost": True, + "message_duration": 24, + "message_template": "Archived video from {author}\nOriginal: {original_message}", + "enabled_sites": [], + "concurrent_downloads": 3 + } + + def __init__(self, bot: Red): + self.bot = bot + self.config = Config.get_conf(self, identifier=855847, force_registration=True) + self.config.register_guild(**self.default_guild) + + # Initialize components dict for each guild + self.components = {} + self.download_path = Path(cog_path) / "downloads" + self.download_path.mkdir(parents=True, exist_ok=True) + + # Clean up downloads on load + cleanup_downloads(str(self.download_path)) + + # Initialize FFmpeg manager + self.ffmpeg_mgr = FFmpegManager() + + def cog_unload(self): + """Cleanup when cog is unloaded""" + if self.download_path.exists(): + shutil.rmtree(self.download_path, ignore_errors=True) + + async def initialize_guild_components(self, guild_id: int): + """Initialize or update components for a guild""" + settings = await self.config.guild_from_id(guild_id).all() + + self.components[guild_id] = { + 'downloader': VideoDownloader( + str(self.download_path), + settings['video_format'], + settings['video_quality'], + settings['max_file_size'], + settings['enabled_sites'] if settings['enabled_sites'] else None + ), + 'message_manager': MessageManager( + settings['message_duration'], + settings['message_template'] + ) + } + + def _check_user_roles(self, member: discord.Member, allowed_roles: List[int]) -> bool: + """Check if user has permission to trigger archiving""" + # If no roles are set, allow all users + if not allowed_roles: + return True + + # Check if user has any of the allowed roles + return any(role.id in allowed_roles for role in member.roles) + + async def log_message(self, guild: discord.Guild, message: str, level: str = "info"): + """Send a log message to the guild's log channel if set""" + settings = await self.config.guild(guild).all() + if settings["log_channel"]: + try: + log_channel = guild.get_channel(settings["log_channel"]) + if log_channel: + await log_channel.send(f"[{level.upper()}] {message}") + except discord.HTTPException: + logger.error(f"Failed to send log message to channel: {message}") + logger.log(getattr(logging, level.upper()), message) + + @commands.hybrid_group(name="videoarchiver", aliases=["va"]) + @commands.guild_only() + @commands.admin_or_permissions(administrator=True) + async def videoarchiver(self, ctx: commands.Context): + """Video Archiver configuration commands""" + if ctx.invoked_subcommand is None: + settings = await self.config.guild(ctx.guild).all() + embed = discord.Embed( + title="Video Archiver Settings", + color=discord.Color.blue() + ) + + archive_channel = ctx.guild.get_channel(settings["archive_channel"]) if settings["archive_channel"] else None + notification_channel = ctx.guild.get_channel(settings["notification_channel"]) if settings["notification_channel"] else None + log_channel = ctx.guild.get_channel(settings["log_channel"]) if settings["log_channel"] else None + monitored_channels = [ctx.guild.get_channel(c) for c in settings["monitored_channels"]] + monitored_channels = [c.mention for c in monitored_channels if c] + allowed_roles = [ctx.guild.get_role(r) for r in settings["allowed_roles"]] + allowed_roles = [r.name for r in allowed_roles if r] + + embed.add_field( + name="Archive Channel", + value=archive_channel.mention if archive_channel else "Not set", + inline=False + ) + embed.add_field( + name="Notification Channel", + value=notification_channel.mention if notification_channel else "Same as archive", + inline=False + ) + embed.add_field( + name="Log Channel", + value=log_channel.mention if log_channel else "Not set", + inline=False + ) + embed.add_field( + name="Monitored Channels", + value="\n".join(monitored_channels) if monitored_channels else "None", + inline=False + ) + embed.add_field( + name="Allowed Roles", + value=", ".join(allowed_roles) if allowed_roles else "All roles (no restrictions)", + inline=False + ) + embed.add_field(name="Video Format", value=settings["video_format"], inline=True) + embed.add_field(name="Max Quality", value=f"{settings['video_quality']}p", inline=True) + embed.add_field(name="Max File Size", value=f"{settings['max_file_size']}MB", inline=True) + embed.add_field(name="Delete After Repost", value=str(settings["delete_after_repost"]), inline=True) + embed.add_field(name="Message Duration", value=f"{settings['message_duration']} hours", inline=True) + embed.add_field(name="Concurrent Downloads", value=str(settings["concurrent_downloads"]), inline=True) + embed.add_field( + name="Enabled Sites", + value=", ".join(settings["enabled_sites"]) if settings["enabled_sites"] else "All sites", + inline=False + ) + + # Add hardware info + gpu_info = self.ffmpeg_mgr._gpu_info + cpu_cores = self.ffmpeg_mgr._cpu_cores + + hardware_info = f"CPU Cores: {cpu_cores}\n" + if gpu_info['nvidia']: + hardware_info += "NVIDIA GPU: Available (using NVENC)\n" + if gpu_info['amd']: + hardware_info += "AMD GPU: Available (using AMF)\n" + if gpu_info['intel']: + hardware_info += "Intel GPU: Available (using QSV)\n" + if not any(gpu_info.values()): + hardware_info += "No GPU acceleration available (using CPU)\n" + + embed.add_field(name="Hardware Info", value=hardware_info, inline=False) + + await ctx.send(embed=embed) + + @videoarchiver.command(name="addrole") + async def add_allowed_role(self, ctx: commands.Context, role: discord.Role): + """Add a role that's allowed to trigger archiving""" + async with self.config.guild(ctx.guild).allowed_roles() as roles: + if role.id not in roles: + roles.append(role.id) + await ctx.send(f"Added {role.name} to allowed roles") + await self.log_message(ctx.guild, f"Added role {role.name} ({role.id}) to allowed roles") + await self.initialize_guild_components(ctx.guild.id) + + @videoarchiver.command(name="removerole") + async def remove_allowed_role(self, ctx: commands.Context, role: discord.Role): + """Remove a role from allowed roles""" + async with self.config.guild(ctx.guild).allowed_roles() as roles: + if role.id in roles: + roles.remove(role.id) + await ctx.send(f"Removed {role.name} from allowed roles") + await self.log_message(ctx.guild, f"Removed role {role.name} ({role.id}) from allowed roles") + await self.initialize_guild_components(ctx.guild.id) + + @videoarchiver.command(name="listroles") + async def list_allowed_roles(self, ctx: commands.Context): + """List all roles allowed to trigger archiving""" + roles = await self.config.guild(ctx.guild).allowed_roles() + if not roles: + await ctx.send("No roles are currently allowed (all users can trigger archiving)") + return + + role_names = [r.name for r in [ctx.guild.get_role(role_id) for role_id in roles] if r] + await ctx.send(f"Allowed roles: {', '.join(role_names)}") + + @videoarchiver.command(name="setconcurrent") + async def set_concurrent_downloads(self, ctx: commands.Context, count: int): + """Set the number of concurrent downloads (1-5)""" + if not 1 <= count <= 5: + await ctx.send("Concurrent downloads must be between 1 and 5") + return + + await self.config.guild(ctx.guild).concurrent_downloads.set(count) + await ctx.send(f"Concurrent downloads set to {count}") + await self.log_message(ctx.guild, f"Concurrent downloads set to {count}") + await self.initialize_guild_components(ctx.guild.id) + + @videoarchiver.command(name="setchannel") + async def set_archive_channel(self, ctx: commands.Context, channel: discord.TextChannel): + """Set the archive channel""" + await self.config.guild(ctx.guild).archive_channel.set(channel.id) + await ctx.send(f"Archive channel set to {channel.mention}") + await self.log_message(ctx.guild, f"Archive channel set to {channel.name} ({channel.id})") + await self.initialize_guild_components(ctx.guild.id) + + @videoarchiver.command(name="setnotification") + async def set_notification_channel(self, ctx: commands.Context, channel: discord.TextChannel): + """Set the notification channel (where archive messages appear)""" + await self.config.guild(ctx.guild).notification_channel.set(channel.id) + await ctx.send(f"Notification channel set to {channel.mention}") + await self.log_message(ctx.guild, f"Notification channel set to {channel.name} ({channel.id})") + await self.initialize_guild_components(ctx.guild.id) + + @videoarchiver.command(name="setlogchannel") + async def set_log_channel(self, ctx: commands.Context, channel: discord.TextChannel): + """Set the log channel for error messages and notifications""" + await self.config.guild(ctx.guild).log_channel.set(channel.id) + await ctx.send(f"Log channel set to {channel.mention}") + await self.log_message(ctx.guild, f"Log channel set to {channel.name} ({channel.id})") + await self.initialize_guild_components(ctx.guild.id) + + @videoarchiver.command(name="addmonitor") + async def add_monitored_channel(self, ctx: commands.Context, channel: discord.TextChannel): + """Add a channel to monitor for videos""" + async with self.config.guild(ctx.guild).monitored_channels() as channels: + if channel.id not in channels: + channels.append(channel.id) + await ctx.send(f"Now monitoring {channel.mention} for videos") + await self.log_message(ctx.guild, f"Added {channel.name} ({channel.id}) to monitored channels") + await self.initialize_guild_components(ctx.guild.id) + + @videoarchiver.command(name="removemonitor") + async def remove_monitored_channel(self, ctx: commands.Context, channel: discord.TextChannel): + """Remove a channel from monitoring""" + async with self.config.guild(ctx.guild).monitored_channels() as channels: + if channel.id in channels: + channels.remove(channel.id) + await ctx.send(f"Stopped monitoring {channel.mention}") + await self.log_message(ctx.guild, f"Removed {channel.name} ({channel.id}) from monitored channels") + await self.initialize_guild_components(ctx.guild.id) + + @videoarchiver.command(name="setformat") + async def set_video_format(self, ctx: commands.Context, format: str): + """Set the video format (e.g., mp4, webm)""" + await self.config.guild(ctx.guild).video_format.set(format.lower()) + await ctx.send(f"Video format set to {format.lower()}") + await self.log_message(ctx.guild, f"Video format set to {format.lower()}") + await self.initialize_guild_components(ctx.guild.id) + + @videoarchiver.command(name="setquality") + async def set_video_quality(self, ctx: commands.Context, quality: int): + """Set the maximum video quality in pixels (e.g., 1080)""" + await self.config.guild(ctx.guild).video_quality.set(quality) + await ctx.send(f"Maximum video quality set to {quality}p") + await self.log_message(ctx.guild, f"Video quality set to {quality}p") + await self.initialize_guild_components(ctx.guild.id) + + @videoarchiver.command(name="setmaxsize") + async def set_max_file_size(self, ctx: commands.Context, size: int): + """Set the maximum file size in MB""" + await self.config.guild(ctx.guild).max_file_size.set(size) + await ctx.send(f"Maximum file size set to {size}MB") + await self.log_message(ctx.guild, f"Maximum file size set to {size}MB") + await self.initialize_guild_components(ctx.guild.id) + + @videoarchiver.command(name="toggledelete") + async def toggle_delete_after_repost(self, ctx: commands.Context): + """Toggle whether to delete local files after reposting""" + current = await self.config.guild(ctx.guild).delete_after_repost() + await self.config.guild(ctx.guild).delete_after_repost.set(not current) + await ctx.send(f"Delete after repost: {not current}") + await self.log_message(ctx.guild, f"Delete after repost set to: {not current}") + + @videoarchiver.command(name="setduration") + async def set_message_duration(self, ctx: commands.Context, hours: int): + """Set how long to keep archive messages (0 for permanent)""" + await self.config.guild(ctx.guild).message_duration.set(hours) + await ctx.send(f"Archive message duration set to {hours} hours") + await self.log_message(ctx.guild, f"Message duration set to {hours} hours") + await self.initialize_guild_components(ctx.guild.id) + + @videoarchiver.command(name="settemplate") + async def set_message_template(self, ctx: commands.Context, *, template: str): + """Set the archive message template. Use {author}, {url}, and {original_message} as placeholders""" + await self.config.guild(ctx.guild).message_template.set(template) + await ctx.send(f"Archive message template set to:\n{template}") + await self.log_message(ctx.guild, f"Message template updated") + await self.initialize_guild_components(ctx.guild.id) + + @videoarchiver.command(name="enablesites") + async def enable_sites(self, ctx: commands.Context, *sites: str): + """Enable specific sites (leave empty for all sites)""" + sites = [s.lower() for s in sites] + if not sites: + await self.config.guild(ctx.guild).enabled_sites.set([]) + await ctx.send("All sites enabled") + else: + # Verify sites are valid + with yt_dlp.YoutubeDL() as ydl: + valid_sites = set(ie.IE_NAME.lower() for ie in ydl._ies) + invalid_sites = [s for s in sites if s not in valid_sites] + if invalid_sites: + await ctx.send(f"Invalid sites: {', '.join(invalid_sites)}\nValid sites: {', '.join(valid_sites)}") + return + + await self.config.guild(ctx.guild).enabled_sites.set(sites) + await ctx.send(f"Enabled sites: {', '.join(sites)}") + + await self.log_message(ctx.guild, f"Enabled sites updated: {', '.join(sites) if sites else 'All sites'}") + await self.initialize_guild_components(ctx.guild.id) + + @videoarchiver.command(name="listsites") + async def list_sites(self, ctx: commands.Context): + """List all available sites and currently enabled sites""" + settings = await self.config.guild(ctx.guild).all() + enabled_sites = settings["enabled_sites"] + + embed = discord.Embed( + title="Video Sites Configuration", + color=discord.Color.blue() + ) + + with yt_dlp.YoutubeDL() as ydl: + all_sites = sorted(ie.IE_NAME for ie in ydl._ies if ie.IE_NAME is not None) + + # Split sites into chunks for Discord's field value limit + chunk_size = 20 + site_chunks = [all_sites[i:i + chunk_size] for i in range(0, len(all_sites), chunk_size)] + + for i, chunk in enumerate(site_chunks, 1): + embed.add_field( + name=f"Available Sites ({i}/{len(site_chunks)})", + value=", ".join(chunk), + inline=False + ) + + embed.add_field( + name="Currently Enabled", + value=", ".join(enabled_sites) if enabled_sites else "All sites", + inline=False + ) + + await ctx.send(embed=embed) + + async def process_video_url(self, url: str, message: discord.Message) -> bool: + """Process a video URL: download, reupload, and cleanup""" + guild_id = message.guild.id + + # Initialize components if needed + if guild_id not in self.components: + await self.initialize_guild_components(guild_id) + + try: + await message.add_reaction('⏳') + await self.log_message(message.guild, f"Processing video URL: {url}") + + settings = await self.config.guild(message.guild).all() + + # Check user roles + if not self._check_user_roles(message.author, settings['allowed_roles']): + await message.add_reaction('🚫') + return False + + # Download video + success, file_path, error = await self.components[guild_id]['downloader'].download_video(url) + + if not success: + await message.add_reaction('❌') + await self.log_message(message.guild, f"Failed to download video: {error}", "error") + return False + + # Get channels + archive_channel = message.guild.get_channel(settings['archive_channel']) + notification_channel = message.guild.get_channel( + settings['notification_channel'] if settings['notification_channel'] + else settings['archive_channel'] + ) + + if not archive_channel or not notification_channel: + await self.log_message(message.guild, "Required channels not found!", "error") + return False + + try: + # Upload to archive channel + file = discord.File(file_path) + archive_message = await archive_channel.send(file=file) + + # Send notification with information + notification_message = await notification_channel.send( + self.components[guild_id]['message_manager'].format_archive_message( + author=message.author.mention, + url=archive_message.attachments[0].url if archive_message.attachments else "No URL available", + original_message=message.jump_url + ) + ) + + # Schedule notification message deletion if needed + await self.components[guild_id]['message_manager'].schedule_message_deletion( + notification_message.id, + notification_message.delete + ) + + await message.add_reaction('✅') + await self.log_message(message.guild, f"Successfully archived video from {message.author}") + + except discord.HTTPException as e: + await self.log_message(message.guild, f"Failed to upload video: {str(e)}", "error") + await message.add_reaction('❌') + return False + + finally: + # Always attempt to delete the file if configured + if settings['delete_after_repost']: + if secure_delete_file(file_path): + await self.log_message(message.guild, f"Successfully deleted file: {file_path}") + else: + await self.log_message(message.guild, f"Failed to delete file: {file_path}", "error") + # Emergency cleanup + cleanup_downloads(str(self.download_path)) + + return True + + except Exception as e: + await self.log_message(message.guild, f"Error processing video: {str(e)}", "error") + await message.add_reaction('❌') + return False + + @commands.Cog.listener() + async def on_message(self, message: discord.Message): + if message.author.bot or not message.guild: + return + + settings = await self.config.guild(message.guild).all() + + # Check if message is in a monitored channel + if message.channel.id not in settings['monitored_channels']: + return + + # Initialize components if needed + if message.guild.id not in self.components: + await self.initialize_guild_components(message.guild.id) + + # Find all video URLs in message + urls = [] + with yt_dlp.YoutubeDL() as ydl: + for ie in ydl._ies: + if ie._VALID_URL: + urls.extend(re.findall(ie._VALID_URL, message.content)) + + if urls: + # Process multiple URLs concurrently but limited + tasks = [] + semaphore = asyncio.Semaphore(settings['concurrent_downloads']) + + async def process_with_semaphore(url): + async with semaphore: + return await self.process_video_url(url, message) + + for url in urls: + tasks.append(asyncio.create_task(process_with_semaphore(url))) + + # Wait for all downloads to complete + await asyncio.gather(*tasks) From 605a902b2bd2eba282cc698d254d823ea83761de Mon Sep 17 00:00:00 2001 From: pacnpal <183241239+pacnpal@users.noreply.github.com> Date: Thu, 14 Nov 2024 17:58:40 +0000 Subject: [PATCH 02/49] commit for rebase --- README.md => video-archive/README.md | 0 video-archive/info.json | 9 +++++++++ .../video_archiver}/__init__.py | 0 .../video_archiver}/ffmpeg_manager.py | 0 .../video_archiver}/info.json | 0 .../video_archiver}/utils.py | 0 .../video_archiver}/video_archiver.py | 0 7 files changed, 9 insertions(+) rename README.md => video-archive/README.md (100%) create mode 100644 video-archive/info.json rename {video_archiver => video-archive/video_archiver}/__init__.py (100%) rename {video_archiver => video-archive/video_archiver}/ffmpeg_manager.py (100%) rename {video_archiver => video-archive/video_archiver}/info.json (100%) rename {video_archiver => video-archive/video_archiver}/utils.py (100%) rename {video_archiver => video-archive/video_archiver}/video_archiver.py (100%) diff --git a/README.md b/video-archive/README.md similarity index 100% rename from README.md rename to video-archive/README.md diff --git a/video-archive/info.json b/video-archive/info.json new file mode 100644 index 0000000..55d2fc2 --- /dev/null +++ b/video-archive/info.json @@ -0,0 +1,9 @@ +{ + "author": [ + "PacNPal" + ], + "install_msg": "Thank you for installing the Pac-cogs repo!", + "name": "Pac-cogs", + "short": "Very cool cogs!", + "description": "Right now, just a birthday cog." +} \ No newline at end of file diff --git a/video_archiver/__init__.py b/video-archive/video_archiver/__init__.py similarity index 100% rename from video_archiver/__init__.py rename to video-archive/video_archiver/__init__.py diff --git a/video_archiver/ffmpeg_manager.py b/video-archive/video_archiver/ffmpeg_manager.py similarity index 100% rename from video_archiver/ffmpeg_manager.py rename to video-archive/video_archiver/ffmpeg_manager.py diff --git a/video_archiver/info.json b/video-archive/video_archiver/info.json similarity index 100% rename from video_archiver/info.json rename to video-archive/video_archiver/info.json diff --git a/video_archiver/utils.py b/video-archive/video_archiver/utils.py similarity index 100% rename from video_archiver/utils.py rename to video-archive/video_archiver/utils.py diff --git a/video_archiver/video_archiver.py b/video-archive/video_archiver/video_archiver.py similarity index 100% rename from video_archiver/video_archiver.py rename to video-archive/video_archiver/video_archiver.py From e6f7fc092ff4a482afbc8de91425b701eaf3681f Mon Sep 17 00:00:00 2001 From: pacnpal Date: Sat, 28 Sep 2024 16:57:47 -0400 Subject: [PATCH 03/49] Initial commit --- .DS_Store | Bin 0 -> 6148 bytes .gitattributes | 2 + LICENSE | 674 +++++++++++++++++++++++++++++++++++++++ birthday-cog/LICENSE | 21 ++ birthday-cog/README.md | 68 ++++ birthday-cog/birthday.py | 94 ++++++ birthday-cog/info.json | 12 + 7 files changed, 871 insertions(+) create mode 100644 .DS_Store create mode 100644 .gitattributes create mode 100644 LICENSE create mode 100644 birthday-cog/LICENSE create mode 100644 birthday-cog/README.md create mode 100644 birthday-cog/birthday.py create mode 100644 birthday-cog/info.json diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..cf08287dd92ff6c14300ca3ee1e26cde1bb16570 GIT binary patch literal 6148 zcmeHK%}N6?5T4X(Q&i|d!IK2MR;*PE;$^M%u5QtTO5JsfUEFR;yQN4e>{(yPC-4zG z`YcX-6=w3-yklx!`GjR`WEzp_HChmW z2RE<^mlJFX{6+=Tx0?eWLg+#QufLy!D}T`I_>uIHbMJSeu$Podk1R8lou0|@9G~Uq zZc7f_#7p|Us@FYLqq>xlKkj?}ao8L*3JZHOPP{N~c6CA+G?8+462^fXRAoO7dOFuN z6FkrJjl$A!SSeSEVr#oRDvIHDxl|OJ8ct-F`9-7)0l{m-~Nu&-(fl_M-V7E^;bgT_oMqDf`8 z#9$^JX1A4$KxG%s!df3We#XL5B6Q-c^m Pqdx*#25LxwA64KPPqA(1 literal 0 HcmV?d00001 diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..dfe0770 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +# Auto detect text files and perform LF normalization +* text=auto diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..e62ec04 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ +GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/birthday-cog/LICENSE b/birthday-cog/LICENSE new file mode 100644 index 0000000..963bf1d --- /dev/null +++ b/birthday-cog/LICENSE @@ -0,0 +1,21 @@ +Creative Commons Attribution 4.0 International License + +This work is licensed under the Creative Commons Attribution 4.0 International License. + +To view a copy of this license, visit: +http://creativecommons.org/licenses/by/4.0/ + +or send a letter to: +Creative Commons, PO Box 1866, Mountain View, CA 94042, USA. + +The full text of the license can be found at: +https://creativecommons.org/licenses/by/4.0/legalcode + +You are free to: +- Share — copy and redistribute the material in any medium or format +- Adapt — remix, transform, and build upon the material for any purpose, even commercially. + +Under the following terms: +- Attribution — You must give appropriate credit, provide a link to the license, and indicate if changes were made. You may do so in any reasonable manner, but not in any way that suggests the licensor endorses you or your use. + +No additional restrictions — You may not apply legal terms or technological measures that legally restrict others from doing anything the license permits. diff --git a/birthday-cog/README.md b/birthday-cog/README.md new file mode 100644 index 0000000..6326715 --- /dev/null +++ b/birthday-cog/README.md @@ -0,0 +1,68 @@ +# Birthday Cog for Red-DiscordBot + +This cog for [Red-DiscordBot](https://github.com/Cog-Creators/Red-DiscordBot) allows server administrators to assign a special "birthday role" to users until midnight Pacific Time. + +## Features + +- Assign a birthday role to a user that automatically expires at midnight Pacific Time +- Restrict usage of the birthday command to specific roles +- Ignore role hierarchy when assigning the birthday role +- Admin commands to set up the birthday role and manage permissions + +## Installation + +To install this cog, follow these steps: + +1. Ensure you have Red-DiscordBot V3 installed. +2. Install the required dependencies: + ``` + [p]pip install pytz + ``` +3. Add the repository to your bot: + ``` + [p]repo add birthday-cog https://github.com/yourusername/birthday-cog + ``` +4. Install the cog: + ``` + [p]cog install birthday-cog birthday + ``` + +## Usage + +After installation, load the cog with: +``` +[p]load birthday +``` + +### Admin Setup + +Before the cog can be used, an admin needs to set it up: + +1. Set the birthday role: + ``` + [p]birthdayset role @BirthdayRole + ``` +2. Add roles that can use the birthday command: + ``` + [p]birthdayset addrole @AllowedRole + ``` + +### Using the Birthday Command + +Users with allowed roles can assign the birthday role to a member: +``` +[p]birthday @User +``` + +The birthday role will be automatically removed at midnight Pacific Time. + +## Commands + +- `[p]birthdayset role @Role`: Set the birthday role +- `[p]birthdayset addrole @Role`: Add a role that can use the birthday command +- `[p]birthdayset removerole @Role`: Remove a role from using the birthday command +- `[p]birthday @User`: Assign the birthday role to a user + +## License + +This project is licensed under the Creative Commons Attribution 4.0 International License - see the [LICENSE](LICENSE) file for details. diff --git a/birthday-cog/birthday.py b/birthday-cog/birthday.py new file mode 100644 index 0000000..68c541c --- /dev/null +++ b/birthday-cog/birthday.py @@ -0,0 +1,94 @@ +import discord +from redbot.core import commands, checks +from redbot.core.bot import Red +from redbot.core.config import Config +from datetime import datetime, time, timedelta +import pytz + +class Birthday(commands.Cog): + """A cog to assign a birthday role until midnight Pacific Time.""" + + def __init__(self, bot: Red): + self.bot = bot + self.config = Config.get_conf(self, identifier=1234567890) + default_guild = { + "birthday_role": None, + "allowed_roles": [] + } + self.config.register_guild(**default_guild) + self.birthday_tasks = {} + + @commands.group() + @checks.admin_or_permissions(manage_roles=True) + async def birthdayset(self, ctx): + """Birthday cog settings.""" + pass + + @birthdayset.command() + async def role(self, ctx, role: discord.Role): + """Set the birthday role.""" + await self.config.guild(ctx.guild).birthday_role.set(role.id) + await ctx.send(f"Birthday role set to {role.name}") + + @birthdayset.command() + async def addrole(self, ctx, role: discord.Role): + """Add a role that can use the birthday command.""" + async with self.config.guild(ctx.guild).allowed_roles() as allowed_roles: + if role.id not in allowed_roles: + allowed_roles.append(role.id) + await ctx.send(f"Added {role.name} to the list of roles that can use the birthday command.") + + @birthdayset.command() + async def removerole(self, ctx, role: discord.Role): + """Remove a role from using the birthday command.""" + async with self.config.guild(ctx.guild).allowed_roles() as allowed_roles: + if role.id in allowed_roles: + allowed_roles.remove(role.id) + await ctx.send(f"Removed {role.name} from the list of roles that can use the birthday command.") + + @commands.command() + async def birthday(self, ctx, member: discord.Member): + """Assign the birthday role to a user until midnight Pacific Time.""" + # Check if the user has permission to use this command + allowed_roles = await self.config.guild(ctx.guild).allowed_roles() + if not any(role.id in allowed_roles for role in ctx.author.roles): + return await ctx.send("You don't have permission to use this command.") + + birthday_role_id = await self.config.guild(ctx.guild).birthday_role() + if not birthday_role_id: + return await ctx.send("The birthday role hasn't been set. An admin needs to set it using `[p]birthdayset role`.") + + birthday_role = ctx.guild.get_role(birthday_role_id) + if not birthday_role: + return await ctx.send("The birthday role doesn't exist anymore. Please ask an admin to set it again.") + + # Assign the role, ignoring hierarchy + try: + await member.add_roles(birthday_role, reason="Birthday role") + except discord.Forbidden: + return await ctx.send("I don't have permission to assign that role.") + + await ctx.send(f"🎉 Happy Birthday, {member.mention}! You've been given the {birthday_role.name} role until midnight Pacific Time.") + + # Schedule role removal + pacific_tz = pytz.timezone('US/Pacific') + now = datetime.now(pacific_tz) + midnight = pacific_tz.localize(datetime.combine(now.date() + timedelta(days=1), time.min)) + + if ctx.guild.id in self.birthday_tasks: + self.birthday_tasks[ctx.guild.id].cancel() + + self.birthday_tasks[ctx.guild.id] = self.bot.loop.create_task(self.remove_birthday_role(ctx.guild, member, birthday_role, midnight)) + + async def remove_birthday_role(self, guild, member, role, when): + """Remove the birthday role at the specified time.""" + await discord.utils.sleep_until(when) + try: + await member.remove_roles(role, reason="Birthday role duration expired") + except (discord.Forbidden, discord.HTTPException): + pass # If we can't remove the role, we'll just let it be + finally: + del self.birthday_tasks[guild.id] + +async def setup(bot): + await bot.add_cog(Birthday(bot)) diff --git a/birthday-cog/info.json b/birthday-cog/info.json new file mode 100644 index 0000000..c15919d --- /dev/null +++ b/birthday-cog/info.json @@ -0,0 +1,12 @@ +{ + "author": ["PacNPal"], + "install_msg": "Thank you for installing the Birthday cog! Make sure to set up the birthday role and allowed roles using `[p]birthdayset`.", + "name": "Birthday", + "short": "Assign a birthday role until midnight Pacific Time", + "description": "This cog allows you to assign a special birthday role to users that automatically expires at midnight Pacific Time. It includes features to restrict usage to specific roles and ignore role hierarchy.", + "tags": ["birthday", "role", "temporary"], + "requirements": ["pytz"], + "min_bot_version": "3.5.0", + "max_bot_version": "3.9.9", + "type": "COG" +} From 93dcf09e37a59e2aaffab4b307d81ada6dc2a49c Mon Sep 17 00:00:00 2001 From: pacnpal Date: Sat, 28 Sep 2024 16:58:50 -0400 Subject: [PATCH 04/49] push push --- .gitignore | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 .gitignore diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..9bea433 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ + +.DS_Store From 61e8caae65a5c0412748ebcbfafdf4b4f7f32d4d Mon Sep 17 00:00:00 2001 From: pacnpal Date: Sat, 28 Sep 2024 16:59:23 -0400 Subject: [PATCH 05/49] Update .gitignore --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 9bea433..43322df 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ .DS_Store +.DS_Store From d683c94c50f1ea3fc2b643d9ef59b2948262ff4a Mon Sep 17 00:00:00 2001 From: pacnpal Date: Sat, 28 Sep 2024 17:04:29 -0400 Subject: [PATCH 06/49] Removed dependency --- birthday-cog/README.md | 7 ++----- birthday-cog/birthday.py | 15 ++++++++------- birthday-cog/info.json | 14 ++++++++++---- 3 files changed, 20 insertions(+), 16 deletions(-) diff --git a/birthday-cog/README.md b/birthday-cog/README.md index 6326715..2264aa7 100644 --- a/birthday-cog/README.md +++ b/birthday-cog/README.md @@ -14,15 +14,12 @@ This cog for [Red-DiscordBot](https://github.com/Cog-Creators/Red-DiscordBot) al To install this cog, follow these steps: 1. Ensure you have Red-DiscordBot V3 installed. -2. Install the required dependencies: ``` - [p]pip install pytz - ``` -3. Add the repository to your bot: +2. Add the repository to your bot: ``` [p]repo add birthday-cog https://github.com/yourusername/birthday-cog ``` -4. Install the cog: +3. Install the cog: ``` [p]cog install birthday-cog birthday ``` diff --git a/birthday-cog/birthday.py b/birthday-cog/birthday.py index 68c541c..a86f204 100644 --- a/birthday-cog/birthday.py +++ b/birthday-cog/birthday.py @@ -3,7 +3,6 @@ from redbot.core import commands, checks from redbot.core.bot import Red from redbot.core.config import Config from datetime import datetime, time, timedelta -import pytz class Birthday(commands.Cog): """A cog to assign a birthday role until midnight Pacific Time.""" @@ -71,14 +70,16 @@ class Birthday(commands.Cog): await ctx.send(f"🎉 Happy Birthday, {member.mention}! You've been given the {birthday_role.name} role until midnight Pacific Time.") # Schedule role removal - pacific_tz = pytz.timezone('US/Pacific') - now = datetime.now(pacific_tz) - midnight = pacific_tz.localize(datetime.combine(now.date() + timedelta(days=1), time.min)) - + utc_now = datetime.utcnow() + pacific_offset = timedelta(hours=-8) # Pacific Standard Time offset + pacific_now = utc_now + pacific_offset + pacific_midnight = datetime.combine(pacific_now.date() + timedelta(days=1), time.min) + utc_midnight = pacific_midnight - pacific_offset + if ctx.guild.id in self.birthday_tasks: self.birthday_tasks[ctx.guild.id].cancel() - self.birthday_tasks[ctx.guild.id] = self.bot.loop.create_task(self.remove_birthday_role(ctx.guild, member, birthday_role, midnight)) + self.birthday_tasks[ctx.guild.id] = self.bot.loop.create_task(self.remove_birthday_role(ctx.guild, member, birthday_role, utc_midnight)) async def remove_birthday_role(self, guild, member, role, when): """Remove the birthday role at the specified time.""" @@ -91,4 +92,4 @@ class Birthday(commands.Cog): del self.birthday_tasks[guild.id] async def setup(bot): - await bot.add_cog(Birthday(bot)) + await bot.add_cog(Birthday(bot)) \ No newline at end of file diff --git a/birthday-cog/info.json b/birthday-cog/info.json index c15919d..c68323e 100644 --- a/birthday-cog/info.json +++ b/birthday-cog/info.json @@ -1,12 +1,18 @@ { - "author": ["PacNPal"], + "author": [ + "Your Name" + ], "install_msg": "Thank you for installing the Birthday cog! Make sure to set up the birthday role and allowed roles using `[p]birthdayset`.", "name": "Birthday", "short": "Assign a birthday role until midnight Pacific Time", "description": "This cog allows you to assign a special birthday role to users that automatically expires at midnight Pacific Time. It includes features to restrict usage to specific roles and ignore role hierarchy.", - "tags": ["birthday", "role", "temporary"], - "requirements": ["pytz"], + "tags": [ + "birthday", + "role", + "temporary" + ], + "requirements": [], "min_bot_version": "3.5.0", "max_bot_version": "3.9.9", "type": "COG" -} +} \ No newline at end of file From fe3bb9f0a769213e2571f171f5830351524e23f3 Mon Sep 17 00:00:00 2001 From: pacnpal Date: Sat, 28 Sep 2024 17:05:53 -0400 Subject: [PATCH 07/49] add .gitignore --- .DS_Store | Bin 6148 -> 6148 bytes birthday-cog/.gitignore | 3 +++ 2 files changed, 3 insertions(+) create mode 100644 birthday-cog/.gitignore diff --git a/.DS_Store b/.DS_Store index cf08287dd92ff6c14300ca3ee1e26cde1bb16570..c149aa0918b8ab76d7c8608bf2e15ceb35a8f980 100644 GIT binary patch delta 50 zcmZoMXfc@J&&akhU^gQp+hiW5x$LHtsP@naLVVjqFBdItr$iMw2%%MQqk(zQr=JL3J}b$6tN` DJys3R diff --git a/birthday-cog/.gitignore b/birthday-cog/.gitignore new file mode 100644 index 0000000..43322df --- /dev/null +++ b/birthday-cog/.gitignore @@ -0,0 +1,3 @@ + +.DS_Store +.DS_Store From 44f9fcc94667d2c71a7746a691e77797d2da817a Mon Sep 17 00:00:00 2001 From: pacnpal Date: Sat, 28 Sep 2024 17:06:16 -0400 Subject: [PATCH 08/49] Delete .DS_Store --- .DS_Store | Bin 6148 -> 0 bytes 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 .DS_Store diff --git a/.DS_Store b/.DS_Store deleted file mode 100644 index c149aa0918b8ab76d7c8608bf2e15ceb35a8f980..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 6148 zcmeHK%}T>S5T317x2VvAf+tz z2luc6%`r9w{-Ofv+bx0*A@m@H&)-kNtv^V*ek6V5Jo()yOww}sh2>`Qvvc!&o-gog zw=D;5>ZSdp=JhVs=uFDUfA4$#dDt2>ipz&GPQ5U0^>jiQw2*Rj5ypWW)MP&n5}oUs z30~lZMsamGtX3)|QK{~XN@BRTT`q~;o$6>*;4AB!`=^b&s1wTvBPzq+pSC57@9>D7 ziSHLA&B(|7D)K~9bi3s?Wv6RaTs!)S+mZFU6^z5h)9cCE^TE&jU@CsM{dq6PW=qtP z0;B*bFtq~q%;XDGXHo(wKnnbK1=RT<&=oosGlTl*z($tq`3h$fZU5`&p^j0?+iEM^8xIxt&&F#BX?D-@=mj_V6e2j&>0mJ}cbzA7+dhDCM% zV_7q){{NapBT|4A_*V+BeBG_r@RjV{I`(qvt`+Dv=*ko?Gx(8$9eoueS6#)c=-MzY XR0q+qm>I+f8vPN_GEhSb{Hg+P9+7qg From 16228c20b11a88e0a6e6c44fa4156ae74c07808c Mon Sep 17 00:00:00 2001 From: pacnpal Date: Sat, 28 Sep 2024 17:07:06 -0400 Subject: [PATCH 09/49] Update README.md --- birthday-cog/README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/birthday-cog/README.md b/birthday-cog/README.md index 2264aa7..907f86b 100644 --- a/birthday-cog/README.md +++ b/birthday-cog/README.md @@ -14,7 +14,6 @@ This cog for [Red-DiscordBot](https://github.com/Cog-Creators/Red-DiscordBot) al To install this cog, follow these steps: 1. Ensure you have Red-DiscordBot V3 installed. - ``` 2. Add the repository to your bot: ``` [p]repo add birthday-cog https://github.com/yourusername/birthday-cog From 4f11dfd4f3ebb3ab924e0477f19a55092c42a42a Mon Sep 17 00:00:00 2001 From: pacnpal Date: Sat, 28 Sep 2024 17:07:49 -0400 Subject: [PATCH 10/49] fix url --- birthday-cog/README.md | 2 +- birthday-cog/info.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/birthday-cog/README.md b/birthday-cog/README.md index 907f86b..7022243 100644 --- a/birthday-cog/README.md +++ b/birthday-cog/README.md @@ -16,7 +16,7 @@ To install this cog, follow these steps: 1. Ensure you have Red-DiscordBot V3 installed. 2. Add the repository to your bot: ``` - [p]repo add birthday-cog https://github.com/yourusername/birthday-cog + [p]repo add birthday-cog https://github.com/pacnpal/birthday-cog ``` 3. Install the cog: ``` diff --git a/birthday-cog/info.json b/birthday-cog/info.json index c68323e..145ccbb 100644 --- a/birthday-cog/info.json +++ b/birthday-cog/info.json @@ -1,6 +1,6 @@ { "author": [ - "Your Name" + "PacNPal" ], "install_msg": "Thank you for installing the Birthday cog! Make sure to set up the birthday role and allowed roles using `[p]birthdayset`.", "name": "Birthday", From 1f325904b6a282f825ca18e4c02dd5618a6aa5b6 Mon Sep 17 00:00:00 2001 From: pacnpal Date: Sat, 28 Sep 2024 17:10:45 -0400 Subject: [PATCH 11/49] Update README.md --- birthday-cog/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/birthday-cog/README.md b/birthday-cog/README.md index 7022243..7f21fab 100644 --- a/birthday-cog/README.md +++ b/birthday-cog/README.md @@ -16,7 +16,7 @@ To install this cog, follow these steps: 1. Ensure you have Red-DiscordBot V3 installed. 2. Add the repository to your bot: ``` - [p]repo add birthday-cog https://github.com/pacnpal/birthday-cog + [p]repo add Pac-cogs https://github.com/pacnpal/Pac-cogs ``` 3. Install the cog: ``` From 7b45509e6f849d9589d6f201c1e4802aade557e1 Mon Sep 17 00:00:00 2001 From: pacnpal Date: Sat, 28 Sep 2024 17:11:35 -0400 Subject: [PATCH 12/49] Update README.md --- birthday-cog/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/birthday-cog/README.md b/birthday-cog/README.md index 7f21fab..36d9bff 100644 --- a/birthday-cog/README.md +++ b/birthday-cog/README.md @@ -20,7 +20,7 @@ To install this cog, follow these steps: ``` 3. Install the cog: ``` - [p]cog install birthday-cog birthday + [p]cog install Pac-cogs birthday ``` ## Usage From d392a22d78a385079b519edfb48379a280a07877 Mon Sep 17 00:00:00 2001 From: pacnpal Date: Sat, 28 Sep 2024 17:12:25 -0400 Subject: [PATCH 13/49] change to birthday --- {birthday-cog => birthday}/.gitignore | 0 {birthday-cog => birthday}/LICENSE | 0 {birthday-cog => birthday}/README.md | 0 {birthday-cog => birthday}/birthday.py | 0 {birthday-cog => birthday}/info.json | 0 5 files changed, 0 insertions(+), 0 deletions(-) rename {birthday-cog => birthday}/.gitignore (100%) rename {birthday-cog => birthday}/LICENSE (100%) rename {birthday-cog => birthday}/README.md (100%) rename {birthday-cog => birthday}/birthday.py (100%) rename {birthday-cog => birthday}/info.json (100%) diff --git a/birthday-cog/.gitignore b/birthday/.gitignore similarity index 100% rename from birthday-cog/.gitignore rename to birthday/.gitignore diff --git a/birthday-cog/LICENSE b/birthday/LICENSE similarity index 100% rename from birthday-cog/LICENSE rename to birthday/LICENSE diff --git a/birthday-cog/README.md b/birthday/README.md similarity index 100% rename from birthday-cog/README.md rename to birthday/README.md diff --git a/birthday-cog/birthday.py b/birthday/birthday.py similarity index 100% rename from birthday-cog/birthday.py rename to birthday/birthday.py diff --git a/birthday-cog/info.json b/birthday/info.json similarity index 100% rename from birthday-cog/info.json rename to birthday/info.json From b66a49474fcf2fced35bb02cd4d8dda3453974b6 Mon Sep 17 00:00:00 2001 From: pacnpal Date: Sat, 28 Sep 2024 17:16:54 -0400 Subject: [PATCH 14/49] Info.json --- birthday/info.json | 18 ------------------ info.json | 18 ++++++++++++++++++ 2 files changed, 18 insertions(+), 18 deletions(-) delete mode 100644 birthday/info.json create mode 100644 info.json diff --git a/birthday/info.json b/birthday/info.json deleted file mode 100644 index 145ccbb..0000000 --- a/birthday/info.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "author": [ - "PacNPal" - ], - "install_msg": "Thank you for installing the Birthday cog! Make sure to set up the birthday role and allowed roles using `[p]birthdayset`.", - "name": "Birthday", - "short": "Assign a birthday role until midnight Pacific Time", - "description": "This cog allows you to assign a special birthday role to users that automatically expires at midnight Pacific Time. It includes features to restrict usage to specific roles and ignore role hierarchy.", - "tags": [ - "birthday", - "role", - "temporary" - ], - "requirements": [], - "min_bot_version": "3.5.0", - "max_bot_version": "3.9.9", - "type": "COG" -} \ No newline at end of file diff --git a/info.json b/info.json new file mode 100644 index 0000000..c5b9ac7 --- /dev/null +++ b/info.json @@ -0,0 +1,18 @@ +{ + "author": [ + "PacNPal" + ], + "install_msg": "Thank you for installing the Pac-cogs repo!", + "name": "Pac-cogs", + "short": "Very cool cogs!", + "description": "Right now, just a birthday cog.", + "tags": [ + "birthday", + "role", + "temporary" + ], + "requirements": [], + "min_bot_version": "3.5.0", + "max_bot_version": "3.9.9", + "type": "COG" +} \ No newline at end of file From 0a1cae82dce69bd936ad8a70194763a6ea69547e Mon Sep 17 00:00:00 2001 From: pacnpal Date: Sat, 28 Sep 2024 17:19:34 -0400 Subject: [PATCH 15/49] Update info.json --- info.json | 11 +---------- 1 file changed, 1 insertion(+), 10 deletions(-) diff --git a/info.json b/info.json index c5b9ac7..55d2fc2 100644 --- a/info.json +++ b/info.json @@ -5,14 +5,5 @@ "install_msg": "Thank you for installing the Pac-cogs repo!", "name": "Pac-cogs", "short": "Very cool cogs!", - "description": "Right now, just a birthday cog.", - "tags": [ - "birthday", - "role", - "temporary" - ], - "requirements": [], - "min_bot_version": "3.5.0", - "max_bot_version": "3.9.9", - "type": "COG" + "description": "Right now, just a birthday cog." } \ No newline at end of file From 75b8d5af426d1fb9a112dcb255ef0e58c405047a Mon Sep 17 00:00:00 2001 From: pacnpal Date: Sat, 28 Sep 2024 17:22:31 -0400 Subject: [PATCH 16/49] Fix --- LICENSE | 2 +- birthday/README.md | 8 ++++++++ birthday/__init__.py | 7 +++++++ 3 files changed, 16 insertions(+), 1 deletion(-) create mode 100644 birthday/__init__.py diff --git a/LICENSE b/LICENSE index e62ec04..f9d9d74 100644 --- a/LICENSE +++ b/LICENSE @@ -657,7 +657,7 @@ notice like this when it starts in an interactive mode: This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. -The hypothetical commands `show w' and `show c' should show the appropriate +The hypothetical commands `show w' and`show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". diff --git a/birthday/README.md b/birthday/README.md index 36d9bff..03ee037 100644 --- a/birthday/README.md +++ b/birthday/README.md @@ -15,10 +15,13 @@ To install this cog, follow these steps: 1. Ensure you have Red-DiscordBot V3 installed. 2. Add the repository to your bot: + ``` [p]repo add Pac-cogs https://github.com/pacnpal/Pac-cogs ``` + 3. Install the cog: + ``` [p]cog install Pac-cogs birthday ``` @@ -26,6 +29,7 @@ To install this cog, follow these steps: ## Usage After installation, load the cog with: + ``` [p]load birthday ``` @@ -35,10 +39,13 @@ After installation, load the cog with: Before the cog can be used, an admin needs to set it up: 1. Set the birthday role: + ``` [p]birthdayset role @BirthdayRole ``` + 2. Add roles that can use the birthday command: + ``` [p]birthdayset addrole @AllowedRole ``` @@ -46,6 +53,7 @@ Before the cog can be used, an admin needs to set it up: ### Using the Birthday Command Users with allowed roles can assign the birthday role to a member: + ``` [p]birthday @User ``` diff --git a/birthday/__init__.py b/birthday/__init__.py new file mode 100644 index 0000000..79de37e --- /dev/null +++ b/birthday/__init__.py @@ -0,0 +1,7 @@ +from .birthday import Birthday + +__red_end_user_data_statement__ = "This allows users with the set roles to give the birthday role to users until the end of the day." + + +def setup(bot): + bot.add_cog(Birthday(bot)) \ No newline at end of file From dc0ac456b0ba4481f3135bfd1f5646fc85babeb2 Mon Sep 17 00:00:00 2001 From: pacnpal Date: Sat, 28 Sep 2024 17:28:38 -0400 Subject: [PATCH 17/49] Update __init__.py --- birthday/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/birthday/__init__.py b/birthday/__init__.py index 79de37e..0324b95 100644 --- a/birthday/__init__.py +++ b/birthday/__init__.py @@ -4,4 +4,4 @@ __red_end_user_data_statement__ = "This allows users with the set roles to give def setup(bot): - bot.add_cog(Birthday(bot)) \ No newline at end of file + await bot.add_cog(Birthday(bot)) \ No newline at end of file From 3a0ba314361ccc3fd703f54090b964ebe479c1b4 Mon Sep 17 00:00:00 2001 From: pacnpal Date: Sat, 28 Sep 2024 17:31:55 -0400 Subject: [PATCH 18/49] Update birthday.py --- birthday/birthday.py | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/birthday/birthday.py b/birthday/birthday.py index a86f204..bb1706b 100644 --- a/birthday/birthday.py +++ b/birthday/birthday.py @@ -89,7 +89,4 @@ class Birthday(commands.Cog): except (discord.Forbidden, discord.HTTPException): pass # If we can't remove the role, we'll just let it be finally: - del self.birthday_tasks[guild.id] - -async def setup(bot): - await bot.add_cog(Birthday(bot)) \ No newline at end of file + del self.birthday_tasks[guild.id] \ No newline at end of file From 51e5b580228d9e431c6e514618935e8d68bab485 Mon Sep 17 00:00:00 2001 From: pacnpal Date: Sat, 28 Sep 2024 17:35:03 -0400 Subject: [PATCH 19/49] Update __init__.py --- birthday/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/birthday/__init__.py b/birthday/__init__.py index 0324b95..9587a2d 100644 --- a/birthday/__init__.py +++ b/birthday/__init__.py @@ -3,5 +3,5 @@ from .birthday import Birthday __red_end_user_data_statement__ = "This allows users with the set roles to give the birthday role to users until the end of the day." -def setup(bot): +async def setup(bot): await bot.add_cog(Birthday(bot)) \ No newline at end of file From 90c0085b7e853fbb1f37e0ec0eba9737de767e6a Mon Sep 17 00:00:00 2001 From: pacnpal Date: Sat, 28 Sep 2024 21:21:29 -0400 Subject: [PATCH 20/49] Updated with new features --- birthday/README.md | 98 ++++++++++++++++++++++++-------------------- birthday/birthday.py | 61 ++++++++++++++++++++++----- 2 files changed, 104 insertions(+), 55 deletions(-) diff --git a/birthday/README.md b/birthday/README.md index 03ee037..8072132 100644 --- a/birthday/README.md +++ b/birthday/README.md @@ -1,13 +1,6 @@ # Birthday Cog for Red-DiscordBot -This cog for [Red-DiscordBot](https://github.com/Cog-Creators/Red-DiscordBot) allows server administrators to assign a special "birthday role" to users until midnight Pacific Time. - -## Features - -- Assign a birthday role to a user that automatically expires at midnight Pacific Time -- Restrict usage of the birthday command to specific roles -- Ignore role hierarchy when assigning the birthday role -- Admin commands to set up the birthday role and manage permissions +This cog allows you to assign a special role to users on their birthday and send them a celebratory message with cake (or pie) emojis! ## Installation @@ -15,58 +8,73 @@ To install this cog, follow these steps: 1. Ensure you have Red-DiscordBot V3 installed. 2. Add the repository to your bot: - ``` [p]repo add Pac-cogs https://github.com/pacnpal/Pac-cogs ``` - -3. Install the cog: - +3. Install the Birthday cog: ``` [p]cog install Pac-cogs birthday ``` +4. Load the cog: + ``` + [p]load birthday + ``` + +Replace `[p]` with your bot's prefix. + +## Setup + +Before using the cog, you need to set it up: + +1. Set the birthday role: + ``` + [p]birthdayset role @Birthday + ``` + **Note:** The bot's role must be above the birthday role in the server's role hierarchy, but users assigning the birthday role do not need to have a role above it. + +2. Add roles that can use the birthday command: + ``` + [p]birthdayset addrole @Moderator + ``` +3. (Optional) Set the timezone for role expiration: + ``` + [p]birthdayset timezone America/New_York + ``` +4. (Optional) Set a specific channel for birthday announcements: + ``` + [p]birthdayset channel #birthdays + ``` ## Usage -After installation, load the cog with: - -``` -[p]load birthday -``` - -### Admin Setup - -Before the cog can be used, an admin needs to set it up: - -1. Set the birthday role: - - ``` - [p]birthdayset role @BirthdayRole - ``` - -2. Add roles that can use the birthday command: - - ``` - [p]birthdayset addrole @AllowedRole - ``` - -### Using the Birthday Command - -Users with allowed roles can assign the birthday role to a member: - +To assign the birthday role to a user: ``` [p]birthday @User ``` -The birthday role will be automatically removed at midnight Pacific Time. +This will assign the birthday role to the user and send a celebratory message with random cake (or pie) emojis. The role will be automatically removed at midnight in the specified timezone. + +## Features + +- Assigns a special birthday role to users +- Sends a celebratory message with random cake (or pie) emojis +- Automatically removes the birthday role at midnight +- Configurable timezone for role expiration +- Option to set a specific channel for birthday announcements +- Restricts usage of the birthday command to specified roles +- Users can assign the birthday role without needing a role higher than it in the hierarchy ## Commands -- `[p]birthdayset role @Role`: Set the birthday role -- `[p]birthdayset addrole @Role`: Add a role that can use the birthday command -- `[p]birthdayset removerole @Role`: Remove a role from using the birthday command -- `[p]birthday @User`: Assign the birthday role to a user +- `[p]birthdayset role`: Set the birthday role +- `[p]birthdayset addrole`: Add a role that can use the birthday command +- `[p]birthdayset removerole`: Remove a role from using the birthday command +- `[p]birthdayset timezone`: Set the timezone for the birthday role expiration +- `[p]birthdayset channel`: Set the channel for birthday announcements +- `[p]birthday`: Assign the birthday role to a user -## License +## Support -This project is licensed under the Creative Commons Attribution 4.0 International License - see the [LICENSE](LICENSE) file for details. +If you encounter any issues or have questions, please open an issue on the [GitHub repository](https://github.com/pacnpal/Pac-cogs). + +Enjoy celebrating birthdays with your Discord community! \ No newline at end of file diff --git a/birthday/birthday.py b/birthday/birthday.py index bb1706b..b14a273 100644 --- a/birthday/birthday.py +++ b/birthday/birthday.py @@ -3,16 +3,20 @@ from redbot.core import commands, checks from redbot.core.bot import Red from redbot.core.config import Config from datetime import datetime, time, timedelta +from zoneinfo import ZoneInfo, ZoneInfoNotFoundError +import random class Birthday(commands.Cog): - """A cog to assign a birthday role until midnight Pacific Time.""" + """A cog to assign a birthday role until midnight in a specified timezone.""" def __init__(self, bot: Red): self.bot = bot self.config = Config.get_conf(self, identifier=1234567890) default_guild = { "birthday_role": None, - "allowed_roles": [] + "allowed_roles": [], + "timezone": "UTC", + "birthday_channel": None } self.config.register_guild(**default_guild) self.birthday_tasks = {} @@ -45,9 +49,27 @@ class Birthday(commands.Cog): allowed_roles.remove(role.id) await ctx.send(f"Removed {role.name} from the list of roles that can use the birthday command.") + @birthdayset.command() + @checks.is_owner() + async def timezone(self, ctx, tz: str): + """Set the timezone for the birthday role expiration.""" + try: + ZoneInfo(tz) + await self.config.guild(ctx.guild).timezone.set(tz) + await ctx.send(f"Timezone set to {tz}") + except ZoneInfoNotFoundError: + await ctx.send(f"Invalid timezone: {tz}. Please use a valid IANA time zone identifier.") + + @birthdayset.command() + @checks.is_owner() + async def channel(self, ctx, channel: discord.TextChannel): + """Set the channel for birthday announcements.""" + await self.config.guild(ctx.guild).birthday_channel.set(channel.id) + await ctx.send(f"Birthday announcement channel set to {channel.mention}") + @commands.command() async def birthday(self, ctx, member: discord.Member): - """Assign the birthday role to a user until midnight Pacific Time.""" + """Assign the birthday role to a user until midnight in the set timezone.""" # Check if the user has permission to use this command allowed_roles = await self.config.guild(ctx.guild).allowed_roles() if not any(role.id in allowed_roles for role in ctx.author.roles): @@ -67,19 +89,38 @@ class Birthday(commands.Cog): except discord.Forbidden: return await ctx.send("I don't have permission to assign that role.") - await ctx.send(f"🎉 Happy Birthday, {member.mention}! You've been given the {birthday_role.name} role until midnight Pacific Time.") + timezone = await self.config.guild(ctx.guild).timezone() + + # Get the birthday announcement channel + birthday_channel_id = await self.config.guild(ctx.guild).birthday_channel() + if birthday_channel_id: + channel = self.bot.get_channel(birthday_channel_id) + else: + channel = ctx.channel + + # Generate birthday message with random cakes (or pie) + cakes = random.randint(0, 5) + if cakes == 0: + message = f"🎉 Happy Birthday, {member.mention}! Sorry, out of cake today! Here's pie instead: 🥧" + else: + message = f"🎉 Happy Birthday, {member.mention}! Here's your cake{'s' if cakes > 1 else ''}: " + "🎂" * cakes + + await channel.send(message) # Schedule role removal - utc_now = datetime.utcnow() - pacific_offset = timedelta(hours=-8) # Pacific Standard Time offset - pacific_now = utc_now + pacific_offset - pacific_midnight = datetime.combine(pacific_now.date() + timedelta(days=1), time.min) - utc_midnight = pacific_midnight - pacific_offset + try: + tz = ZoneInfo(timezone) + except ZoneInfoNotFoundError: + await ctx.send(f"Warning: Invalid timezone set. Defaulting to UTC.") + tz = ZoneInfo("UTC") + + now = datetime.now(tz) + midnight = datetime.combine(now.date() + timedelta(days=1), time.min).replace(tzinfo=tz) if ctx.guild.id in self.birthday_tasks: self.birthday_tasks[ctx.guild.id].cancel() - self.birthday_tasks[ctx.guild.id] = self.bot.loop.create_task(self.remove_birthday_role(ctx.guild, member, birthday_role, utc_midnight)) + self.birthday_tasks[ctx.guild.id] = self.bot.loop.create_task(self.remove_birthday_role(ctx.guild, member, birthday_role, midnight)) async def remove_birthday_role(self, guild, member, role, when): """Remove the birthday role at the specified time.""" From b9a81d1c2a3ac4d2e13e40695dea642761b75342 Mon Sep 17 00:00:00 2001 From: pacnpal Date: Sat, 28 Sep 2024 21:31:22 -0400 Subject: [PATCH 21/49] birthday fixes --- birthday/README.md | 7 +++---- birthday/birthday.py | 2 ++ 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/birthday/README.md b/birthday/README.md index 8072132..9bcb647 100644 --- a/birthday/README.md +++ b/birthday/README.md @@ -44,6 +44,7 @@ Before using the cog, you need to set it up: ``` [p]birthdayset channel #birthdays ``` + If not set, the birthday message will be sent in the channel where the command is used. ## Usage @@ -60,7 +61,7 @@ This will assign the birthday role to the user and send a celebratory message wi - Sends a celebratory message with random cake (or pie) emojis - Automatically removes the birthday role at midnight - Configurable timezone for role expiration -- Option to set a specific channel for birthday announcements +- Option to set a specific channel for birthday announcements (defaults to the channel where the command is used) - Restricts usage of the birthday command to specified roles - Users can assign the birthday role without needing a role higher than it in the hierarchy @@ -75,6 +76,4 @@ This will assign the birthday role to the user and send a celebratory message wi ## Support -If you encounter any issues or have questions, please open an issue on the [GitHub repository](https://github.com/pacnpal/Pac-cogs). - -Enjoy celebrating birthdays with your Discord community! \ No newline at end of file +If you encounter any issues or have questions, please open an issue on the [GitHub repository](https://github.com/pacnpal/Pac-cogs). \ No newline at end of file diff --git a/birthday/birthday.py b/birthday/birthday.py index b14a273..5cc2459 100644 --- a/birthday/birthday.py +++ b/birthday/birthday.py @@ -95,6 +95,8 @@ class Birthday(commands.Cog): birthday_channel_id = await self.config.guild(ctx.guild).birthday_channel() if birthday_channel_id: channel = self.bot.get_channel(birthday_channel_id) + if not channel: # If the set channel doesn't exist anymore + channel = ctx.channel else: channel = ctx.channel From 90c3d997f51eaee8eb84ef2fba4eafffb145b69f Mon Sep 17 00:00:00 2001 From: pacnpal Date: Sat, 28 Sep 2024 22:10:53 -0400 Subject: [PATCH 22/49] Create README.md --- README.md | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 README.md diff --git a/README.md b/README.md new file mode 100644 index 0000000..b434706 --- /dev/null +++ b/README.md @@ -0,0 +1,34 @@ +# Pac-cogs - RedBot Cogs Collection + +Welcome to **Pac-cogs**, a collection of custom cogs for [RedBot](https://github.com/Cog-Creators/Red-DiscordBot). These cogs are designed to add extra functionality to your RedBot instance on Discord. + +## Cogs Overview + +| Cog Name | Description | +|------------|--------------------------------------------------| +| **Birthday** | Assigns a special birthday role to users and sends a celebratory message with random cake or pie emojis. Automatically removes the birthday role at midnight, with a configurable timezone. Offers the option to set a specific announcement channel and restricts usage to specified roles. Users can assign the role without needing a higher role in the hierarchy. | + +## Installation + +To install the cogs in this repository, follow these steps: + +1. Ensure you have [RedBot](https://github.com/Cog-Creators/Red-DiscordBot) set up. +2. Add this repository to your RedBot instance: + + ```bash + [p]repo add Pac-cogs https://github.com/pacnpal/Pac-cogs + ``` + +3. Install the **birthday** cog: + + ```bash + [p]cog install Pac-cogs birthday + ``` + +4. Load the installed cog: + + ```bash + [p]load birthday + ``` + +For more details on setting up and managing RedBot, visit the [RedBot documentation](https://docs.discord.red). From 79ec28d15992f6b3f0d0050edd1abf317693e37b Mon Sep 17 00:00:00 2001 From: pacnpal Date: Sat, 28 Sep 2024 22:13:34 -0400 Subject: [PATCH 23/49] Update README.md --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index b434706..b64ae32 100644 --- a/README.md +++ b/README.md @@ -19,16 +19,16 @@ To install the cogs in this repository, follow these steps: [p]repo add Pac-cogs https://github.com/pacnpal/Pac-cogs ``` -3. Install the **birthday** cog: +3. Install a cog: ```bash - [p]cog install Pac-cogs birthday + [p]cog install Pac-cogs ``` 4. Load the installed cog: ```bash - [p]load birthday + [p]load ``` For more details on setting up and managing RedBot, visit the [RedBot documentation](https://docs.discord.red). From cae9ce5fea3e599fd4e4d2aeb006ec3df0ce6314 Mon Sep 17 00:00:00 2001 From: pacnpal Date: Sat, 28 Sep 2024 22:18:24 -0400 Subject: [PATCH 24/49] Update README.md --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index b64ae32..701b2b1 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# Pac-cogs - RedBot Cogs Collection +# Pac-cogs - Red Discord Bot Cogs Collection Welcome to **Pac-cogs**, a collection of custom cogs for [RedBot](https://github.com/Cog-Creators/Red-DiscordBot). These cogs are designed to add extra functionality to your RedBot instance on Discord. @@ -12,8 +12,8 @@ Welcome to **Pac-cogs**, a collection of custom cogs for [RedBot](https://github To install the cogs in this repository, follow these steps: -1. Ensure you have [RedBot](https://github.com/Cog-Creators/Red-DiscordBot) set up. -2. Add this repository to your RedBot instance: +1. Ensure you have [Red](https://github.com/Cog-Creators/Red-DiscordBot) set up. +2. Add this repository to your Red instance: ```bash [p]repo add Pac-cogs https://github.com/pacnpal/Pac-cogs @@ -31,4 +31,4 @@ To install the cogs in this repository, follow these steps: [p]load ``` -For more details on setting up and managing RedBot, visit the [RedBot documentation](https://docs.discord.red). +For more details on setting up and managing Red, visit the [RedBot documentation](https://docs.discord.red). From c5f40f4ba383e3a3dc52b0ede07a34d4d3c5cf03 Mon Sep 17 00:00:00 2001 From: pacnpal Date: Sat, 28 Sep 2024 22:18:38 -0400 Subject: [PATCH 25/49] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 701b2b1..4ed7f18 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Pac-cogs - Red Discord Bot Cogs Collection -Welcome to **Pac-cogs**, a collection of custom cogs for [RedBot](https://github.com/Cog-Creators/Red-DiscordBot). These cogs are designed to add extra functionality to your RedBot instance on Discord. +Welcome to **Pac-cogs**, a collection of custom cogs for [Red](https://github.com/Cog-Creators/Red-DiscordBot). These cogs are designed to add extra functionality to your RedBot instance on Discord. ## Cogs Overview From af0ee790d138219a1d2dc59ec289a58d9e43390a Mon Sep 17 00:00:00 2001 From: pacnpal Date: Sat, 28 Sep 2024 22:18:50 -0400 Subject: [PATCH 26/49] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 4ed7f18..f1ff33c 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Pac-cogs - Red Discord Bot Cogs Collection -Welcome to **Pac-cogs**, a collection of custom cogs for [Red](https://github.com/Cog-Creators/Red-DiscordBot). These cogs are designed to add extra functionality to your RedBot instance on Discord. +Welcome to **Pac-cogs**, a collection of custom cogs for [Red](https://github.com/Cog-Creators/Red-DiscordBot). These cogs are designed to add extra functionality to your Red bot instance on Discord. ## Cogs Overview From adf45c96f9e5266cf6a96e99b7770a4ee4d871ee Mon Sep 17 00:00:00 2001 From: pacnpal Date: Sat, 28 Sep 2024 22:19:04 -0400 Subject: [PATCH 27/49] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index f1ff33c..af956e0 100644 --- a/README.md +++ b/README.md @@ -31,4 +31,4 @@ To install the cogs in this repository, follow these steps: [p]load ``` -For more details on setting up and managing Red, visit the [RedBot documentation](https://docs.discord.red). +For more details on setting up and managing Red, visit the [Red documentation](https://docs.discord.red). From b30c786103de3e1caae6753b91e69a4869988bf7 Mon Sep 17 00:00:00 2001 From: pacnpal <183241239+pacnpal@users.noreply.github.com> Date: Sun, 29 Sep 2024 00:18:10 -0400 Subject: [PATCH 28/49] yeah I changed some stuff --- birthday/README.md | 18 ++++++++- birthday/birthday.py | 90 ++++++++++++++++++++++++++++---------------- 2 files changed, 74 insertions(+), 34 deletions(-) diff --git a/birthday/README.md b/birthday/README.md index 9bcb647..5ebd86c 100644 --- a/birthday/README.md +++ b/birthday/README.md @@ -8,14 +8,19 @@ To install this cog, follow these steps: 1. Ensure you have Red-DiscordBot V3 installed. 2. Add the repository to your bot: + ``` [p]repo add Pac-cogs https://github.com/pacnpal/Pac-cogs ``` + 3. Install the Birthday cog: + ``` [p]cog install Pac-cogs birthday ``` + 4. Load the cog: + ``` [p]load birthday ``` @@ -27,28 +32,37 @@ Replace `[p]` with your bot's prefix. Before using the cog, you need to set it up: 1. Set the birthday role: + ``` [p]birthdayset role @Birthday ``` + **Note:** The bot's role must be above the birthday role in the server's role hierarchy, but users assigning the birthday role do not need to have a role above it. 2. Add roles that can use the birthday command: + ``` [p]birthdayset addrole @Moderator ``` + 3. (Optional) Set the timezone for role expiration: + ``` [p]birthdayset timezone America/New_York ``` + 4. (Optional) Set a specific channel for birthday announcements: + ``` [p]birthdayset channel #birthdays ``` + If not set, the birthday message will be sent in the channel where the command is used. ## Usage To assign the birthday role to a user: + ``` [p]birthday @User ``` @@ -59,7 +73,7 @@ This will assign the birthday role to the user and send a celebratory message wi - Assigns a special birthday role to users - Sends a celebratory message with random cake (or pie) emojis -- Automatically removes the birthday role at midnight +- Automatically removes the birthday role at midnight, temporarily stores so tasks will complete even if cog is reloaded - Configurable timezone for role expiration - Option to set a specific channel for birthday announcements (defaults to the channel where the command is used) - Restricts usage of the birthday command to specified roles @@ -76,4 +90,4 @@ This will assign the birthday role to the user and send a celebratory message wi ## Support -If you encounter any issues or have questions, please open an issue on the [GitHub repository](https://github.com/pacnpal/Pac-cogs). \ No newline at end of file +If you encounter any issues or have questions, please open an issue on the [GitHub repository](https://github.com/pacnpal/Pac-cogs). diff --git a/birthday/birthday.py b/birthday/birthday.py index 5cc2459..f2b16dd 100644 --- a/birthday/birthday.py +++ b/birthday/birthday.py @@ -16,7 +16,8 @@ class Birthday(commands.Cog): "birthday_role": None, "allowed_roles": [], "timezone": "UTC", - "birthday_channel": None + "birthday_channel": None, + "scheduled_tasks": {} } self.config.register_guild(**default_guild) self.birthday_tasks = {} @@ -28,27 +29,12 @@ class Birthday(commands.Cog): pass @birthdayset.command() + @checks.is_owner() async def role(self, ctx, role: discord.Role): """Set the birthday role.""" await self.config.guild(ctx.guild).birthday_role.set(role.id) await ctx.send(f"Birthday role set to {role.name}") - @birthdayset.command() - async def addrole(self, ctx, role: discord.Role): - """Add a role that can use the birthday command.""" - async with self.config.guild(ctx.guild).allowed_roles() as allowed_roles: - if role.id not in allowed_roles: - allowed_roles.append(role.id) - await ctx.send(f"Added {role.name} to the list of roles that can use the birthday command.") - - @birthdayset.command() - async def removerole(self, ctx, role: discord.Role): - """Remove a role from using the birthday command.""" - async with self.config.guild(ctx.guild).allowed_roles() as allowed_roles: - if role.id in allowed_roles: - allowed_roles.remove(role.id) - await ctx.send(f"Removed {role.name} from the list of roles that can use the birthday command.") - @birthdayset.command() @checks.is_owner() async def timezone(self, ctx, tz: str): @@ -67,6 +53,22 @@ class Birthday(commands.Cog): await self.config.guild(ctx.guild).birthday_channel.set(channel.id) await ctx.send(f"Birthday announcement channel set to {channel.mention}") + @birthdayset.command() + async def addrole(self, ctx, role: discord.Role): + """Add a role that can use the birthday command.""" + async with self.config.guild(ctx.guild).allowed_roles() as allowed_roles: + if role.id not in allowed_roles: + allowed_roles.append(role.id) + await ctx.send(f"Added {role.name} to the list of roles that can use the birthday command.") + + @birthdayset.command() + async def removerole(self, ctx, role: discord.Role): + """Remove a role from using the birthday command.""" + async with self.config.guild(ctx.guild).allowed_roles() as allowed_roles: + if role.id in allowed_roles: + allowed_roles.remove(role.id) + await ctx.send(f"Removed {role.name} from the list of roles that can use the birthday command.") + @commands.command() async def birthday(self, ctx, member: discord.Member): """Assign the birthday role to a user until midnight in the set timezone.""" @@ -78,7 +80,7 @@ class Birthday(commands.Cog): birthday_role_id = await self.config.guild(ctx.guild).birthday_role() if not birthday_role_id: return await ctx.send("The birthday role hasn't been set. An admin needs to set it using `[p]birthdayset role`.") - + birthday_role = ctx.guild.get_role(birthday_role_id) if not birthday_role: return await ctx.send("The birthday role doesn't exist anymore. Please ask an admin to set it again.") @@ -89,8 +91,13 @@ class Birthday(commands.Cog): except discord.Forbidden: return await ctx.send("I don't have permission to assign that role.") - timezone = await self.config.guild(ctx.guild).timezone() - + # Generate birthday message with random cakes (or pie) + cakes = random.randint(0, 5) + if cakes == 0: + message = f"🎉 Happy Birthday, {member.mention}! Sorry, out of cake today! Here's pie instead: 🥧" + else: + message = f"🎉 Happy Birthday, {member.mention}! Here's your cake{'s' if cakes > 1 else ''}: " + "🎂" * cakes + # Get the birthday announcement channel birthday_channel_id = await self.config.guild(ctx.guild).birthday_channel() if birthday_channel_id: @@ -100,16 +107,10 @@ class Birthday(commands.Cog): else: channel = ctx.channel - # Generate birthday message with random cakes (or pie) - cakes = random.randint(0, 5) - if cakes == 0: - message = f"🎉 Happy Birthday, {member.mention}! Sorry, out of cake today! Here's pie instead: 🥧" - else: - message = f"🎉 Happy Birthday, {member.mention}! Here's your cake{'s' if cakes > 1 else ''}: " + "🎂" * cakes - await channel.send(message) # Schedule role removal + timezone = await self.config.guild(ctx.guild).timezone() try: tz = ZoneInfo(timezone) except ZoneInfoNotFoundError: @@ -119,10 +120,15 @@ class Birthday(commands.Cog): now = datetime.now(tz) midnight = datetime.combine(now.date() + timedelta(days=1), time.min).replace(tzinfo=tz) - if ctx.guild.id in self.birthday_tasks: - self.birthday_tasks[ctx.guild.id].cancel() - - self.birthday_tasks[ctx.guild.id] = self.bot.loop.create_task(self.remove_birthday_role(ctx.guild, member, birthday_role, midnight)) + await self.schedule_birthday_role_removal(ctx.guild, member, birthday_role, midnight) + + async def schedule_birthday_role_removal(self, guild, member, role, when): + """Schedule the removal of the birthday role.""" + await self.config.guild(guild).scheduled_tasks.set_raw(str(member.id), value={ + "role_id": role.id, + "remove_at": when.isoformat() + }) + self.birthday_tasks[guild.id] = self.bot.loop.create_task(self.remove_birthday_role(guild, member, role, when)) async def remove_birthday_role(self, guild, member, role, when): """Remove the birthday role at the specified time.""" @@ -132,4 +138,24 @@ class Birthday(commands.Cog): except (discord.Forbidden, discord.HTTPException): pass # If we can't remove the role, we'll just let it be finally: - del self.birthday_tasks[guild.id] \ No newline at end of file + del self.birthday_tasks[guild.id] + await self.config.guild(guild).scheduled_tasks.clear_raw(str(member.id)) + + async def reload_scheduled_tasks(self): + """Reload and reschedule tasks from the configuration.""" + for guild in self.bot.guilds: + scheduled_tasks = await self.config.guild(guild).scheduled_tasks() + for member_id, task_info in scheduled_tasks.items(): + member = guild.get_member(int(member_id)) + if not member: + continue + role = guild.get_role(task_info["role_id"]) + if not role: + continue + remove_at = datetime.fromisoformat(task_info["remove_at"]).replace(tzinfo=ZoneInfo(await self.config.guild(guild).timezone())) + self.birthday_tasks[guild.id] = self.bot.loop.create_task(self.remove_birthday_role(guild, member, role, remove_at)) + +async def setup(bot): + cog = Birthday(bot) + await bot.add_cog(cog) + await cog.reload_scheduled_tasks() \ No newline at end of file From 88f628de91b74e2a0e79ef68e4e080e21f466ee7 Mon Sep 17 00:00:00 2001 From: pacnpal Date: Mon, 30 Sep 2024 20:08:21 -0400 Subject: [PATCH 29/49] Add Overseerr cog --- overseerr/LICENSE | 21 ++++++ overseerr/README.md | 35 ++++++++++ overseerr/__init__.py | 7 ++ overseerr/overseerr.py | 152 +++++++++++++++++++++++++++++++++++++++++ 4 files changed, 215 insertions(+) create mode 100644 overseerr/LICENSE create mode 100644 overseerr/README.md create mode 100644 overseerr/__init__.py create mode 100644 overseerr/overseerr.py diff --git a/overseerr/LICENSE b/overseerr/LICENSE new file mode 100644 index 0000000..963bf1d --- /dev/null +++ b/overseerr/LICENSE @@ -0,0 +1,21 @@ +Creative Commons Attribution 4.0 International License + +This work is licensed under the Creative Commons Attribution 4.0 International License. + +To view a copy of this license, visit: +http://creativecommons.org/licenses/by/4.0/ + +or send a letter to: +Creative Commons, PO Box 1866, Mountain View, CA 94042, USA. + +The full text of the license can be found at: +https://creativecommons.org/licenses/by/4.0/legalcode + +You are free to: +- Share — copy and redistribute the material in any medium or format +- Adapt — remix, transform, and build upon the material for any purpose, even commercially. + +Under the following terms: +- Attribution — You must give appropriate credit, provide a link to the license, and indicate if changes were made. You may do so in any reasonable manner, but not in any way that suggests the licensor endorses you or your use. + +No additional restrictions — You may not apply legal terms or technological measures that legally restrict others from doing anything the license permits. diff --git a/overseerr/README.md b/overseerr/README.md new file mode 100644 index 0000000..ac28795 --- /dev/null +++ b/overseerr/README.md @@ -0,0 +1,35 @@ +# Overseerr Cog for Red Discord Bot + +This cog allows interaction with [Overseerr](https://overseerr.dev/) directly from Discord. Users can search for movies or TV shows, request them, and have admins approve requests. It's designed for servers with Overseerr set up for managing media requests. + +## Features +- **Set Overseerr URL and API key**: Admins can configure the Overseerr URL and API key for API interactions. +- **Search and request media**: Users can search for movies or TV shows and request them directly in Discord. +- **Media availability status**: The cog checks if media is already available or has been requested before making new requests. +- **Approve requests**: Admins with the appropriate role can approve Overseerr requests within Discord. + +## Commands + +### Admin Commands +- **`[p]setoverseerr `** + - Set the Overseerr URL and API key for the bot to communicate with Overseerr. + - Example: `[p]setoverseerr https://my.overseerr.url abcdefghijklmnop` + +- **`[p]setadminrole `** + - Set the name of the admin role that is allowed to approve Overseerr requests. + - Example: `[p]setadminrole Overseerr Admin` + +### User Commands +- **`[p]request `** + - Search for a movie or TV show and request it if it's not already available or requested. + - Example: `[p]request The Matrix` + +- **`[p]approve `** + - Approve a media request by its request ID (requires the admin role). + - Example: `[p]approve 123` + +## Installation + +1. Add the cog to your Red instance: + ```bash + [p]load overseerr diff --git a/overseerr/__init__.py b/overseerr/__init__.py new file mode 100644 index 0000000..38736ea --- /dev/null +++ b/overseerr/__init__.py @@ -0,0 +1,7 @@ +from .overseerr import Overseerr + +__red_end_user_data_statement__ = "This allows users to make requests to Overseerr and Admins can approve them." + + +async def setup(bot): + await bot.add_cog(Overseerr(bot)) \ No newline at end of file diff --git a/overseerr/overseerr.py b/overseerr/overseerr.py new file mode 100644 index 0000000..d88e116 --- /dev/null +++ b/overseerr/overseerr.py @@ -0,0 +1,152 @@ +from redbot.core import commands, Config +from redbot.core.bot import Red +import asyncio +import json + +class Overseerr(commands.Cog): + def __init__(self, bot: Red): + self.bot = bot + self.config = Config.get_conf(self, identifier=1234567890) + default_global = { + "overseerr_url": None, + "overseerr_api_key": None, + "admin_role_name": "Overseerr Admin" + } + self.config.register_global(**default_global) + + @commands.command() + @commands.admin() + async def setoverseerr(self, ctx: commands.Context, url: str, api_key: str): + """Set the Overseerr URL and API key.""" + await self.config.overseerr_url.set(url) + await self.config.overseerr_api_key.set(api_key) + await ctx.send("Overseerr URL and API key have been set.") + + @commands.command() + @commands.admin() + async def setadminrole(self, ctx: commands.Context, role_name: str): + """Set the admin role name for Overseerr approvals.""" + await self.config.admin_role_name.set(role_name) + await ctx.send(f"Admin role for Overseerr approvals set to {role_name}.") + + async def get_media_status(self, media_id, media_type): + overseerr_url = await self.config.overseerr_url() + overseerr_api_key = await self.config.overseerr_api_key() + url = f"{overseerr_url}/api/v1/{'movie' if media_type == 'movie' else 'tv'}/{media_id}" + headers = {"X-Api-key": overseerr_api_key} + + async with self.bot.session.get(url, headers=headers) as resp: + if resp.status == 200: + data = await resp.json() + status = "Available" if data.get('mediaInfo', {}).get('status') == 3 else "Not Available" + if data.get('request'): + status += " (Requested)" + return status + return "Status Unknown" + + @commands.command() + async def request(self, ctx: commands.Context, *, query: str): + """Search and request a movie or TV show on Overseerr.""" + overseerr_url = await self.config.overseerr_url() + overseerr_api_key = await self.config.overseerr_api_key() + + if not overseerr_url or not overseerr_api_key: + await ctx.send("Overseerr is not configured. Please ask an admin to set it up.") + return + + search_url = f"{overseerr_url}/api/v1/search" + request_url = f"{overseerr_url}/api/v1/request" + + headers = { + "X-Api-Key": overseerr_api_key, + "Content-Type": "application/json" + } + + # Search for the movie or TV show + async with self.bot.session.get(search_url, headers=headers, params={"query": query}) as resp: + search_results = await resp.json() + + if not search_results['results']: + await ctx.send(f"No results found for '{query}'.") + return + + # Display search results with availability status + result_message = "Please choose a result by reacting with the corresponding number:\n\n" + for i, result in enumerate(search_results['results'][:5], start=1): + media_type = result['mediaType'] + status = await self.get_media_status(result['id'], media_type) + result_message += f"{i}. [{media_type.upper()}] {result['title']} ({result.get('releaseDate', 'N/A')}) - {status}\n" + + result_msg = await ctx.send(result_message) + + # Add reaction options + reactions = ['1️⃣', '2️⃣', '3️⃣', '4️⃣', '5️⃣'] + for i in range(min(len(search_results['results']), 5)): + await result_msg.add_reaction(reactions[i]) + + def check(reaction, user): + return user == ctx.author and str(reaction.emoji) in reactions + + try: + reaction, user = await self.bot.wait_for('reaction_add', timeout=60.0, check=check) + except asyncio.TimeoutError: + await ctx.send("Search timed out. Please try again.") + return + + selected_index = reactions.index(str(reaction.emoji)) + selected_result = search_results['results'][selected_index] + media_type = selected_result['mediaType'] + + # Check if the media is already available or requested + status = await self.get_media_status(selected_result['id'], media_type) + if "Available" in status: + await ctx.send(f"'{selected_result['title']}' is already available. No need to request!") + return + elif "Requested" in status: + await ctx.send(f"'{selected_result['title']}' has already been requested. No need to request again!") + return + + # Make the request + request_data = { + "mediaId": selected_result['id'], + "mediaType": media_type + } + + async with self.bot.session.post(request_url, headers=headers, json=request_data) as resp: + if resp.status == 200: + response_data = await resp.json() + request_id = response_data.get('id') + await ctx.send(f"Successfully requested {media_type} '{selected_result['title']}'! Request ID: {request_id}") + else: + await ctx.send(f"Failed to request {media_type} '{selected_result['title']}'. Please try again later.") + + @commands.command() + async def approve(self, ctx: commands.Context, request_id: int): + """Approve a request on Overseerr.""" + admin_role_name = await self.config.admin_role_name() + if not any(role.name == admin_role_name for role in ctx.author.roles): + await ctx.send(f"You need the '{admin_role_name}' role to approve requests.") + return + + overseerr_url = await self.config.overseerr_url() + overseerr_api_key = await self.config.overseerr_api_key() + + if not overseerr_url or not overseerr_api_key: + await ctx.send("Overseerr is not configured. Please ask an admin to set it up.") + return + + approve_url = f"{overseerr_url}/api/v1/request/{request_id}/approve" + + headers = { + "X-Api-Key": overseerr_api_key, + "Content-Type": "application/json" + } + + async with self.bot.session.post(approve_url, headers=headers) as resp: + if resp.status == 200: + await ctx.send(f"Request {request_id} has been approved!") + else: + await ctx.send(f"Failed to approve request {request_id}. Please check the request ID and try again.") + +def setup(bot: Red): + bot.add_cog(Overseerr(bot)) From 4edb139a465c3762dea1b4ad6ff54fc5c42e2d5e Mon Sep 17 00:00:00 2001 From: pacnpal <183241239+pacnpal@users.noreply.github.com> Date: Sun, 29 Sep 2024 00:26:08 -0400 Subject: [PATCH 30/49] updated birthday.py --- birthday/birthday.py | 27 ++++++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/birthday/birthday.py b/birthday/birthday.py index f2b16dd..c546638 100644 --- a/birthday/birthday.py +++ b/birthday/birthday.py @@ -122,6 +122,31 @@ class Birthday(commands.Cog): await self.schedule_birthday_role_removal(ctx.guild, member, birthday_role, midnight) + @commands.command() + async def bdaycheck(self, ctx): + """Check the upcoming birthday role removal tasks.""" + # Check if the user has permission to use this command + allowed_roles = await self.config.guild(ctx.guild).allowed_roles() + if not any(role.id in allowed_roles for role in ctx.author.roles): + return await ctx.send("You don't have permission to use this command.") + + scheduled_tasks = await self.config.guild(ctx.guild).scheduled_tasks() + if not scheduled_tasks: + return await ctx.send("There are no scheduled tasks.") + + message = "Upcoming birthday role removal tasks:\n" + for member_id, task_info in scheduled_tasks.items(): + member = ctx.guild.get_member(int(member_id)) + if not member: + continue + role = ctx.guild.get_role(task_info["role_id"]) + if not role: + continue + remove_at = datetime.fromisoformat(task_info["remove_at"]).replace(tzinfo=ZoneInfo(await self.config.guild(ctx.guild).timezone())) + message += f"- {member.display_name} ({member.id}): {role.name} will be removed at {remove_at}\n" + + await ctx.send(message) + async def schedule_birthday_role_removal(self, guild, member, role, when): """Schedule the removal of the birthday role.""" await self.config.guild(guild).scheduled_tasks.set_raw(str(member.id), value={ @@ -158,4 +183,4 @@ class Birthday(commands.Cog): async def setup(bot): cog = Birthday(bot) await bot.add_cog(cog) - await cog.reload_scheduled_tasks() \ No newline at end of file + await cog.reload_scheduled_tasks() From 42f951dafb863b6f9495fdbf5b66c41e4169822c Mon Sep 17 00:00:00 2001 From: pacnpal <183241239+pacnpal@users.noreply.github.com> Date: Sun, 29 Sep 2024 00:28:28 -0400 Subject: [PATCH 31/49] generated uuid for identifier --- birthday/birthday.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/birthday/birthday.py b/birthday/birthday.py index c546638..25e147c 100644 --- a/birthday/birthday.py +++ b/birthday/birthday.py @@ -11,7 +11,7 @@ class Birthday(commands.Cog): def __init__(self, bot: Red): self.bot = bot - self.config = Config.get_conf(self, identifier=1234567890) + self.config = Config.get_conf(self, identifier=428eb4b6-de7f-45ba-8eda-a15c163f1c7d) default_guild = { "birthday_role": None, "allowed_roles": [], From 906cea6267d3eb388ff9da7550c1b6d9063612cf Mon Sep 17 00:00:00 2001 From: pacnpal <183241239+pacnpal@users.noreply.github.com> Date: Sun, 29 Sep 2024 00:32:20 -0400 Subject: [PATCH 32/49] fixed uuid --- birthday/birthday.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/birthday/birthday.py b/birthday/birthday.py index 25e147c..ca23a1a 100644 --- a/birthday/birthday.py +++ b/birthday/birthday.py @@ -11,7 +11,7 @@ class Birthday(commands.Cog): def __init__(self, bot: Red): self.bot = bot - self.config = Config.get_conf(self, identifier=428eb4b6-de7f-45ba-8eda-a15c163f1c7d) + self.config = Config.get_conf(self, identifier=5458102289) default_guild = { "birthday_role": None, "allowed_roles": [], From 28fb9490fb7117472200a3720cc7cb7da45ae03a Mon Sep 17 00:00:00 2001 From: pacnpal <183241239+pacnpal@users.noreply.github.com> Date: Mon, 30 Sep 2024 20:42:15 -0400 Subject: [PATCH 33/49] Update overseerr.py --- overseerr/overseerr.py | 28 +++++++++++++++++++--------- 1 file changed, 19 insertions(+), 9 deletions(-) diff --git a/overseerr/overseerr.py b/overseerr/overseerr.py index d88e116..2240ee9 100644 --- a/overseerr/overseerr.py +++ b/overseerr/overseerr.py @@ -14,17 +14,27 @@ class Overseerr(commands.Cog): } self.config.register_global(**default_global) - @commands.command() + @commands.group() @commands.admin() - async def setoverseerr(self, ctx: commands.Context, url: str, api_key: str): - """Set the Overseerr URL and API key.""" - await self.config.overseerr_url.set(url) - await self.config.overseerr_api_key.set(api_key) - await ctx.send("Overseerr URL and API key have been set.") + async def overseerr(self, ctx: commands.Context): + """Manage Overseerr settings.""" + if ctx.invoked_subcommand is None: + await ctx.send_help(ctx.command) - @commands.command() - @commands.admin() - async def setadminrole(self, ctx: commands.Context, role_name: str): + @overseerr.command(name="seturl") + async def overseerr_seturl(self, ctx: commands.Context, url: str): + """Set the Overseerr URL.""" + await self.config.overseerr_url.set(url) + await ctx.send("Overseerr URL has been set.") + + @overseerr.command(name="setapikey") + async def overseerr_setapikey(self, ctx: commands.Context, api_key: str): + """Set the Overseerr API key.""" + await self.config.overseerr_api_key.set(api_key) + await ctx.send("Overseerr API key has been set.") + + @overseerr.command(name="setadminrole") + async def overseerr_setadminrole(self, ctx: commands.Context, role_name: str): """Set the admin role name for Overseerr approvals.""" await self.config.admin_role_name.set(role_name) await ctx.send(f"Admin role for Overseerr approvals set to {role_name}.") From 63049c1e2bc0b27365e7c3c52a834c47885374b8 Mon Sep 17 00:00:00 2001 From: pacnpal <183241239+pacnpal@users.noreply.github.com> Date: Mon, 30 Sep 2024 20:36:31 -0400 Subject: [PATCH 34/49] Update overseerr.py --- overseerr/overseerr.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/overseerr/overseerr.py b/overseerr/overseerr.py index 2240ee9..1d0f63d 100644 --- a/overseerr/overseerr.py +++ b/overseerr/overseerr.py @@ -6,7 +6,7 @@ import json class Overseerr(commands.Cog): def __init__(self, bot: Red): self.bot = bot - self.config = Config.get_conf(self, identifier=1234567890) + self.config = Config.get_conf(self, identifier=336473788746) default_global = { "overseerr_url": None, "overseerr_api_key": None, From 63b68afbf32ee0564434d7dde4bec163799b60ca Mon Sep 17 00:00:00 2001 From: pacnpal <183241239+pacnpal@users.noreply.github.com> Date: Mon, 30 Sep 2024 20:46:28 -0400 Subject: [PATCH 35/49] Update overseerr.py --- overseerr/overseerr.py | 59 +++++++++++++++++++++++------------------- 1 file changed, 32 insertions(+), 27 deletions(-) diff --git a/overseerr/overseerr.py b/overseerr/overseerr.py index 1d0f63d..38a1f58 100644 --- a/overseerr/overseerr.py +++ b/overseerr/overseerr.py @@ -1,12 +1,13 @@ from redbot.core import commands, Config from redbot.core.bot import Red +import aiohttp import asyncio import json class Overseerr(commands.Cog): def __init__(self, bot: Red): self.bot = bot - self.config = Config.get_conf(self, identifier=336473788746) + self.config = Config.get_conf(self, identifier=1234567890) default_global = { "overseerr_url": None, "overseerr_api_key": None, @@ -43,23 +44,24 @@ class Overseerr(commands.Cog): overseerr_url = await self.config.overseerr_url() overseerr_api_key = await self.config.overseerr_api_key() url = f"{overseerr_url}/api/v1/{'movie' if media_type == 'movie' else 'tv'}/{media_id}" - headers = {"X-Api-key": overseerr_api_key} - - async with self.bot.session.get(url, headers=headers) as resp: - if resp.status == 200: - data = await resp.json() - status = "Available" if data.get('mediaInfo', {}).get('status') == 3 else "Not Available" - if data.get('request'): - status += " (Requested)" - return status - return "Status Unknown" + headers = {"X-Api-Key": overseerr_api_key} + + async with aiohttp.ClientSession() as session: + async with session.get(url, headers=headers) as resp: + if resp.status == 200: + data = await resp.json() + status = "Available" if data.get('mediaInfo', {}).get('status') == 3 else "Not Available" + if data.get('request'): + status += " (Requested)" + return status + return "Status Unknown" @commands.command() async def request(self, ctx: commands.Context, *, query: str): """Search and request a movie or TV show on Overseerr.""" overseerr_url = await self.config.overseerr_url() overseerr_api_key = await self.config.overseerr_api_key() - + if not overseerr_url or not overseerr_api_key: await ctx.send("Overseerr is not configured. Please ask an admin to set it up.") return @@ -73,8 +75,9 @@ class Overseerr(commands.Cog): } # Search for the movie or TV show - async with self.bot.session.get(search_url, headers=headers, params={"query": query}) as resp: - search_results = await resp.json() + async with aiohttp.ClientSession() as session: + async with session.get(search_url, headers=headers, params={"query": query}) as resp: + search_results = await resp.json() if not search_results['results']: await ctx.send(f"No results found for '{query}'.") @@ -122,13 +125,14 @@ class Overseerr(commands.Cog): "mediaType": media_type } - async with self.bot.session.post(request_url, headers=headers, json=request_data) as resp: - if resp.status == 200: - response_data = await resp.json() - request_id = response_data.get('id') - await ctx.send(f"Successfully requested {media_type} '{selected_result['title']}'! Request ID: {request_id}") - else: - await ctx.send(f"Failed to request {media_type} '{selected_result['title']}'. Please try again later.") + async with aiohttp.ClientSession() as session: + async with session.post(request_url, headers=headers, json=request_data) as resp: + if resp.status == 200: + response_data = await resp.json() + request_id = response_data.get('id') + await ctx.send(f"Successfully requested {media_type} '{selected_result['title']}'! Request ID: {request_id}") + else: + await ctx.send(f"Failed to request {media_type} '{selected_result['title']}'. Please try again later.") @commands.command() async def approve(self, ctx: commands.Context, request_id: int): @@ -140,7 +144,7 @@ class Overseerr(commands.Cog): overseerr_url = await self.config.overseerr_url() overseerr_api_key = await self.config.overseerr_api_key() - + if not overseerr_url or not overseerr_api_key: await ctx.send("Overseerr is not configured. Please ask an admin to set it up.") return @@ -152,11 +156,12 @@ class Overseerr(commands.Cog): "Content-Type": "application/json" } - async with self.bot.session.post(approve_url, headers=headers) as resp: - if resp.status == 200: - await ctx.send(f"Request {request_id} has been approved!") - else: - await ctx.send(f"Failed to approve request {request_id}. Please check the request ID and try again.") + async with aiohttp.ClientSession() as session: + async with session.post(approve_url, headers=headers) as resp: + if resp.status == 200: + await ctx.send(f"Request {request_id} has been approved!") + else: + await ctx.send(f"Failed to approve request {request_id}. Please check the request ID and try again.") def setup(bot: Red): bot.add_cog(Overseerr(bot)) From 09060c2cc692727a87e20451e90b587465809c04 Mon Sep 17 00:00:00 2001 From: pacnpal <183241239+pacnpal@users.noreply.github.com> Date: Mon, 30 Sep 2024 20:48:00 -0400 Subject: [PATCH 36/49] Update overseerr.py --- overseerr/overseerr.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/overseerr/overseerr.py b/overseerr/overseerr.py index 38a1f58..17660e1 100644 --- a/overseerr/overseerr.py +++ b/overseerr/overseerr.py @@ -7,7 +7,7 @@ import json class Overseerr(commands.Cog): def __init__(self, bot: Red): self.bot = bot - self.config = Config.get_conf(self, identifier=1234567890) + self.config = Config.get_conf(self, identifier=3467367746) default_global = { "overseerr_url": None, "overseerr_api_key": None, From f76dfa1c5cf145c6db1cdea8c8dcf68e92d8b041 Mon Sep 17 00:00:00 2001 From: pacnpal <183241239+pacnpal@users.noreply.github.com> Date: Mon, 30 Sep 2024 20:49:07 -0400 Subject: [PATCH 37/49] Update overseerr.py --- overseerr/overseerr.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/overseerr/overseerr.py b/overseerr/overseerr.py index 17660e1..9095c14 100644 --- a/overseerr/overseerr.py +++ b/overseerr/overseerr.py @@ -20,7 +20,7 @@ class Overseerr(commands.Cog): async def overseerr(self, ctx: commands.Context): """Manage Overseerr settings.""" if ctx.invoked_subcommand is None: - await ctx.send_help(ctx.command) + return @overseerr.command(name="seturl") async def overseerr_seturl(self, ctx: commands.Context, url: str): From fa9ff05e71873973cdb2659bfe7836664bd5b665 Mon Sep 17 00:00:00 2001 From: pacnpal <183241239+pacnpal@users.noreply.github.com> Date: Mon, 30 Sep 2024 21:01:15 -0400 Subject: [PATCH 38/49] Update overseerr.py --- overseerr/overseerr.py | 86 ++++++++++++++++++++++++------------------ 1 file changed, 50 insertions(+), 36 deletions(-) diff --git a/overseerr/overseerr.py b/overseerr/overseerr.py index 9095c14..98be88e 100644 --- a/overseerr/overseerr.py +++ b/overseerr/overseerr.py @@ -1,8 +1,6 @@ +import aiohttp from redbot.core import commands, Config from redbot.core.bot import Red -import aiohttp -import asyncio -import json class Overseerr(commands.Cog): def __init__(self, bot: Red): @@ -15,46 +13,33 @@ class Overseerr(commands.Cog): } self.config.register_global(**default_global) + ### GROUP: SETTINGS COMMANDS ### + @commands.group() @commands.admin() async def overseerr(self, ctx: commands.Context): - """Manage Overseerr settings.""" - if ctx.invoked_subcommand is None: - return + """Base command group for Overseerr configuration.""" + pass - @overseerr.command(name="seturl") - async def overseerr_seturl(self, ctx: commands.Context, url: str): + @overseerr.command() + async def url(self, ctx: commands.Context, url: str): """Set the Overseerr URL.""" await self.config.overseerr_url.set(url) - await ctx.send("Overseerr URL has been set.") + await ctx.send(f"Overseerr URL set to: {url}") - @overseerr.command(name="setapikey") - async def overseerr_setapikey(self, ctx: commands.Context, api_key: str): + @overseerr.command() + async def apikey(self, ctx: commands.Context, api_key: str): """Set the Overseerr API key.""" await self.config.overseerr_api_key.set(api_key) await ctx.send("Overseerr API key has been set.") - @overseerr.command(name="setadminrole") - async def overseerr_setadminrole(self, ctx: commands.Context, role_name: str): + @overseerr.command() + async def adminrole(self, ctx: commands.Context, role_name: str): """Set the admin role name for Overseerr approvals.""" await self.config.admin_role_name.set(role_name) - await ctx.send(f"Admin role for Overseerr approvals set to {role_name}.") + await ctx.send(f"Admin role for Overseerr approvals set to: {role_name}") - async def get_media_status(self, media_id, media_type): - overseerr_url = await self.config.overseerr_url() - overseerr_api_key = await self.config.overseerr_api_key() - url = f"{overseerr_url}/api/v1/{'movie' if media_type == 'movie' else 'tv'}/{media_id}" - headers = {"X-Api-Key": overseerr_api_key} - - async with aiohttp.ClientSession() as session: - async with session.get(url, headers=headers) as resp: - if resp.status == 200: - data = await resp.json() - status = "Available" if data.get('mediaInfo', {}).get('status') == 3 else "Not Available" - if data.get('request'): - status += " (Requested)" - return status - return "Status Unknown" + ### REQUEST & APPROVAL COMMANDS ### @commands.command() async def request(self, ctx: commands.Context, *, query: str): @@ -67,17 +52,26 @@ class Overseerr(commands.Cog): return search_url = f"{overseerr_url}/api/v1/search" - request_url = f"{overseerr_url}/api/v1/request" - headers = { "X-Api-Key": overseerr_api_key, "Content-Type": "application/json" } - # Search for the movie or TV show async with aiohttp.ClientSession() as session: async with session.get(search_url, headers=headers, params={"query": query}) as resp: - search_results = await resp.json() + if resp.status != 200: + await ctx.send(f"Error from Overseerr API: {resp.status}") + return + + try: + search_results = await resp.json() + except Exception as e: + await ctx.send(f"Failed to parse JSON: {e}") + return + + if 'results' not in search_results: + await ctx.send(f"No results found for '{query}'. API Response: {search_results}") + return if not search_results['results']: await ctx.send(f"No results found for '{query}'.") @@ -87,8 +81,10 @@ class Overseerr(commands.Cog): result_message = "Please choose a result by reacting with the corresponding number:\n\n" for i, result in enumerate(search_results['results'][:5], start=1): media_type = result['mediaType'] + title = result['title'] + release_date = result.get('releaseDate', 'N/A') status = await self.get_media_status(result['id'], media_type) - result_message += f"{i}. [{media_type.upper()}] {result['title']} ({result.get('releaseDate', 'N/A')}) - {status}\n" + result_message += f"{i}. [{media_type.upper()}] {title} ({release_date}) - {status}\n" result_msg = await ctx.send(result_message) @@ -120,6 +116,7 @@ class Overseerr(commands.Cog): return # Make the request + request_url = f"{overseerr_url}/api/v1/request" request_data = { "mediaId": selected_result['id'], "mediaType": media_type @@ -144,13 +141,12 @@ class Overseerr(commands.Cog): overseerr_url = await self.config.overseerr_url() overseerr_api_key = await self.config.overseerr_api_key() - + if not overseerr_url or not overseerr_api_key: await ctx.send("Overseerr is not configured. Please ask an admin to set it up.") return approve_url = f"{overseerr_url}/api/v1/request/{request_id}/approve" - headers = { "X-Api-Key": overseerr_api_key, "Content-Type": "application/json" @@ -163,5 +159,23 @@ class Overseerr(commands.Cog): else: await ctx.send(f"Failed to approve request {request_id}. Please check the request ID and try again.") + ### HELPER FUNCTION TO CHECK MEDIA STATUS ### + + async def get_media_status(self, media_id, media_type): + overseerr_url = await self.config.overseerr_url() + overseerr_api_key = await self.config.overseerr_api_key() + url = f"{overseerr_url}/api/v1/{'movie' if media_type == 'movie' else 'tv'}/{media_id}" + headers = {"X-Api-Key": overseerr_api_key} + + async with aiohttp.ClientSession() as session: + async with session.get(url, headers=headers) as resp: + if resp.status == 200: + data = await resp.json() + status = "Available" if data.get('mediaInfo', {}).get('status') == 3 else "Not Available" + if data.get('request'): + status += " (Requested)" + return status + return "Status Unknown" + def setup(bot: Red): bot.add_cog(Overseerr(bot)) From c5f3471dfc38df0701716243d5159ef314e87cff Mon Sep 17 00:00:00 2001 From: pacnpal <183241239+pacnpal@users.noreply.github.com> Date: Mon, 30 Sep 2024 21:13:15 -0400 Subject: [PATCH 39/49] Update overseerr.py --- overseerr/overseerr.py | 1 + 1 file changed, 1 insertion(+) diff --git a/overseerr/overseerr.py b/overseerr/overseerr.py index 98be88e..1705c9c 100644 --- a/overseerr/overseerr.py +++ b/overseerr/overseerr.py @@ -24,6 +24,7 @@ class Overseerr(commands.Cog): @overseerr.command() async def url(self, ctx: commands.Context, url: str): """Set the Overseerr URL.""" + url = url.rstrip('/') await self.config.overseerr_url.set(url) await ctx.send(f"Overseerr URL set to: {url}") From 9926193ac89adb362d2647f6a49522a8398b7b0b Mon Sep 17 00:00:00 2001 From: pacnpal <183241239+pacnpal@users.noreply.github.com> Date: Mon, 30 Sep 2024 21:19:28 -0400 Subject: [PATCH 40/49] Update overseerr.py --- overseerr/overseerr.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/overseerr/overseerr.py b/overseerr/overseerr.py index 1705c9c..6a85c69 100644 --- a/overseerr/overseerr.py +++ b/overseerr/overseerr.py @@ -1,6 +1,9 @@ import aiohttp from redbot.core import commands, Config from redbot.core.bot import Red +import asyncio # Import asyncio +import json +import urllib.parse # Import for encoding URLs class Overseerr(commands.Cog): def __init__(self, bot: Red): From 9437863ac927d2b3b56c22df7e554cae201b7d15 Mon Sep 17 00:00:00 2001 From: pacnpal <183241239+pacnpal@users.noreply.github.com> Date: Mon, 21 Oct 2024 13:34:58 -0400 Subject: [PATCH 41/49] adding Overseerr cog to README and give its own README --- README.md | 1 + overseerr/README.md | 60 ++++++++++++++++++++++++++++++++++++++++++--- 2 files changed, 57 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index af956e0..fd19021 100644 --- a/README.md +++ b/README.md @@ -7,6 +7,7 @@ Welcome to **Pac-cogs**, a collection of custom cogs for [Red](https://github.co | Cog Name | Description | |------------|--------------------------------------------------| | **Birthday** | Assigns a special birthday role to users and sends a celebratory message with random cake or pie emojis. Automatically removes the birthday role at midnight, with a configurable timezone. Offers the option to set a specific announcement channel and restricts usage to specified roles. Users can assign the role without needing a higher role in the hierarchy. | +| **Overseerr** | Allows interaction with [Overseerr](https://overseerr.dev/) directly from Discord. Users can search for movies or TV shows, request them, and have admins approve requests. It's designed for servers with Overseerr set up for managing media requests. | ## Installation diff --git a/overseerr/README.md b/overseerr/README.md index ac28795..391cd80 100644 --- a/overseerr/README.md +++ b/overseerr/README.md @@ -2,6 +2,59 @@ This cog allows interaction with [Overseerr](https://overseerr.dev/) directly from Discord. Users can search for movies or TV shows, request them, and have admins approve requests. It's designed for servers with Overseerr set up for managing media requests. +## Installation + +To install this cog, follow these steps: + +1. Ensure you have Red-DiscordBot V3 installed. +2. Add the repository to your bot: + + ``` + [p]repo add Pac-cogs https://github.com/pacnpal/Pac-cogs + ``` + +3. Install the Overseerr cog: + + ``` + [p]cog install Pac-cogs overseerr + ``` + +4. Load the cog: + + ``` + [p]load overseerr + ``` + +Replace `[p]` with your bot's prefix. + + +## Setup + +Before using the cog, you'll need to configure it: + +1. Set the Overseerr URL and API key: + ``` + [p]setoverseerr https://your.overseerr.instance/api/v3 your_api_key + ``` +2. Set the admin role allowed to approve requests: + ``` + [p]setadminrole @OverseerrAdmins + ``` + +## Usage + +Users can request movies or TV shows using the following command: + +``` +[p]request Movie/TV Show Name +``` + +Admins can approve requests using: + +``` +[p]approve request_id +``` + ## Features - **Set Overseerr URL and API key**: Admins can configure the Overseerr URL and API key for API interactions. - **Search and request media**: Users can search for movies or TV shows and request them directly in Discord. @@ -28,8 +81,7 @@ This cog allows interaction with [Overseerr](https://overseerr.dev/) directly fr - Approve a media request by its request ID (requires the admin role). - Example: `[p]approve 123` -## Installation -1. Add the cog to your Red instance: - ```bash - [p]load overseerr +## Support + +If you encounter any issues or have questions, please open an issue on the [GitHub repository](https://github.com/pacnpal/Pac-cogs). From fc7703b1d52094567560083a937077a0bc457512 Mon Sep 17 00:00:00 2001 From: pacnpal <183241239+pacnpal@users.noreply.github.com> Date: Mon, 21 Oct 2024 13:40:53 -0400 Subject: [PATCH 42/49] fix README --- overseerr/README.md | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/overseerr/README.md b/overseerr/README.md index 391cd80..ce07cf2 100644 --- a/overseerr/README.md +++ b/overseerr/README.md @@ -34,9 +34,13 @@ Before using the cog, you'll need to configure it: 1. Set the Overseerr URL and API key: ``` - [p]setoverseerr https://your.overseerr.instance/api/v3 your_api_key + [p]setoverseerr url https://your.overseerr.instance ``` -2. Set the admin role allowed to approve requests: +2. Set the Overseerr API key: + ``` + [p]setoverseerr api_key your_api_key + ``` +4. Set the admin role allowed to approve requests: ``` [p]setadminrole @OverseerrAdmins ``` From 3b4d0545b9d878eb55133c4ddcf4adf283ef389f Mon Sep 17 00:00:00 2001 From: pacnpal <183241239+pacnpal@users.noreply.github.com> Date: Mon, 21 Oct 2024 13:41:24 -0400 Subject: [PATCH 43/49] Update README.md --- overseerr/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/overseerr/README.md b/overseerr/README.md index ce07cf2..e9de520 100644 --- a/overseerr/README.md +++ b/overseerr/README.md @@ -38,7 +38,7 @@ Before using the cog, you'll need to configure it: ``` 2. Set the Overseerr API key: ``` - [p]setoverseerr api_key your_api_key + [p]setoverseerr apikey your_api_key ``` 4. Set the admin role allowed to approve requests: ``` From 76dd2f1b1a17f9f2b0576e8caab88f24268f8851 Mon Sep 17 00:00:00 2001 From: pacnpal <183241239+pacnpal@users.noreply.github.com> Date: Mon, 21 Oct 2024 13:58:25 -0400 Subject: [PATCH 44/49] Update README.md --- overseerr/README.md | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/overseerr/README.md b/overseerr/README.md index e9de520..fd69f9d 100644 --- a/overseerr/README.md +++ b/overseerr/README.md @@ -34,15 +34,15 @@ Before using the cog, you'll need to configure it: 1. Set the Overseerr URL and API key: ``` - [p]setoverseerr url https://your.overseerr.instance + [p]overseerr url https://your.overseerr.instance ``` 2. Set the Overseerr API key: ``` - [p]setoverseerr apikey your_api_key + [p]overseerr apikey your_api_key ``` 4. Set the admin role allowed to approve requests: ``` - [p]setadminrole @OverseerrAdmins + [p]adminrole @OverseerrAdmins ``` ## Usage @@ -68,13 +68,15 @@ Admins can approve requests using: ## Commands ### Admin Commands -- **`[p]setoverseerr `** - - Set the Overseerr URL and API key for the bot to communicate with Overseerr. - - Example: `[p]setoverseerr https://my.overseerr.url abcdefghijklmnop` - -- **`[p]setadminrole `** +- **`[p]overseerr url `** + - Set the Overseerr URL for the bot to communicate with Overseerr. + - Example: `[p]overseerr https://my.overseerr.url` +- **`[p]overseerr apikey `** + - Set the Overseerr API Key. retrieved from `https://your-overseerr-url/settings`. + - Example: `[p]overseerr apikey 4OK6WLU8Fv2TrZfcOskLZb2PK5WA3547Jz2fEfJqfkLiT34xUP0D48Z7jwC9lC8xU9` +- **`[p]overseerr adminrole `** - Set the name of the admin role that is allowed to approve Overseerr requests. - - Example: `[p]setadminrole Overseerr Admin` + - Example: `[p]overseerr adminrole @Overseerr Admin` ### User Commands - **`[p]request `** From f9a129cac9e3a1b0d5a64e4813c39d65387aabbb Mon Sep 17 00:00:00 2001 From: pacnpal <183241239+pacnpal@users.noreply.github.com> Date: Mon, 21 Oct 2024 13:59:03 -0400 Subject: [PATCH 45/49] Update README.md --- overseerr/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/overseerr/README.md b/overseerr/README.md index fd69f9d..b33d1c7 100644 --- a/overseerr/README.md +++ b/overseerr/README.md @@ -70,7 +70,7 @@ Admins can approve requests using: ### Admin Commands - **`[p]overseerr url `** - Set the Overseerr URL for the bot to communicate with Overseerr. - - Example: `[p]overseerr https://my.overseerr.url` + - Example: `[p]overseerr https://your-overseerr-url` - **`[p]overseerr apikey `** - Set the Overseerr API Key. retrieved from `https://your-overseerr-url/settings`. - Example: `[p]overseerr apikey 4OK6WLU8Fv2TrZfcOskLZb2PK5WA3547Jz2fEfJqfkLiT34xUP0D48Z7jwC9lC8xU9` From 8bc55d75770300cf1f02d65a67f91140f279dec5 Mon Sep 17 00:00:00 2001 From: pacnpal <183241239+pacnpal@users.noreply.github.com> Date: Thu, 14 Nov 2024 17:46:45 +0000 Subject: [PATCH 46/49] first --- info.json | 9 -- video-archive/README.md | 181 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 181 insertions(+), 9 deletions(-) delete mode 100644 info.json diff --git a/info.json b/info.json deleted file mode 100644 index 55d2fc2..0000000 --- a/info.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "author": [ - "PacNPal" - ], - "install_msg": "Thank you for installing the Pac-cogs repo!", - "name": "Pac-cogs", - "short": "Very cool cogs!", - "description": "Right now, just a birthday cog." -} \ No newline at end of file diff --git a/video-archive/README.md b/video-archive/README.md index a8f1fd7..7a3bb29 100644 --- a/video-archive/README.md +++ b/video-archive/README.md @@ -164,3 +164,184 @@ Before submitting an issue: ## License This cog is licensed under the MIT License - see the [LICENSE](../LICENSE) file for details. + +# VideoArchiver Cog for Red-DiscordBot + +A powerful video archiving cog that automatically downloads and reposts videos from monitored channels, with support for GPU-accelerated compression, multi-video processing, and role-based permissions. + +## Features + +- **Hardware-Accelerated Video Processing**: + - NVIDIA GPU support using NVENC + - AMD GPU support using AMF + - Intel GPU support using QuickSync + - ARM64/aarch64 support with V4L2 M2M encoder + - Multi-core CPU optimization +- **Smart Video Processing**: + - Intelligent quality preservation + - Only compresses when needed + - Concurrent video processing + - Default 8MB file size limit +- **Role-Based Access**: + - Restrict archiving to specific roles + - Default allows all users + - Per-guild role configuration +- **Wide Platform Support**: + - Support for multiple video platforms via [yt-dlp](https://github.com/yt-dlp/yt-dlp) + - Configurable site whitelist + - Automatic quality selection + +## Quick Installation + +1. Install the cog: + +``` +[p]repo add video-archiver https://github.com/yourusername/discord-video-bot +[p]cog install video-archiver video_archiver +[p]load video_archiver +``` + +The required dependencies will be installed automatically. If you need to install them manually: + +```bash +python -m pip install -U yt-dlp>=2024.11.4 ffmpeg-python>=0.2.0 requests>=2.32.3 +``` + +### Important: Keeping yt-dlp Updated + +The cog relies on [yt-dlp](https://github.com/yt-dlp/yt-dlp) for video downloading. Video platforms frequently update their sites, which may break video downloading if yt-dlp is outdated. To ensure continued functionality, regularly update yt-dlp: + +```bash +[p]pipinstall --upgrade yt-dlp + +# Or manually: +python -m pip install -U yt-dlp +``` + +**Note**: Before submitting any GitHub issues related to video downloading, please ensure you have updated yt-dlp to the latest version first, as most downloading issues can be resolved by updating. + +## Configuration + +The cog supports both slash commands and traditional prefix commands. Use whichever style you prefer. + +### Channel Setup + +``` +/videoarchiver setchannel #archive-channel # Set archive channel +/videoarchiver setnotification #notify-channel # Set notification channel +/videoarchiver setlogchannel #log-channel # Set log channel for errors/notifications +/videoarchiver addmonitor #videos-channel # Add channel to monitor +/videoarchiver removemonitor #channel # Remove monitored channel + +# Legacy commands also supported: +[p]videoarchiver setchannel #channel +[p]videoarchiver setnotification #channel +etc. +``` + +### Role Management + +``` +/videoarchiver addrole @role # Add role that can trigger archiving +/videoarchiver removerole @role # Remove role from allowed list +/videoarchiver listroles # List all allowed roles (empty = all allowed) +``` + +### Video Settings + +``` +/videoarchiver setformat mp4 # Set video format +/videoarchiver setquality 1080 # Set max quality (pixels) +/videoarchiver setmaxsize 8 # Set max size (MB, default 8MB) +/videoarchiver toggledelete # Toggle file cleanup +``` + +### Message Settings + +``` +/videoarchiver setduration 24 # Set message duration (hours) +/videoarchiver settemplate "Archived video from {author}\nOriginal: {original_message}" +/videoarchiver enablesites # Configure allowed sites +``` + +## Architecture Support + +The cog supports multiple architectures: + +- x86_64/amd64 +- ARM64/aarch64 +- ARMv7 (32-bit) +- Apple Silicon (M1/M2) + +Hardware acceleration is automatically configured based on your system: + +- x86_64: Full GPU support (NVIDIA, AMD, Intel) +- ARM64: V4L2 M2M hardware encoding when available +- All platforms: Multi-core CPU optimization + +## Troubleshooting + +1. **Permission Issues**: + - Bot needs "Manage Messages" permission + - Bot needs "Attach Files" permission + - Bot needs "Read Message History" permission + - Bot needs "Use Application Commands" for slash commands + +2. **Video Processing Issues**: + - Ensure FFmpeg is properly installed + - Check GPU drivers are up to date + - Verify file permissions in the downloads directory + - Update yt-dlp if videos fail to download + +3. **Role Issues**: + - Verify role hierarchy (bot's role must be higher than managed roles) + - Check if roles are properly configured + +4. **Performance Issues**: + - Check available disk space + - Monitor system resource usage + +## Support + +For support: + +1. First, check the [Troubleshooting](#troubleshooting) section above +2. Update yt-dlp to the latest version: + + ```bash + [p]pipinstall --upgrade yt-dlp + # Or manually: + python -m pip install -U yt-dlp + ``` + +3. If the issue persists after updating yt-dlp: + - Join the Red-DiscordBot server and ask in the #support channel + - Open an issue on GitHub with: + - Your Red-Bot version + - The output of `[p]pipinstall list` + - Steps to reproduce the issue + - Any error messages + +## Contributing + +Contributions are welcome! Please feel free to submit a Pull Request. + +Before submitting an issue: + +1. Update yt-dlp to the latest version first: + + ```bash + [p]pipinstall --upgrade yt-dlp + # Or manually: + python -m pip install -U yt-dlp + ``` + +2. If the issue persists after updating yt-dlp, please include: + - Your Red-Bot version + - The output of `[p]pipinstall list` + - Steps to reproduce the issue + - Any error messages + +## License + +This cog is licensed under the MIT License - see the [LICENSE](../LICENSE) file for details. From 0510721aeff4bde3642bd4d2904c5da36ed0f0b1 Mon Sep 17 00:00:00 2001 From: pacnpal <183241239+pacnpal@users.noreply.github.com> Date: Thu, 14 Nov 2024 17:58:40 +0000 Subject: [PATCH 47/49] commit for rebase --- README.md | 35 ----------------------------------- 1 file changed, 35 deletions(-) delete mode 100644 README.md diff --git a/README.md b/README.md deleted file mode 100644 index fd19021..0000000 --- a/README.md +++ /dev/null @@ -1,35 +0,0 @@ -# Pac-cogs - Red Discord Bot Cogs Collection - -Welcome to **Pac-cogs**, a collection of custom cogs for [Red](https://github.com/Cog-Creators/Red-DiscordBot). These cogs are designed to add extra functionality to your Red bot instance on Discord. - -## Cogs Overview - -| Cog Name | Description | -|------------|--------------------------------------------------| -| **Birthday** | Assigns a special birthday role to users and sends a celebratory message with random cake or pie emojis. Automatically removes the birthday role at midnight, with a configurable timezone. Offers the option to set a specific announcement channel and restricts usage to specified roles. Users can assign the role without needing a higher role in the hierarchy. | -| **Overseerr** | Allows interaction with [Overseerr](https://overseerr.dev/) directly from Discord. Users can search for movies or TV shows, request them, and have admins approve requests. It's designed for servers with Overseerr set up for managing media requests. | - -## Installation - -To install the cogs in this repository, follow these steps: - -1. Ensure you have [Red](https://github.com/Cog-Creators/Red-DiscordBot) set up. -2. Add this repository to your Red instance: - - ```bash - [p]repo add Pac-cogs https://github.com/pacnpal/Pac-cogs - ``` - -3. Install a cog: - - ```bash - [p]cog install Pac-cogs - ``` - -4. Load the installed cog: - - ```bash - [p]load - ``` - -For more details on setting up and managing Red, visit the [Red documentation](https://docs.discord.red). From b33a325facb0eaf7f4ec00b998f041ca5f1223f8 Mon Sep 17 00:00:00 2001 From: pacnpal <183241239+pacnpal@users.noreply.github.com> Date: Thu, 14 Nov 2024 17:46:45 +0000 Subject: [PATCH 48/49] first --- video_archiver/__init__.py | 4 + video_archiver/ffmpeg_manager.py | 270 +++++++++++++++++ video_archiver/info.json | 22 ++ video_archiver/utils.py | 205 +++++++++++++ video_archiver/video_archiver.py | 494 +++++++++++++++++++++++++++++++ 5 files changed, 995 insertions(+) create mode 100644 video_archiver/__init__.py create mode 100644 video_archiver/ffmpeg_manager.py create mode 100644 video_archiver/info.json create mode 100644 video_archiver/utils.py create mode 100644 video_archiver/video_archiver.py diff --git a/video_archiver/__init__.py b/video_archiver/__init__.py new file mode 100644 index 0000000..7c68e10 --- /dev/null +++ b/video_archiver/__init__.py @@ -0,0 +1,4 @@ +from .video_archiver import VideoArchiver + +async def setup(bot): + await bot.add_cog(VideoArchiver(bot)) diff --git a/video_archiver/ffmpeg_manager.py b/video_archiver/ffmpeg_manager.py new file mode 100644 index 0000000..246f4be --- /dev/null +++ b/video_archiver/ffmpeg_manager.py @@ -0,0 +1,270 @@ +import os +import sys +import platform +import subprocess +import logging +import shutil +import requests +import zipfile +import tarfile +from pathlib import Path +import stat +import multiprocessing +import ffmpeg + +logger = logging.getLogger('VideoArchiver') + +class FFmpegManager: + FFMPEG_URLS = { + 'Windows': { + 'x86_64': { + 'url': 'https://github.com/BtbN/FFmpeg-Builds/releases/download/latest/ffmpeg-master-latest-win64-gpl.zip', + 'bin_name': 'ffmpeg.exe' + } + }, + 'Linux': { + 'x86_64': { + 'url': 'https://github.com/BtbN/FFmpeg-Builds/releases/download/latest/ffmpeg-master-latest-linux64-gpl.tar.xz', + 'bin_name': 'ffmpeg' + }, + 'aarch64': { # ARM64 + 'url': 'https://github.com/BtbN/FFmpeg-Builds/releases/download/latest/ffmpeg-master-latest-linuxarm64-gpl.tar.xz', + 'bin_name': 'ffmpeg' + }, + 'armv7l': { # ARM32 + 'url': 'https://github.com/BtbN/FFmpeg-Builds/releases/download/latest/ffmpeg-master-latest-linuxarm32-gpl.tar.xz', + 'bin_name': 'ffmpeg' + } + }, + 'Darwin': { # macOS + 'x86_64': { + 'url': 'https://evermeet.cx/ffmpeg/getrelease/zip', + 'bin_name': 'ffmpeg' + }, + 'arm64': { # Apple Silicon + 'url': 'https://evermeet.cx/ffmpeg/getrelease/zip', + 'bin_name': 'ffmpeg' + } + } + } + + def __init__(self): + self.base_path = Path(__file__).parent / 'bin' + self.base_path.mkdir(exist_ok=True) + + # Get system architecture + self.system = platform.system() + self.machine = platform.machine().lower() + if self.machine == 'arm64': + self.machine = 'aarch64' # Normalize ARM64 naming + + # Try to use system FFmpeg first + system_ffmpeg = shutil.which('ffmpeg') + if system_ffmpeg: + self.ffmpeg_path = Path(system_ffmpeg) + logger.info(f"Using system FFmpeg: {self.ffmpeg_path}") + else: + # Fall back to downloaded FFmpeg + try: + arch_config = self.FFMPEG_URLS[self.system][self.machine] + self.ffmpeg_path = self.base_path / arch_config['bin_name'] + except KeyError: + raise Exception(f"Unsupported system/architecture: {self.system}/{self.machine}") + + self._gpu_info = self._detect_gpu() + self._cpu_cores = multiprocessing.cpu_count() + + if not system_ffmpeg: + self._ensure_ffmpeg() + + def _detect_gpu(self) -> dict: + """Detect available GPU and its capabilities""" + gpu_info = { + 'nvidia': False, + 'amd': False, + 'intel': False, + 'arm': False + } + + try: + if self.system == 'Linux': + # Check for NVIDIA GPU + nvidia_smi = subprocess.run(['nvidia-smi'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) + if nvidia_smi.returncode == 0: + gpu_info['nvidia'] = True + + # Check for AMD GPU + if os.path.exists('/dev/dri/renderD128'): + gpu_info['amd'] = True + + # Check for Intel GPU + lspci = subprocess.run(['lspci'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) + if b'VGA' in lspci.stdout and b'Intel' in lspci.stdout: + gpu_info['intel'] = True + + # Check for ARM GPU + if self.machine in ['aarch64', 'armv7l']: + gpu_info['arm'] = True + + elif self.system == 'Windows': + # Check for any GPU using dxdiag + dxdiag = subprocess.run(['dxdiag', '/t', 'temp_dxdiag.txt'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) + if os.path.exists('temp_dxdiag.txt'): + with open('temp_dxdiag.txt', 'r') as f: + content = f.read().lower() + if 'nvidia' in content: + gpu_info['nvidia'] = True + if 'amd' in content or 'radeon' in content: + gpu_info['amd'] = True + if 'intel' in content: + gpu_info['intel'] = True + os.remove('temp_dxdiag.txt') + + except Exception as e: + logger.warning(f"GPU detection failed: {str(e)}") + + return gpu_info + + def _get_optimal_ffmpeg_params(self, input_path: str, target_size_bytes: int) -> dict: + """Get optimal FFmpeg parameters based on hardware and video size""" + params = { + 'c:v': 'libx264', # Default to CPU encoding + 'threads': str(self._cpu_cores), # Use all CPU cores + 'preset': 'medium', + 'crf': '23', # Default quality + 'maxrate': None, + 'bufsize': None, + 'movflags': '+faststart', # Optimize for web playback + 'profile:v': 'high', # High profile for better quality + 'level': '4.1', # Compatibility level + 'pix_fmt': 'yuv420p' # Standard pixel format + } + + # Check if GPU encoding is possible + if self._gpu_info['nvidia']: + params.update({ + 'c:v': 'h264_nvenc', + 'preset': 'p4', # High quality NVENC preset + 'rc:v': 'vbr', # Variable bitrate for better quality + 'cq:v': '19', # Quality level for NVENC + 'spatial-aq': '1', # Enable spatial adaptive quantization + 'temporal-aq': '1', # Enable temporal adaptive quantization + 'b_ref_mode': 'middle' # Better quality for B-frames + }) + elif self._gpu_info['amd']: + params.update({ + 'c:v': 'h264_amf', + 'quality': 'quality', + 'rc': 'vbr_peak', + 'enforce_hrd': '1', + 'vbaq': '1', # Enable adaptive quantization + 'preanalysis': '1' + }) + elif self._gpu_info['intel']: + params.update({ + 'c:v': 'h264_qsv', + 'preset': 'veryslow', # Best quality for QSV + 'look_ahead': '1', + 'global_quality': '23' + }) + elif self._gpu_info['arm']: + # Use OpenMAX (OMX) on supported ARM devices + if os.path.exists('/dev/video-codec'): + params.update({ + 'c:v': 'h264_v4l2m2m', # V4L2 M2M encoder + 'extra_hw_frames': '10' + }) + else: + # Fall back to optimized CPU encoding for ARM + params.update({ + 'c:v': 'libx264', + 'preset': 'medium', + 'tune': 'fastdecode' + }) + + # Get input file size and probe info + input_size = os.path.getsize(input_path) + probe = ffmpeg.probe(input_path) + duration = float(probe['format']['duration']) + + # Only add bitrate constraints if compression is needed + if input_size > target_size_bytes: + # Calculate target bitrate (bits/second) + target_bitrate = int((target_size_bytes * 8) / duration * 0.95) # 95% of target size + + params['maxrate'] = f"{target_bitrate}" + params['bufsize'] = f"{target_bitrate * 2}" + + # Adjust quality settings based on compression ratio + ratio = input_size / target_size_bytes + if ratio > 4: + params['crf'] = '28' if params['c:v'] == 'libx264' else '23' + params['preset'] = 'faster' + elif ratio > 2: + params['crf'] = '26' if params['c:v'] == 'libx264' else '21' + params['preset'] = 'medium' + else: + params['crf'] = '23' if params['c:v'] == 'libx264' else '19' + params['preset'] = 'slow' + + # Audio settings + params.update({ + 'c:a': 'aac', + 'b:a': '192k', # High quality audio + 'ar': '48000' # Standard sample rate + }) + + return params + + def _ensure_ffmpeg(self): + """Ensure FFmpeg is available, downloading if necessary""" + if not self.ffmpeg_path.exists(): + self._download_ffmpeg() + + # Make binary executable on Unix systems + if self.system != 'Windows': + self.ffmpeg_path.chmod(self.ffmpeg_path.stat().st_mode | stat.S_IEXEC) + + def _download_ffmpeg(self): + """Download and extract FFmpeg binary""" + try: + arch_config = self.FFMPEG_URLS[self.system][self.machine] + except KeyError: + raise Exception(f"Unsupported system/architecture: {self.system}/{self.machine}") + + url = arch_config['url'] + archive_path = self.base_path / f"ffmpeg_archive{'.zip' if self.system == 'Windows' else '.tar.xz'}" + + # Download archive + response = requests.get(url, stream=True) + response.raise_for_status() + with open(archive_path, 'wb') as f: + for chunk in response.iter_content(chunk_size=8192): + f.write(chunk) + + # Extract archive + if self.system == 'Windows': + with zipfile.ZipFile(archive_path, 'r') as zip_ref: + ffmpeg_files = [f for f in zip_ref.namelist() if arch_config['bin_name'] in f] + if ffmpeg_files: + zip_ref.extract(ffmpeg_files[0], self.base_path) + os.rename(self.base_path / ffmpeg_files[0], self.ffmpeg_path) + else: + with tarfile.open(archive_path, 'r:xz') as tar_ref: + ffmpeg_files = [f for f in tar_ref.getnames() if arch_config['bin_name'] in f] + if ffmpeg_files: + tar_ref.extract(ffmpeg_files[0], self.base_path) + os.rename(self.base_path / ffmpeg_files[0], self.ffmpeg_path) + + # Cleanup + archive_path.unlink() + + def get_ffmpeg_path(self) -> str: + """Get path to FFmpeg binary""" + if not self.ffmpeg_path.exists(): + raise Exception("FFmpeg is not available") + return str(self.ffmpeg_path) + + def get_compression_params(self, input_path: str, target_size_mb: int) -> dict: + """Get optimal compression parameters for the given input file""" + return self._get_optimal_ffmpeg_params(input_path, target_size_mb * 1024 * 1024) diff --git a/video_archiver/info.json b/video_archiver/info.json new file mode 100644 index 0000000..c3c9067 --- /dev/null +++ b/video_archiver/info.json @@ -0,0 +1,22 @@ +{ + "name": "VideoArchiver", + "author": ["Cline"], + "description": "A powerful Discord video archiver cog that automatically downloads and reposts videos from monitored channels. Features include:\n- GPU-accelerated video compression (NVIDIA, AMD, Intel)\n- Multi-core CPU utilization\n- Concurrent multi-video processing\n- Intelligent quality preservation\n- Support for multiple video sites\n- Customizable archive messages\n- Automatic cleanup", + "short": "Archive videos from Discord channels with GPU-accelerated compression", + "tags": [ + "video", + "archive", + "download", + "compression", + "media" + ], + "requirements": [ + "yt-dlp>=2023.12.30", + "ffmpeg-python>=0.2.0", + "requests>=2.31.0" + ], + "min_bot_version": "3.5.0", + "hidden": false, + "disabled": false, + "type": "COG" +} diff --git a/video_archiver/utils.py b/video_archiver/utils.py new file mode 100644 index 0000000..89caed0 --- /dev/null +++ b/video_archiver/utils.py @@ -0,0 +1,205 @@ +import os +import shutil +import logging +import asyncio +from pathlib import Path +from typing import Dict, List, Optional, Tuple, Set +import yt_dlp +import ffmpeg +from datetime import datetime, timedelta +from concurrent.futures import ThreadPoolExecutor +from .ffmpeg_manager import FFmpegManager + +logging.basicConfig( + level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s" +) +logger = logging.getLogger("VideoArchiver") + +# Initialize FFmpeg manager +ffmpeg_mgr = FFmpegManager() + +# Global thread pool for concurrent downloads +download_pool = ThreadPoolExecutor(max_workers=3) + +class VideoDownloader: + def __init__(self, download_path: str, video_format: str, max_quality: int, max_file_size: int, enabled_sites: Optional[List[str]] = None): + self.download_path = download_path + self.video_format = video_format + self.max_quality = max_quality + self.max_file_size = max_file_size + self.enabled_sites = enabled_sites + self.url_patterns = self._get_url_patterns() + + # Configure yt-dlp options + self.ydl_opts = { + 'format': f'bestvideo[height<={max_quality}]+bestaudio/best[height<={max_quality}]', + 'outtmpl': os.path.join(download_path, '%(title)s.%(ext)s'), + 'merge_output_format': video_format, + 'quiet': True, + 'no_warnings': True, + 'extract_flat': False, + 'concurrent_fragment_downloads': 3, + 'postprocessor_hooks': [self._check_file_size], + 'progress_hooks': [self._progress_hook], + 'ffmpeg_location': ffmpeg_mgr.get_ffmpeg_path(), + } + + def _get_url_patterns(self) -> List[str]: + """Get URL patterns for supported sites""" + patterns = [] + with yt_dlp.YoutubeDL() as ydl: + for extractor in ydl._ies: + if hasattr(extractor, '_VALID_URL') and extractor._VALID_URL: + if not self.enabled_sites or any(site.lower() in extractor.IE_NAME.lower() for site in self.enabled_sites): + patterns.append(extractor._VALID_URL) + return patterns + + def _check_file_size(self, info): + """Check if file size is within limits""" + if info.get('filepath') and os.path.exists(info['filepath']): + size = os.path.getsize(info['filepath']) + if size > (self.max_file_size * 1024 * 1024): + logger.info(f"File exceeds size limit, will compress: {info['filepath']}") + + def _progress_hook(self, d): + """Handle download progress""" + if d['status'] == 'finished': + logger.info(f"Download completed: {d['filename']}") + + async def download_video(self, url: str) -> Tuple[bool, str, str]: + """Download and process a video""" + try: + # Configure yt-dlp for this download + ydl_opts = self.ydl_opts.copy() + + with yt_dlp.YoutubeDL(ydl_opts) as ydl: + # Run download in executor to prevent blocking + info = await asyncio.get_event_loop().run_in_executor( + download_pool, lambda: ydl.extract_info(url, download=True) + ) + + if info is None: + return False, "", "Failed to extract video information" + + file_path = os.path.join(self.download_path, ydl.prepare_filename(info)) + + if not os.path.exists(file_path): + return False, "", "Download completed but file not found" + + # Check file size and compress if needed + file_size = os.path.getsize(file_path) + if file_size > (self.max_file_size * 1024 * 1024): + logger.info(f"Compressing video: {file_path}") + try: + # Get optimal compression parameters + params = ffmpeg_mgr.get_compression_params(file_path, self.max_file_size) + output_path = file_path + ".compressed." + self.video_format + + # Configure ffmpeg with optimal parameters + stream = ffmpeg.input(file_path) + stream = ffmpeg.output(stream, output_path, **params) + + # Run compression in executor + await asyncio.get_event_loop().run_in_executor( + None, + lambda: ffmpeg.run( + stream, + capture_stdout=True, + capture_stderr=True, + overwrite_output=True, + ), + ) + + if os.path.exists(output_path): + compressed_size = os.path.getsize(output_path) + if compressed_size <= (self.max_file_size * 1024 * 1024): + os.remove(file_path) # Remove original + return True, output_path, "" + else: + os.remove(output_path) + return False, "", "Failed to compress to target size" + except Exception as e: + logger.error(f"Compression error: {str(e)}") + return False, "", f"Compression error: {str(e)}" + + return True, file_path, "" + + except Exception as e: + logger.error(f"Download error: {str(e)}") + return False, "", str(e) + + def is_supported_url(self, url: str) -> bool: + """Check if URL is supported""" + try: + with yt_dlp.YoutubeDL() as ydl: + # Try to extract info without downloading + ie = ydl.extract_info(url, download=False, process=False) + return ie is not None + except: + return False + + +class MessageManager: + def __init__(self, message_duration: int, message_template: str): + self.message_duration = message_duration + self.message_template = message_template + self.scheduled_deletions: Dict[int, asyncio.Task] = {} + + def format_archive_message(self, author: str, url: str, original_message: str) -> str: + return self.message_template.format( + author=author, url=url, original_message=original_message + ) + + async def schedule_message_deletion(self, message_id: int, delete_func) -> None: + if self.message_duration <= 0: + return + + if message_id in self.scheduled_deletions: + self.scheduled_deletions[message_id].cancel() + + async def delete_later(): + await asyncio.sleep(self.message_duration * 3600) # Convert hours to seconds + try: + await delete_func() + except Exception as e: + logger.error(f"Failed to delete message {message_id}: {str(e)}") + finally: + self.scheduled_deletions.pop(message_id, None) + + self.scheduled_deletions[message_id] = asyncio.create_task(delete_later()) + + +def secure_delete_file(file_path: str, passes: int = 3) -> bool: + if not os.path.exists(file_path): + return True + + try: + file_size = os.path.getsize(file_path) + for _ in range(passes): + with open(file_path, "wb") as f: + f.write(os.urandom(file_size)) + f.flush() + os.fsync(f.fileno()) + + os.remove(file_path) + + if os.path.exists(file_path) or Path(file_path).exists(): + os.unlink(file_path) + + return not (os.path.exists(file_path) or Path(file_path).exists()) + + except Exception as e: + logger.error(f"Error during secure delete: {str(e)}") + return False + + +def cleanup_downloads(download_path: str) -> None: + try: + if os.path.exists(download_path): + for file_path in Path(download_path).glob("*"): + secure_delete_file(str(file_path)) + + shutil.rmtree(download_path, ignore_errors=True) + Path(download_path).mkdir(parents=True, exist_ok=True) + except Exception as e: + logger.error(f"Error during cleanup: {str(e)}") diff --git a/video_archiver/video_archiver.py b/video_archiver/video_archiver.py new file mode 100644 index 0000000..47166ec --- /dev/null +++ b/video_archiver/video_archiver.py @@ -0,0 +1,494 @@ +import os +import re +import discord +from redbot.core import commands, Config +from redbot.core.bot import Red +from redbot.core.utils.chat_formatting import box +from discord import app_commands +import logging +from pathlib import Path +import yt_dlp +import shutil +import asyncio +from typing import Optional, List, Set, Dict +import sys + +# Add cog directory to path for local imports +cog_path = Path(__file__).parent +if str(cog_path) not in sys.path: + sys.path.append(str(cog_path)) + +# Import local utils +from utils import VideoDownloader, secure_delete_file, cleanup_downloads, MessageManager +from ffmpeg_manager import FFmpegManager + +# Configure logging +logging.basicConfig( + level=logging.INFO, + format='%(asctime)s - %(name)s - %(levelname)s - %(message)s' +) +logger = logging.getLogger('VideoArchiver') + +class VideoArchiver(commands.Cog): + """Archive videos from Discord channels""" + + default_guild = { + "archive_channel": None, + "notification_channel": None, + "log_channel": None, # Added log channel + "monitored_channels": [], + "allowed_roles": [], # Added role management + "video_format": "mp4", + "video_quality": 1080, + "max_file_size": 8, # Changed to 8MB default + "delete_after_repost": True, + "message_duration": 24, + "message_template": "Archived video from {author}\nOriginal: {original_message}", + "enabled_sites": [], + "concurrent_downloads": 3 + } + + def __init__(self, bot: Red): + self.bot = bot + self.config = Config.get_conf(self, identifier=855847, force_registration=True) + self.config.register_guild(**self.default_guild) + + # Initialize components dict for each guild + self.components = {} + self.download_path = Path(cog_path) / "downloads" + self.download_path.mkdir(parents=True, exist_ok=True) + + # Clean up downloads on load + cleanup_downloads(str(self.download_path)) + + # Initialize FFmpeg manager + self.ffmpeg_mgr = FFmpegManager() + + def cog_unload(self): + """Cleanup when cog is unloaded""" + if self.download_path.exists(): + shutil.rmtree(self.download_path, ignore_errors=True) + + async def initialize_guild_components(self, guild_id: int): + """Initialize or update components for a guild""" + settings = await self.config.guild_from_id(guild_id).all() + + self.components[guild_id] = { + 'downloader': VideoDownloader( + str(self.download_path), + settings['video_format'], + settings['video_quality'], + settings['max_file_size'], + settings['enabled_sites'] if settings['enabled_sites'] else None + ), + 'message_manager': MessageManager( + settings['message_duration'], + settings['message_template'] + ) + } + + def _check_user_roles(self, member: discord.Member, allowed_roles: List[int]) -> bool: + """Check if user has permission to trigger archiving""" + # If no roles are set, allow all users + if not allowed_roles: + return True + + # Check if user has any of the allowed roles + return any(role.id in allowed_roles for role in member.roles) + + async def log_message(self, guild: discord.Guild, message: str, level: str = "info"): + """Send a log message to the guild's log channel if set""" + settings = await self.config.guild(guild).all() + if settings["log_channel"]: + try: + log_channel = guild.get_channel(settings["log_channel"]) + if log_channel: + await log_channel.send(f"[{level.upper()}] {message}") + except discord.HTTPException: + logger.error(f"Failed to send log message to channel: {message}") + logger.log(getattr(logging, level.upper()), message) + + @commands.hybrid_group(name="videoarchiver", aliases=["va"]) + @commands.guild_only() + @commands.admin_or_permissions(administrator=True) + async def videoarchiver(self, ctx: commands.Context): + """Video Archiver configuration commands""" + if ctx.invoked_subcommand is None: + settings = await self.config.guild(ctx.guild).all() + embed = discord.Embed( + title="Video Archiver Settings", + color=discord.Color.blue() + ) + + archive_channel = ctx.guild.get_channel(settings["archive_channel"]) if settings["archive_channel"] else None + notification_channel = ctx.guild.get_channel(settings["notification_channel"]) if settings["notification_channel"] else None + log_channel = ctx.guild.get_channel(settings["log_channel"]) if settings["log_channel"] else None + monitored_channels = [ctx.guild.get_channel(c) for c in settings["monitored_channels"]] + monitored_channels = [c.mention for c in monitored_channels if c] + allowed_roles = [ctx.guild.get_role(r) for r in settings["allowed_roles"]] + allowed_roles = [r.name for r in allowed_roles if r] + + embed.add_field( + name="Archive Channel", + value=archive_channel.mention if archive_channel else "Not set", + inline=False + ) + embed.add_field( + name="Notification Channel", + value=notification_channel.mention if notification_channel else "Same as archive", + inline=False + ) + embed.add_field( + name="Log Channel", + value=log_channel.mention if log_channel else "Not set", + inline=False + ) + embed.add_field( + name="Monitored Channels", + value="\n".join(monitored_channels) if monitored_channels else "None", + inline=False + ) + embed.add_field( + name="Allowed Roles", + value=", ".join(allowed_roles) if allowed_roles else "All roles (no restrictions)", + inline=False + ) + embed.add_field(name="Video Format", value=settings["video_format"], inline=True) + embed.add_field(name="Max Quality", value=f"{settings['video_quality']}p", inline=True) + embed.add_field(name="Max File Size", value=f"{settings['max_file_size']}MB", inline=True) + embed.add_field(name="Delete After Repost", value=str(settings["delete_after_repost"]), inline=True) + embed.add_field(name="Message Duration", value=f"{settings['message_duration']} hours", inline=True) + embed.add_field(name="Concurrent Downloads", value=str(settings["concurrent_downloads"]), inline=True) + embed.add_field( + name="Enabled Sites", + value=", ".join(settings["enabled_sites"]) if settings["enabled_sites"] else "All sites", + inline=False + ) + + # Add hardware info + gpu_info = self.ffmpeg_mgr._gpu_info + cpu_cores = self.ffmpeg_mgr._cpu_cores + + hardware_info = f"CPU Cores: {cpu_cores}\n" + if gpu_info['nvidia']: + hardware_info += "NVIDIA GPU: Available (using NVENC)\n" + if gpu_info['amd']: + hardware_info += "AMD GPU: Available (using AMF)\n" + if gpu_info['intel']: + hardware_info += "Intel GPU: Available (using QSV)\n" + if not any(gpu_info.values()): + hardware_info += "No GPU acceleration available (using CPU)\n" + + embed.add_field(name="Hardware Info", value=hardware_info, inline=False) + + await ctx.send(embed=embed) + + @videoarchiver.command(name="addrole") + async def add_allowed_role(self, ctx: commands.Context, role: discord.Role): + """Add a role that's allowed to trigger archiving""" + async with self.config.guild(ctx.guild).allowed_roles() as roles: + if role.id not in roles: + roles.append(role.id) + await ctx.send(f"Added {role.name} to allowed roles") + await self.log_message(ctx.guild, f"Added role {role.name} ({role.id}) to allowed roles") + await self.initialize_guild_components(ctx.guild.id) + + @videoarchiver.command(name="removerole") + async def remove_allowed_role(self, ctx: commands.Context, role: discord.Role): + """Remove a role from allowed roles""" + async with self.config.guild(ctx.guild).allowed_roles() as roles: + if role.id in roles: + roles.remove(role.id) + await ctx.send(f"Removed {role.name} from allowed roles") + await self.log_message(ctx.guild, f"Removed role {role.name} ({role.id}) from allowed roles") + await self.initialize_guild_components(ctx.guild.id) + + @videoarchiver.command(name="listroles") + async def list_allowed_roles(self, ctx: commands.Context): + """List all roles allowed to trigger archiving""" + roles = await self.config.guild(ctx.guild).allowed_roles() + if not roles: + await ctx.send("No roles are currently allowed (all users can trigger archiving)") + return + + role_names = [r.name for r in [ctx.guild.get_role(role_id) for role_id in roles] if r] + await ctx.send(f"Allowed roles: {', '.join(role_names)}") + + @videoarchiver.command(name="setconcurrent") + async def set_concurrent_downloads(self, ctx: commands.Context, count: int): + """Set the number of concurrent downloads (1-5)""" + if not 1 <= count <= 5: + await ctx.send("Concurrent downloads must be between 1 and 5") + return + + await self.config.guild(ctx.guild).concurrent_downloads.set(count) + await ctx.send(f"Concurrent downloads set to {count}") + await self.log_message(ctx.guild, f"Concurrent downloads set to {count}") + await self.initialize_guild_components(ctx.guild.id) + + @videoarchiver.command(name="setchannel") + async def set_archive_channel(self, ctx: commands.Context, channel: discord.TextChannel): + """Set the archive channel""" + await self.config.guild(ctx.guild).archive_channel.set(channel.id) + await ctx.send(f"Archive channel set to {channel.mention}") + await self.log_message(ctx.guild, f"Archive channel set to {channel.name} ({channel.id})") + await self.initialize_guild_components(ctx.guild.id) + + @videoarchiver.command(name="setnotification") + async def set_notification_channel(self, ctx: commands.Context, channel: discord.TextChannel): + """Set the notification channel (where archive messages appear)""" + await self.config.guild(ctx.guild).notification_channel.set(channel.id) + await ctx.send(f"Notification channel set to {channel.mention}") + await self.log_message(ctx.guild, f"Notification channel set to {channel.name} ({channel.id})") + await self.initialize_guild_components(ctx.guild.id) + + @videoarchiver.command(name="setlogchannel") + async def set_log_channel(self, ctx: commands.Context, channel: discord.TextChannel): + """Set the log channel for error messages and notifications""" + await self.config.guild(ctx.guild).log_channel.set(channel.id) + await ctx.send(f"Log channel set to {channel.mention}") + await self.log_message(ctx.guild, f"Log channel set to {channel.name} ({channel.id})") + await self.initialize_guild_components(ctx.guild.id) + + @videoarchiver.command(name="addmonitor") + async def add_monitored_channel(self, ctx: commands.Context, channel: discord.TextChannel): + """Add a channel to monitor for videos""" + async with self.config.guild(ctx.guild).monitored_channels() as channels: + if channel.id not in channels: + channels.append(channel.id) + await ctx.send(f"Now monitoring {channel.mention} for videos") + await self.log_message(ctx.guild, f"Added {channel.name} ({channel.id}) to monitored channels") + await self.initialize_guild_components(ctx.guild.id) + + @videoarchiver.command(name="removemonitor") + async def remove_monitored_channel(self, ctx: commands.Context, channel: discord.TextChannel): + """Remove a channel from monitoring""" + async with self.config.guild(ctx.guild).monitored_channels() as channels: + if channel.id in channels: + channels.remove(channel.id) + await ctx.send(f"Stopped monitoring {channel.mention}") + await self.log_message(ctx.guild, f"Removed {channel.name} ({channel.id}) from monitored channels") + await self.initialize_guild_components(ctx.guild.id) + + @videoarchiver.command(name="setformat") + async def set_video_format(self, ctx: commands.Context, format: str): + """Set the video format (e.g., mp4, webm)""" + await self.config.guild(ctx.guild).video_format.set(format.lower()) + await ctx.send(f"Video format set to {format.lower()}") + await self.log_message(ctx.guild, f"Video format set to {format.lower()}") + await self.initialize_guild_components(ctx.guild.id) + + @videoarchiver.command(name="setquality") + async def set_video_quality(self, ctx: commands.Context, quality: int): + """Set the maximum video quality in pixels (e.g., 1080)""" + await self.config.guild(ctx.guild).video_quality.set(quality) + await ctx.send(f"Maximum video quality set to {quality}p") + await self.log_message(ctx.guild, f"Video quality set to {quality}p") + await self.initialize_guild_components(ctx.guild.id) + + @videoarchiver.command(name="setmaxsize") + async def set_max_file_size(self, ctx: commands.Context, size: int): + """Set the maximum file size in MB""" + await self.config.guild(ctx.guild).max_file_size.set(size) + await ctx.send(f"Maximum file size set to {size}MB") + await self.log_message(ctx.guild, f"Maximum file size set to {size}MB") + await self.initialize_guild_components(ctx.guild.id) + + @videoarchiver.command(name="toggledelete") + async def toggle_delete_after_repost(self, ctx: commands.Context): + """Toggle whether to delete local files after reposting""" + current = await self.config.guild(ctx.guild).delete_after_repost() + await self.config.guild(ctx.guild).delete_after_repost.set(not current) + await ctx.send(f"Delete after repost: {not current}") + await self.log_message(ctx.guild, f"Delete after repost set to: {not current}") + + @videoarchiver.command(name="setduration") + async def set_message_duration(self, ctx: commands.Context, hours: int): + """Set how long to keep archive messages (0 for permanent)""" + await self.config.guild(ctx.guild).message_duration.set(hours) + await ctx.send(f"Archive message duration set to {hours} hours") + await self.log_message(ctx.guild, f"Message duration set to {hours} hours") + await self.initialize_guild_components(ctx.guild.id) + + @videoarchiver.command(name="settemplate") + async def set_message_template(self, ctx: commands.Context, *, template: str): + """Set the archive message template. Use {author}, {url}, and {original_message} as placeholders""" + await self.config.guild(ctx.guild).message_template.set(template) + await ctx.send(f"Archive message template set to:\n{template}") + await self.log_message(ctx.guild, f"Message template updated") + await self.initialize_guild_components(ctx.guild.id) + + @videoarchiver.command(name="enablesites") + async def enable_sites(self, ctx: commands.Context, *sites: str): + """Enable specific sites (leave empty for all sites)""" + sites = [s.lower() for s in sites] + if not sites: + await self.config.guild(ctx.guild).enabled_sites.set([]) + await ctx.send("All sites enabled") + else: + # Verify sites are valid + with yt_dlp.YoutubeDL() as ydl: + valid_sites = set(ie.IE_NAME.lower() for ie in ydl._ies) + invalid_sites = [s for s in sites if s not in valid_sites] + if invalid_sites: + await ctx.send(f"Invalid sites: {', '.join(invalid_sites)}\nValid sites: {', '.join(valid_sites)}") + return + + await self.config.guild(ctx.guild).enabled_sites.set(sites) + await ctx.send(f"Enabled sites: {', '.join(sites)}") + + await self.log_message(ctx.guild, f"Enabled sites updated: {', '.join(sites) if sites else 'All sites'}") + await self.initialize_guild_components(ctx.guild.id) + + @videoarchiver.command(name="listsites") + async def list_sites(self, ctx: commands.Context): + """List all available sites and currently enabled sites""" + settings = await self.config.guild(ctx.guild).all() + enabled_sites = settings["enabled_sites"] + + embed = discord.Embed( + title="Video Sites Configuration", + color=discord.Color.blue() + ) + + with yt_dlp.YoutubeDL() as ydl: + all_sites = sorted(ie.IE_NAME for ie in ydl._ies if ie.IE_NAME is not None) + + # Split sites into chunks for Discord's field value limit + chunk_size = 20 + site_chunks = [all_sites[i:i + chunk_size] for i in range(0, len(all_sites), chunk_size)] + + for i, chunk in enumerate(site_chunks, 1): + embed.add_field( + name=f"Available Sites ({i}/{len(site_chunks)})", + value=", ".join(chunk), + inline=False + ) + + embed.add_field( + name="Currently Enabled", + value=", ".join(enabled_sites) if enabled_sites else "All sites", + inline=False + ) + + await ctx.send(embed=embed) + + async def process_video_url(self, url: str, message: discord.Message) -> bool: + """Process a video URL: download, reupload, and cleanup""" + guild_id = message.guild.id + + # Initialize components if needed + if guild_id not in self.components: + await self.initialize_guild_components(guild_id) + + try: + await message.add_reaction('⏳') + await self.log_message(message.guild, f"Processing video URL: {url}") + + settings = await self.config.guild(message.guild).all() + + # Check user roles + if not self._check_user_roles(message.author, settings['allowed_roles']): + await message.add_reaction('🚫') + return False + + # Download video + success, file_path, error = await self.components[guild_id]['downloader'].download_video(url) + + if not success: + await message.add_reaction('❌') + await self.log_message(message.guild, f"Failed to download video: {error}", "error") + return False + + # Get channels + archive_channel = message.guild.get_channel(settings['archive_channel']) + notification_channel = message.guild.get_channel( + settings['notification_channel'] if settings['notification_channel'] + else settings['archive_channel'] + ) + + if not archive_channel or not notification_channel: + await self.log_message(message.guild, "Required channels not found!", "error") + return False + + try: + # Upload to archive channel + file = discord.File(file_path) + archive_message = await archive_channel.send(file=file) + + # Send notification with information + notification_message = await notification_channel.send( + self.components[guild_id]['message_manager'].format_archive_message( + author=message.author.mention, + url=archive_message.attachments[0].url if archive_message.attachments else "No URL available", + original_message=message.jump_url + ) + ) + + # Schedule notification message deletion if needed + await self.components[guild_id]['message_manager'].schedule_message_deletion( + notification_message.id, + notification_message.delete + ) + + await message.add_reaction('✅') + await self.log_message(message.guild, f"Successfully archived video from {message.author}") + + except discord.HTTPException as e: + await self.log_message(message.guild, f"Failed to upload video: {str(e)}", "error") + await message.add_reaction('❌') + return False + + finally: + # Always attempt to delete the file if configured + if settings['delete_after_repost']: + if secure_delete_file(file_path): + await self.log_message(message.guild, f"Successfully deleted file: {file_path}") + else: + await self.log_message(message.guild, f"Failed to delete file: {file_path}", "error") + # Emergency cleanup + cleanup_downloads(str(self.download_path)) + + return True + + except Exception as e: + await self.log_message(message.guild, f"Error processing video: {str(e)}", "error") + await message.add_reaction('❌') + return False + + @commands.Cog.listener() + async def on_message(self, message: discord.Message): + if message.author.bot or not message.guild: + return + + settings = await self.config.guild(message.guild).all() + + # Check if message is in a monitored channel + if message.channel.id not in settings['monitored_channels']: + return + + # Initialize components if needed + if message.guild.id not in self.components: + await self.initialize_guild_components(message.guild.id) + + # Find all video URLs in message + urls = [] + with yt_dlp.YoutubeDL() as ydl: + for ie in ydl._ies: + if ie._VALID_URL: + urls.extend(re.findall(ie._VALID_URL, message.content)) + + if urls: + # Process multiple URLs concurrently but limited + tasks = [] + semaphore = asyncio.Semaphore(settings['concurrent_downloads']) + + async def process_with_semaphore(url): + async with semaphore: + return await self.process_video_url(url, message) + + for url in urls: + tasks.append(asyncio.create_task(process_with_semaphore(url))) + + # Wait for all downloads to complete + await asyncio.gather(*tasks) From cbbd234d56e507e614c446d6caa24d02d43142cc Mon Sep 17 00:00:00 2001 From: pacnpal <183241239+pacnpal@users.noreply.github.com> Date: Thu, 14 Nov 2024 17:58:40 +0000 Subject: [PATCH 49/49] commit for rebase --- video_archiver/__init__.py | 4 - video_archiver/ffmpeg_manager.py | 270 ----------------- video_archiver/info.json | 22 -- video_archiver/utils.py | 205 ------------- video_archiver/video_archiver.py | 494 ------------------------------- 5 files changed, 995 deletions(-) delete mode 100644 video_archiver/__init__.py delete mode 100644 video_archiver/ffmpeg_manager.py delete mode 100644 video_archiver/info.json delete mode 100644 video_archiver/utils.py delete mode 100644 video_archiver/video_archiver.py diff --git a/video_archiver/__init__.py b/video_archiver/__init__.py deleted file mode 100644 index 7c68e10..0000000 --- a/video_archiver/__init__.py +++ /dev/null @@ -1,4 +0,0 @@ -from .video_archiver import VideoArchiver - -async def setup(bot): - await bot.add_cog(VideoArchiver(bot)) diff --git a/video_archiver/ffmpeg_manager.py b/video_archiver/ffmpeg_manager.py deleted file mode 100644 index 246f4be..0000000 --- a/video_archiver/ffmpeg_manager.py +++ /dev/null @@ -1,270 +0,0 @@ -import os -import sys -import platform -import subprocess -import logging -import shutil -import requests -import zipfile -import tarfile -from pathlib import Path -import stat -import multiprocessing -import ffmpeg - -logger = logging.getLogger('VideoArchiver') - -class FFmpegManager: - FFMPEG_URLS = { - 'Windows': { - 'x86_64': { - 'url': 'https://github.com/BtbN/FFmpeg-Builds/releases/download/latest/ffmpeg-master-latest-win64-gpl.zip', - 'bin_name': 'ffmpeg.exe' - } - }, - 'Linux': { - 'x86_64': { - 'url': 'https://github.com/BtbN/FFmpeg-Builds/releases/download/latest/ffmpeg-master-latest-linux64-gpl.tar.xz', - 'bin_name': 'ffmpeg' - }, - 'aarch64': { # ARM64 - 'url': 'https://github.com/BtbN/FFmpeg-Builds/releases/download/latest/ffmpeg-master-latest-linuxarm64-gpl.tar.xz', - 'bin_name': 'ffmpeg' - }, - 'armv7l': { # ARM32 - 'url': 'https://github.com/BtbN/FFmpeg-Builds/releases/download/latest/ffmpeg-master-latest-linuxarm32-gpl.tar.xz', - 'bin_name': 'ffmpeg' - } - }, - 'Darwin': { # macOS - 'x86_64': { - 'url': 'https://evermeet.cx/ffmpeg/getrelease/zip', - 'bin_name': 'ffmpeg' - }, - 'arm64': { # Apple Silicon - 'url': 'https://evermeet.cx/ffmpeg/getrelease/zip', - 'bin_name': 'ffmpeg' - } - } - } - - def __init__(self): - self.base_path = Path(__file__).parent / 'bin' - self.base_path.mkdir(exist_ok=True) - - # Get system architecture - self.system = platform.system() - self.machine = platform.machine().lower() - if self.machine == 'arm64': - self.machine = 'aarch64' # Normalize ARM64 naming - - # Try to use system FFmpeg first - system_ffmpeg = shutil.which('ffmpeg') - if system_ffmpeg: - self.ffmpeg_path = Path(system_ffmpeg) - logger.info(f"Using system FFmpeg: {self.ffmpeg_path}") - else: - # Fall back to downloaded FFmpeg - try: - arch_config = self.FFMPEG_URLS[self.system][self.machine] - self.ffmpeg_path = self.base_path / arch_config['bin_name'] - except KeyError: - raise Exception(f"Unsupported system/architecture: {self.system}/{self.machine}") - - self._gpu_info = self._detect_gpu() - self._cpu_cores = multiprocessing.cpu_count() - - if not system_ffmpeg: - self._ensure_ffmpeg() - - def _detect_gpu(self) -> dict: - """Detect available GPU and its capabilities""" - gpu_info = { - 'nvidia': False, - 'amd': False, - 'intel': False, - 'arm': False - } - - try: - if self.system == 'Linux': - # Check for NVIDIA GPU - nvidia_smi = subprocess.run(['nvidia-smi'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) - if nvidia_smi.returncode == 0: - gpu_info['nvidia'] = True - - # Check for AMD GPU - if os.path.exists('/dev/dri/renderD128'): - gpu_info['amd'] = True - - # Check for Intel GPU - lspci = subprocess.run(['lspci'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) - if b'VGA' in lspci.stdout and b'Intel' in lspci.stdout: - gpu_info['intel'] = True - - # Check for ARM GPU - if self.machine in ['aarch64', 'armv7l']: - gpu_info['arm'] = True - - elif self.system == 'Windows': - # Check for any GPU using dxdiag - dxdiag = subprocess.run(['dxdiag', '/t', 'temp_dxdiag.txt'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) - if os.path.exists('temp_dxdiag.txt'): - with open('temp_dxdiag.txt', 'r') as f: - content = f.read().lower() - if 'nvidia' in content: - gpu_info['nvidia'] = True - if 'amd' in content or 'radeon' in content: - gpu_info['amd'] = True - if 'intel' in content: - gpu_info['intel'] = True - os.remove('temp_dxdiag.txt') - - except Exception as e: - logger.warning(f"GPU detection failed: {str(e)}") - - return gpu_info - - def _get_optimal_ffmpeg_params(self, input_path: str, target_size_bytes: int) -> dict: - """Get optimal FFmpeg parameters based on hardware and video size""" - params = { - 'c:v': 'libx264', # Default to CPU encoding - 'threads': str(self._cpu_cores), # Use all CPU cores - 'preset': 'medium', - 'crf': '23', # Default quality - 'maxrate': None, - 'bufsize': None, - 'movflags': '+faststart', # Optimize for web playback - 'profile:v': 'high', # High profile for better quality - 'level': '4.1', # Compatibility level - 'pix_fmt': 'yuv420p' # Standard pixel format - } - - # Check if GPU encoding is possible - if self._gpu_info['nvidia']: - params.update({ - 'c:v': 'h264_nvenc', - 'preset': 'p4', # High quality NVENC preset - 'rc:v': 'vbr', # Variable bitrate for better quality - 'cq:v': '19', # Quality level for NVENC - 'spatial-aq': '1', # Enable spatial adaptive quantization - 'temporal-aq': '1', # Enable temporal adaptive quantization - 'b_ref_mode': 'middle' # Better quality for B-frames - }) - elif self._gpu_info['amd']: - params.update({ - 'c:v': 'h264_amf', - 'quality': 'quality', - 'rc': 'vbr_peak', - 'enforce_hrd': '1', - 'vbaq': '1', # Enable adaptive quantization - 'preanalysis': '1' - }) - elif self._gpu_info['intel']: - params.update({ - 'c:v': 'h264_qsv', - 'preset': 'veryslow', # Best quality for QSV - 'look_ahead': '1', - 'global_quality': '23' - }) - elif self._gpu_info['arm']: - # Use OpenMAX (OMX) on supported ARM devices - if os.path.exists('/dev/video-codec'): - params.update({ - 'c:v': 'h264_v4l2m2m', # V4L2 M2M encoder - 'extra_hw_frames': '10' - }) - else: - # Fall back to optimized CPU encoding for ARM - params.update({ - 'c:v': 'libx264', - 'preset': 'medium', - 'tune': 'fastdecode' - }) - - # Get input file size and probe info - input_size = os.path.getsize(input_path) - probe = ffmpeg.probe(input_path) - duration = float(probe['format']['duration']) - - # Only add bitrate constraints if compression is needed - if input_size > target_size_bytes: - # Calculate target bitrate (bits/second) - target_bitrate = int((target_size_bytes * 8) / duration * 0.95) # 95% of target size - - params['maxrate'] = f"{target_bitrate}" - params['bufsize'] = f"{target_bitrate * 2}" - - # Adjust quality settings based on compression ratio - ratio = input_size / target_size_bytes - if ratio > 4: - params['crf'] = '28' if params['c:v'] == 'libx264' else '23' - params['preset'] = 'faster' - elif ratio > 2: - params['crf'] = '26' if params['c:v'] == 'libx264' else '21' - params['preset'] = 'medium' - else: - params['crf'] = '23' if params['c:v'] == 'libx264' else '19' - params['preset'] = 'slow' - - # Audio settings - params.update({ - 'c:a': 'aac', - 'b:a': '192k', # High quality audio - 'ar': '48000' # Standard sample rate - }) - - return params - - def _ensure_ffmpeg(self): - """Ensure FFmpeg is available, downloading if necessary""" - if not self.ffmpeg_path.exists(): - self._download_ffmpeg() - - # Make binary executable on Unix systems - if self.system != 'Windows': - self.ffmpeg_path.chmod(self.ffmpeg_path.stat().st_mode | stat.S_IEXEC) - - def _download_ffmpeg(self): - """Download and extract FFmpeg binary""" - try: - arch_config = self.FFMPEG_URLS[self.system][self.machine] - except KeyError: - raise Exception(f"Unsupported system/architecture: {self.system}/{self.machine}") - - url = arch_config['url'] - archive_path = self.base_path / f"ffmpeg_archive{'.zip' if self.system == 'Windows' else '.tar.xz'}" - - # Download archive - response = requests.get(url, stream=True) - response.raise_for_status() - with open(archive_path, 'wb') as f: - for chunk in response.iter_content(chunk_size=8192): - f.write(chunk) - - # Extract archive - if self.system == 'Windows': - with zipfile.ZipFile(archive_path, 'r') as zip_ref: - ffmpeg_files = [f for f in zip_ref.namelist() if arch_config['bin_name'] in f] - if ffmpeg_files: - zip_ref.extract(ffmpeg_files[0], self.base_path) - os.rename(self.base_path / ffmpeg_files[0], self.ffmpeg_path) - else: - with tarfile.open(archive_path, 'r:xz') as tar_ref: - ffmpeg_files = [f for f in tar_ref.getnames() if arch_config['bin_name'] in f] - if ffmpeg_files: - tar_ref.extract(ffmpeg_files[0], self.base_path) - os.rename(self.base_path / ffmpeg_files[0], self.ffmpeg_path) - - # Cleanup - archive_path.unlink() - - def get_ffmpeg_path(self) -> str: - """Get path to FFmpeg binary""" - if not self.ffmpeg_path.exists(): - raise Exception("FFmpeg is not available") - return str(self.ffmpeg_path) - - def get_compression_params(self, input_path: str, target_size_mb: int) -> dict: - """Get optimal compression parameters for the given input file""" - return self._get_optimal_ffmpeg_params(input_path, target_size_mb * 1024 * 1024) diff --git a/video_archiver/info.json b/video_archiver/info.json deleted file mode 100644 index c3c9067..0000000 --- a/video_archiver/info.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "name": "VideoArchiver", - "author": ["Cline"], - "description": "A powerful Discord video archiver cog that automatically downloads and reposts videos from monitored channels. Features include:\n- GPU-accelerated video compression (NVIDIA, AMD, Intel)\n- Multi-core CPU utilization\n- Concurrent multi-video processing\n- Intelligent quality preservation\n- Support for multiple video sites\n- Customizable archive messages\n- Automatic cleanup", - "short": "Archive videos from Discord channels with GPU-accelerated compression", - "tags": [ - "video", - "archive", - "download", - "compression", - "media" - ], - "requirements": [ - "yt-dlp>=2023.12.30", - "ffmpeg-python>=0.2.0", - "requests>=2.31.0" - ], - "min_bot_version": "3.5.0", - "hidden": false, - "disabled": false, - "type": "COG" -} diff --git a/video_archiver/utils.py b/video_archiver/utils.py deleted file mode 100644 index 89caed0..0000000 --- a/video_archiver/utils.py +++ /dev/null @@ -1,205 +0,0 @@ -import os -import shutil -import logging -import asyncio -from pathlib import Path -from typing import Dict, List, Optional, Tuple, Set -import yt_dlp -import ffmpeg -from datetime import datetime, timedelta -from concurrent.futures import ThreadPoolExecutor -from .ffmpeg_manager import FFmpegManager - -logging.basicConfig( - level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s" -) -logger = logging.getLogger("VideoArchiver") - -# Initialize FFmpeg manager -ffmpeg_mgr = FFmpegManager() - -# Global thread pool for concurrent downloads -download_pool = ThreadPoolExecutor(max_workers=3) - -class VideoDownloader: - def __init__(self, download_path: str, video_format: str, max_quality: int, max_file_size: int, enabled_sites: Optional[List[str]] = None): - self.download_path = download_path - self.video_format = video_format - self.max_quality = max_quality - self.max_file_size = max_file_size - self.enabled_sites = enabled_sites - self.url_patterns = self._get_url_patterns() - - # Configure yt-dlp options - self.ydl_opts = { - 'format': f'bestvideo[height<={max_quality}]+bestaudio/best[height<={max_quality}]', - 'outtmpl': os.path.join(download_path, '%(title)s.%(ext)s'), - 'merge_output_format': video_format, - 'quiet': True, - 'no_warnings': True, - 'extract_flat': False, - 'concurrent_fragment_downloads': 3, - 'postprocessor_hooks': [self._check_file_size], - 'progress_hooks': [self._progress_hook], - 'ffmpeg_location': ffmpeg_mgr.get_ffmpeg_path(), - } - - def _get_url_patterns(self) -> List[str]: - """Get URL patterns for supported sites""" - patterns = [] - with yt_dlp.YoutubeDL() as ydl: - for extractor in ydl._ies: - if hasattr(extractor, '_VALID_URL') and extractor._VALID_URL: - if not self.enabled_sites or any(site.lower() in extractor.IE_NAME.lower() for site in self.enabled_sites): - patterns.append(extractor._VALID_URL) - return patterns - - def _check_file_size(self, info): - """Check if file size is within limits""" - if info.get('filepath') and os.path.exists(info['filepath']): - size = os.path.getsize(info['filepath']) - if size > (self.max_file_size * 1024 * 1024): - logger.info(f"File exceeds size limit, will compress: {info['filepath']}") - - def _progress_hook(self, d): - """Handle download progress""" - if d['status'] == 'finished': - logger.info(f"Download completed: {d['filename']}") - - async def download_video(self, url: str) -> Tuple[bool, str, str]: - """Download and process a video""" - try: - # Configure yt-dlp for this download - ydl_opts = self.ydl_opts.copy() - - with yt_dlp.YoutubeDL(ydl_opts) as ydl: - # Run download in executor to prevent blocking - info = await asyncio.get_event_loop().run_in_executor( - download_pool, lambda: ydl.extract_info(url, download=True) - ) - - if info is None: - return False, "", "Failed to extract video information" - - file_path = os.path.join(self.download_path, ydl.prepare_filename(info)) - - if not os.path.exists(file_path): - return False, "", "Download completed but file not found" - - # Check file size and compress if needed - file_size = os.path.getsize(file_path) - if file_size > (self.max_file_size * 1024 * 1024): - logger.info(f"Compressing video: {file_path}") - try: - # Get optimal compression parameters - params = ffmpeg_mgr.get_compression_params(file_path, self.max_file_size) - output_path = file_path + ".compressed." + self.video_format - - # Configure ffmpeg with optimal parameters - stream = ffmpeg.input(file_path) - stream = ffmpeg.output(stream, output_path, **params) - - # Run compression in executor - await asyncio.get_event_loop().run_in_executor( - None, - lambda: ffmpeg.run( - stream, - capture_stdout=True, - capture_stderr=True, - overwrite_output=True, - ), - ) - - if os.path.exists(output_path): - compressed_size = os.path.getsize(output_path) - if compressed_size <= (self.max_file_size * 1024 * 1024): - os.remove(file_path) # Remove original - return True, output_path, "" - else: - os.remove(output_path) - return False, "", "Failed to compress to target size" - except Exception as e: - logger.error(f"Compression error: {str(e)}") - return False, "", f"Compression error: {str(e)}" - - return True, file_path, "" - - except Exception as e: - logger.error(f"Download error: {str(e)}") - return False, "", str(e) - - def is_supported_url(self, url: str) -> bool: - """Check if URL is supported""" - try: - with yt_dlp.YoutubeDL() as ydl: - # Try to extract info without downloading - ie = ydl.extract_info(url, download=False, process=False) - return ie is not None - except: - return False - - -class MessageManager: - def __init__(self, message_duration: int, message_template: str): - self.message_duration = message_duration - self.message_template = message_template - self.scheduled_deletions: Dict[int, asyncio.Task] = {} - - def format_archive_message(self, author: str, url: str, original_message: str) -> str: - return self.message_template.format( - author=author, url=url, original_message=original_message - ) - - async def schedule_message_deletion(self, message_id: int, delete_func) -> None: - if self.message_duration <= 0: - return - - if message_id in self.scheduled_deletions: - self.scheduled_deletions[message_id].cancel() - - async def delete_later(): - await asyncio.sleep(self.message_duration * 3600) # Convert hours to seconds - try: - await delete_func() - except Exception as e: - logger.error(f"Failed to delete message {message_id}: {str(e)}") - finally: - self.scheduled_deletions.pop(message_id, None) - - self.scheduled_deletions[message_id] = asyncio.create_task(delete_later()) - - -def secure_delete_file(file_path: str, passes: int = 3) -> bool: - if not os.path.exists(file_path): - return True - - try: - file_size = os.path.getsize(file_path) - for _ in range(passes): - with open(file_path, "wb") as f: - f.write(os.urandom(file_size)) - f.flush() - os.fsync(f.fileno()) - - os.remove(file_path) - - if os.path.exists(file_path) or Path(file_path).exists(): - os.unlink(file_path) - - return not (os.path.exists(file_path) or Path(file_path).exists()) - - except Exception as e: - logger.error(f"Error during secure delete: {str(e)}") - return False - - -def cleanup_downloads(download_path: str) -> None: - try: - if os.path.exists(download_path): - for file_path in Path(download_path).glob("*"): - secure_delete_file(str(file_path)) - - shutil.rmtree(download_path, ignore_errors=True) - Path(download_path).mkdir(parents=True, exist_ok=True) - except Exception as e: - logger.error(f"Error during cleanup: {str(e)}") diff --git a/video_archiver/video_archiver.py b/video_archiver/video_archiver.py deleted file mode 100644 index 47166ec..0000000 --- a/video_archiver/video_archiver.py +++ /dev/null @@ -1,494 +0,0 @@ -import os -import re -import discord -from redbot.core import commands, Config -from redbot.core.bot import Red -from redbot.core.utils.chat_formatting import box -from discord import app_commands -import logging -from pathlib import Path -import yt_dlp -import shutil -import asyncio -from typing import Optional, List, Set, Dict -import sys - -# Add cog directory to path for local imports -cog_path = Path(__file__).parent -if str(cog_path) not in sys.path: - sys.path.append(str(cog_path)) - -# Import local utils -from utils import VideoDownloader, secure_delete_file, cleanup_downloads, MessageManager -from ffmpeg_manager import FFmpegManager - -# Configure logging -logging.basicConfig( - level=logging.INFO, - format='%(asctime)s - %(name)s - %(levelname)s - %(message)s' -) -logger = logging.getLogger('VideoArchiver') - -class VideoArchiver(commands.Cog): - """Archive videos from Discord channels""" - - default_guild = { - "archive_channel": None, - "notification_channel": None, - "log_channel": None, # Added log channel - "monitored_channels": [], - "allowed_roles": [], # Added role management - "video_format": "mp4", - "video_quality": 1080, - "max_file_size": 8, # Changed to 8MB default - "delete_after_repost": True, - "message_duration": 24, - "message_template": "Archived video from {author}\nOriginal: {original_message}", - "enabled_sites": [], - "concurrent_downloads": 3 - } - - def __init__(self, bot: Red): - self.bot = bot - self.config = Config.get_conf(self, identifier=855847, force_registration=True) - self.config.register_guild(**self.default_guild) - - # Initialize components dict for each guild - self.components = {} - self.download_path = Path(cog_path) / "downloads" - self.download_path.mkdir(parents=True, exist_ok=True) - - # Clean up downloads on load - cleanup_downloads(str(self.download_path)) - - # Initialize FFmpeg manager - self.ffmpeg_mgr = FFmpegManager() - - def cog_unload(self): - """Cleanup when cog is unloaded""" - if self.download_path.exists(): - shutil.rmtree(self.download_path, ignore_errors=True) - - async def initialize_guild_components(self, guild_id: int): - """Initialize or update components for a guild""" - settings = await self.config.guild_from_id(guild_id).all() - - self.components[guild_id] = { - 'downloader': VideoDownloader( - str(self.download_path), - settings['video_format'], - settings['video_quality'], - settings['max_file_size'], - settings['enabled_sites'] if settings['enabled_sites'] else None - ), - 'message_manager': MessageManager( - settings['message_duration'], - settings['message_template'] - ) - } - - def _check_user_roles(self, member: discord.Member, allowed_roles: List[int]) -> bool: - """Check if user has permission to trigger archiving""" - # If no roles are set, allow all users - if not allowed_roles: - return True - - # Check if user has any of the allowed roles - return any(role.id in allowed_roles for role in member.roles) - - async def log_message(self, guild: discord.Guild, message: str, level: str = "info"): - """Send a log message to the guild's log channel if set""" - settings = await self.config.guild(guild).all() - if settings["log_channel"]: - try: - log_channel = guild.get_channel(settings["log_channel"]) - if log_channel: - await log_channel.send(f"[{level.upper()}] {message}") - except discord.HTTPException: - logger.error(f"Failed to send log message to channel: {message}") - logger.log(getattr(logging, level.upper()), message) - - @commands.hybrid_group(name="videoarchiver", aliases=["va"]) - @commands.guild_only() - @commands.admin_or_permissions(administrator=True) - async def videoarchiver(self, ctx: commands.Context): - """Video Archiver configuration commands""" - if ctx.invoked_subcommand is None: - settings = await self.config.guild(ctx.guild).all() - embed = discord.Embed( - title="Video Archiver Settings", - color=discord.Color.blue() - ) - - archive_channel = ctx.guild.get_channel(settings["archive_channel"]) if settings["archive_channel"] else None - notification_channel = ctx.guild.get_channel(settings["notification_channel"]) if settings["notification_channel"] else None - log_channel = ctx.guild.get_channel(settings["log_channel"]) if settings["log_channel"] else None - monitored_channels = [ctx.guild.get_channel(c) for c in settings["monitored_channels"]] - monitored_channels = [c.mention for c in monitored_channels if c] - allowed_roles = [ctx.guild.get_role(r) for r in settings["allowed_roles"]] - allowed_roles = [r.name for r in allowed_roles if r] - - embed.add_field( - name="Archive Channel", - value=archive_channel.mention if archive_channel else "Not set", - inline=False - ) - embed.add_field( - name="Notification Channel", - value=notification_channel.mention if notification_channel else "Same as archive", - inline=False - ) - embed.add_field( - name="Log Channel", - value=log_channel.mention if log_channel else "Not set", - inline=False - ) - embed.add_field( - name="Monitored Channels", - value="\n".join(monitored_channels) if monitored_channels else "None", - inline=False - ) - embed.add_field( - name="Allowed Roles", - value=", ".join(allowed_roles) if allowed_roles else "All roles (no restrictions)", - inline=False - ) - embed.add_field(name="Video Format", value=settings["video_format"], inline=True) - embed.add_field(name="Max Quality", value=f"{settings['video_quality']}p", inline=True) - embed.add_field(name="Max File Size", value=f"{settings['max_file_size']}MB", inline=True) - embed.add_field(name="Delete After Repost", value=str(settings["delete_after_repost"]), inline=True) - embed.add_field(name="Message Duration", value=f"{settings['message_duration']} hours", inline=True) - embed.add_field(name="Concurrent Downloads", value=str(settings["concurrent_downloads"]), inline=True) - embed.add_field( - name="Enabled Sites", - value=", ".join(settings["enabled_sites"]) if settings["enabled_sites"] else "All sites", - inline=False - ) - - # Add hardware info - gpu_info = self.ffmpeg_mgr._gpu_info - cpu_cores = self.ffmpeg_mgr._cpu_cores - - hardware_info = f"CPU Cores: {cpu_cores}\n" - if gpu_info['nvidia']: - hardware_info += "NVIDIA GPU: Available (using NVENC)\n" - if gpu_info['amd']: - hardware_info += "AMD GPU: Available (using AMF)\n" - if gpu_info['intel']: - hardware_info += "Intel GPU: Available (using QSV)\n" - if not any(gpu_info.values()): - hardware_info += "No GPU acceleration available (using CPU)\n" - - embed.add_field(name="Hardware Info", value=hardware_info, inline=False) - - await ctx.send(embed=embed) - - @videoarchiver.command(name="addrole") - async def add_allowed_role(self, ctx: commands.Context, role: discord.Role): - """Add a role that's allowed to trigger archiving""" - async with self.config.guild(ctx.guild).allowed_roles() as roles: - if role.id not in roles: - roles.append(role.id) - await ctx.send(f"Added {role.name} to allowed roles") - await self.log_message(ctx.guild, f"Added role {role.name} ({role.id}) to allowed roles") - await self.initialize_guild_components(ctx.guild.id) - - @videoarchiver.command(name="removerole") - async def remove_allowed_role(self, ctx: commands.Context, role: discord.Role): - """Remove a role from allowed roles""" - async with self.config.guild(ctx.guild).allowed_roles() as roles: - if role.id in roles: - roles.remove(role.id) - await ctx.send(f"Removed {role.name} from allowed roles") - await self.log_message(ctx.guild, f"Removed role {role.name} ({role.id}) from allowed roles") - await self.initialize_guild_components(ctx.guild.id) - - @videoarchiver.command(name="listroles") - async def list_allowed_roles(self, ctx: commands.Context): - """List all roles allowed to trigger archiving""" - roles = await self.config.guild(ctx.guild).allowed_roles() - if not roles: - await ctx.send("No roles are currently allowed (all users can trigger archiving)") - return - - role_names = [r.name for r in [ctx.guild.get_role(role_id) for role_id in roles] if r] - await ctx.send(f"Allowed roles: {', '.join(role_names)}") - - @videoarchiver.command(name="setconcurrent") - async def set_concurrent_downloads(self, ctx: commands.Context, count: int): - """Set the number of concurrent downloads (1-5)""" - if not 1 <= count <= 5: - await ctx.send("Concurrent downloads must be between 1 and 5") - return - - await self.config.guild(ctx.guild).concurrent_downloads.set(count) - await ctx.send(f"Concurrent downloads set to {count}") - await self.log_message(ctx.guild, f"Concurrent downloads set to {count}") - await self.initialize_guild_components(ctx.guild.id) - - @videoarchiver.command(name="setchannel") - async def set_archive_channel(self, ctx: commands.Context, channel: discord.TextChannel): - """Set the archive channel""" - await self.config.guild(ctx.guild).archive_channel.set(channel.id) - await ctx.send(f"Archive channel set to {channel.mention}") - await self.log_message(ctx.guild, f"Archive channel set to {channel.name} ({channel.id})") - await self.initialize_guild_components(ctx.guild.id) - - @videoarchiver.command(name="setnotification") - async def set_notification_channel(self, ctx: commands.Context, channel: discord.TextChannel): - """Set the notification channel (where archive messages appear)""" - await self.config.guild(ctx.guild).notification_channel.set(channel.id) - await ctx.send(f"Notification channel set to {channel.mention}") - await self.log_message(ctx.guild, f"Notification channel set to {channel.name} ({channel.id})") - await self.initialize_guild_components(ctx.guild.id) - - @videoarchiver.command(name="setlogchannel") - async def set_log_channel(self, ctx: commands.Context, channel: discord.TextChannel): - """Set the log channel for error messages and notifications""" - await self.config.guild(ctx.guild).log_channel.set(channel.id) - await ctx.send(f"Log channel set to {channel.mention}") - await self.log_message(ctx.guild, f"Log channel set to {channel.name} ({channel.id})") - await self.initialize_guild_components(ctx.guild.id) - - @videoarchiver.command(name="addmonitor") - async def add_monitored_channel(self, ctx: commands.Context, channel: discord.TextChannel): - """Add a channel to monitor for videos""" - async with self.config.guild(ctx.guild).monitored_channels() as channels: - if channel.id not in channels: - channels.append(channel.id) - await ctx.send(f"Now monitoring {channel.mention} for videos") - await self.log_message(ctx.guild, f"Added {channel.name} ({channel.id}) to monitored channels") - await self.initialize_guild_components(ctx.guild.id) - - @videoarchiver.command(name="removemonitor") - async def remove_monitored_channel(self, ctx: commands.Context, channel: discord.TextChannel): - """Remove a channel from monitoring""" - async with self.config.guild(ctx.guild).monitored_channels() as channels: - if channel.id in channels: - channels.remove(channel.id) - await ctx.send(f"Stopped monitoring {channel.mention}") - await self.log_message(ctx.guild, f"Removed {channel.name} ({channel.id}) from monitored channels") - await self.initialize_guild_components(ctx.guild.id) - - @videoarchiver.command(name="setformat") - async def set_video_format(self, ctx: commands.Context, format: str): - """Set the video format (e.g., mp4, webm)""" - await self.config.guild(ctx.guild).video_format.set(format.lower()) - await ctx.send(f"Video format set to {format.lower()}") - await self.log_message(ctx.guild, f"Video format set to {format.lower()}") - await self.initialize_guild_components(ctx.guild.id) - - @videoarchiver.command(name="setquality") - async def set_video_quality(self, ctx: commands.Context, quality: int): - """Set the maximum video quality in pixels (e.g., 1080)""" - await self.config.guild(ctx.guild).video_quality.set(quality) - await ctx.send(f"Maximum video quality set to {quality}p") - await self.log_message(ctx.guild, f"Video quality set to {quality}p") - await self.initialize_guild_components(ctx.guild.id) - - @videoarchiver.command(name="setmaxsize") - async def set_max_file_size(self, ctx: commands.Context, size: int): - """Set the maximum file size in MB""" - await self.config.guild(ctx.guild).max_file_size.set(size) - await ctx.send(f"Maximum file size set to {size}MB") - await self.log_message(ctx.guild, f"Maximum file size set to {size}MB") - await self.initialize_guild_components(ctx.guild.id) - - @videoarchiver.command(name="toggledelete") - async def toggle_delete_after_repost(self, ctx: commands.Context): - """Toggle whether to delete local files after reposting""" - current = await self.config.guild(ctx.guild).delete_after_repost() - await self.config.guild(ctx.guild).delete_after_repost.set(not current) - await ctx.send(f"Delete after repost: {not current}") - await self.log_message(ctx.guild, f"Delete after repost set to: {not current}") - - @videoarchiver.command(name="setduration") - async def set_message_duration(self, ctx: commands.Context, hours: int): - """Set how long to keep archive messages (0 for permanent)""" - await self.config.guild(ctx.guild).message_duration.set(hours) - await ctx.send(f"Archive message duration set to {hours} hours") - await self.log_message(ctx.guild, f"Message duration set to {hours} hours") - await self.initialize_guild_components(ctx.guild.id) - - @videoarchiver.command(name="settemplate") - async def set_message_template(self, ctx: commands.Context, *, template: str): - """Set the archive message template. Use {author}, {url}, and {original_message} as placeholders""" - await self.config.guild(ctx.guild).message_template.set(template) - await ctx.send(f"Archive message template set to:\n{template}") - await self.log_message(ctx.guild, f"Message template updated") - await self.initialize_guild_components(ctx.guild.id) - - @videoarchiver.command(name="enablesites") - async def enable_sites(self, ctx: commands.Context, *sites: str): - """Enable specific sites (leave empty for all sites)""" - sites = [s.lower() for s in sites] - if not sites: - await self.config.guild(ctx.guild).enabled_sites.set([]) - await ctx.send("All sites enabled") - else: - # Verify sites are valid - with yt_dlp.YoutubeDL() as ydl: - valid_sites = set(ie.IE_NAME.lower() for ie in ydl._ies) - invalid_sites = [s for s in sites if s not in valid_sites] - if invalid_sites: - await ctx.send(f"Invalid sites: {', '.join(invalid_sites)}\nValid sites: {', '.join(valid_sites)}") - return - - await self.config.guild(ctx.guild).enabled_sites.set(sites) - await ctx.send(f"Enabled sites: {', '.join(sites)}") - - await self.log_message(ctx.guild, f"Enabled sites updated: {', '.join(sites) if sites else 'All sites'}") - await self.initialize_guild_components(ctx.guild.id) - - @videoarchiver.command(name="listsites") - async def list_sites(self, ctx: commands.Context): - """List all available sites and currently enabled sites""" - settings = await self.config.guild(ctx.guild).all() - enabled_sites = settings["enabled_sites"] - - embed = discord.Embed( - title="Video Sites Configuration", - color=discord.Color.blue() - ) - - with yt_dlp.YoutubeDL() as ydl: - all_sites = sorted(ie.IE_NAME for ie in ydl._ies if ie.IE_NAME is not None) - - # Split sites into chunks for Discord's field value limit - chunk_size = 20 - site_chunks = [all_sites[i:i + chunk_size] for i in range(0, len(all_sites), chunk_size)] - - for i, chunk in enumerate(site_chunks, 1): - embed.add_field( - name=f"Available Sites ({i}/{len(site_chunks)})", - value=", ".join(chunk), - inline=False - ) - - embed.add_field( - name="Currently Enabled", - value=", ".join(enabled_sites) if enabled_sites else "All sites", - inline=False - ) - - await ctx.send(embed=embed) - - async def process_video_url(self, url: str, message: discord.Message) -> bool: - """Process a video URL: download, reupload, and cleanup""" - guild_id = message.guild.id - - # Initialize components if needed - if guild_id not in self.components: - await self.initialize_guild_components(guild_id) - - try: - await message.add_reaction('⏳') - await self.log_message(message.guild, f"Processing video URL: {url}") - - settings = await self.config.guild(message.guild).all() - - # Check user roles - if not self._check_user_roles(message.author, settings['allowed_roles']): - await message.add_reaction('🚫') - return False - - # Download video - success, file_path, error = await self.components[guild_id]['downloader'].download_video(url) - - if not success: - await message.add_reaction('❌') - await self.log_message(message.guild, f"Failed to download video: {error}", "error") - return False - - # Get channels - archive_channel = message.guild.get_channel(settings['archive_channel']) - notification_channel = message.guild.get_channel( - settings['notification_channel'] if settings['notification_channel'] - else settings['archive_channel'] - ) - - if not archive_channel or not notification_channel: - await self.log_message(message.guild, "Required channels not found!", "error") - return False - - try: - # Upload to archive channel - file = discord.File(file_path) - archive_message = await archive_channel.send(file=file) - - # Send notification with information - notification_message = await notification_channel.send( - self.components[guild_id]['message_manager'].format_archive_message( - author=message.author.mention, - url=archive_message.attachments[0].url if archive_message.attachments else "No URL available", - original_message=message.jump_url - ) - ) - - # Schedule notification message deletion if needed - await self.components[guild_id]['message_manager'].schedule_message_deletion( - notification_message.id, - notification_message.delete - ) - - await message.add_reaction('✅') - await self.log_message(message.guild, f"Successfully archived video from {message.author}") - - except discord.HTTPException as e: - await self.log_message(message.guild, f"Failed to upload video: {str(e)}", "error") - await message.add_reaction('❌') - return False - - finally: - # Always attempt to delete the file if configured - if settings['delete_after_repost']: - if secure_delete_file(file_path): - await self.log_message(message.guild, f"Successfully deleted file: {file_path}") - else: - await self.log_message(message.guild, f"Failed to delete file: {file_path}", "error") - # Emergency cleanup - cleanup_downloads(str(self.download_path)) - - return True - - except Exception as e: - await self.log_message(message.guild, f"Error processing video: {str(e)}", "error") - await message.add_reaction('❌') - return False - - @commands.Cog.listener() - async def on_message(self, message: discord.Message): - if message.author.bot or not message.guild: - return - - settings = await self.config.guild(message.guild).all() - - # Check if message is in a monitored channel - if message.channel.id not in settings['monitored_channels']: - return - - # Initialize components if needed - if message.guild.id not in self.components: - await self.initialize_guild_components(message.guild.id) - - # Find all video URLs in message - urls = [] - with yt_dlp.YoutubeDL() as ydl: - for ie in ydl._ies: - if ie._VALID_URL: - urls.extend(re.findall(ie._VALID_URL, message.content)) - - if urls: - # Process multiple URLs concurrently but limited - tasks = [] - semaphore = asyncio.Semaphore(settings['concurrent_downloads']) - - async def process_with_semaphore(url): - async with semaphore: - return await self.process_video_url(url, message) - - for url in urls: - tasks.append(asyncio.create_task(process_with_semaphore(url))) - - # Wait for all downloads to complete - await asyncio.gather(*tasks)