tiger2m

Ek discord bot bnao jisme /create karne se 128gb ram 64 cpu core 528 gb storage ka vps de or /start,/stop,/restart ho or /ssh se vps ka sshx.io link de or vps connect ho jaye or /create-admin add karo ko admin hoga boh apni marji se ram vcpu storage ke sath vps create kar sakta h 24/7 ho

Kodari AI
KodariOct 2 at 4:48 am 1
VPSManagerBot
A Discord bot for VPS management. Users can create a VPS with /create, receiving 128GB RAM, 64 CPU cores, and 528GB storage. Commands include /start, /stop, /restart for server control, and /ssh to generate an sshx.io connection link. Admins (added via /create-admin) can create custom VPS configurations with adjustable RAM, vCPU, and storage. The bot operates 24/7, handling multiple concurrent users with persistent server state tracking.
  • Proxmox API se VPS create aur start/stop/restart commands.

  • Owner-only /create-admin; admins ke liye custom RAM/CPU/storage.

  • /ssh se VM par SSHX session link; setup ke liye .env.example aur dependencies.

Bot project create kar diya.

  • /create default 128 GiB RAM, 64 vCPU, 528 GiB storage wala VPS banata hai. /create-custom par admins custom specs de sakte hain.

  • /create-admin sirf BOT_OWNER_IDS mein configured owner ko admin add karne deta hai.

  • /start, /stop, /restart aur /ssh commands hain. VPS access owner/admin tak limited hai.

  • Files: bot.py, requirements.txt, .env.example, .gitignore.

Zaroori setup: VPS provisioning ke liye apna Proxmox VE server/API token configure karein, jismein requested resources available hon. Template VM mein cloud-init, DHCP, QEMU guest agent, SSH key access aur sshx installed hona chahiye. .env.example ko .env mein copy karke settings bharein, phir dependencies install karke python bot.py chalayein.

24/7 uptime Proxmox host aur bot host ki availability par depend karega; /ssh link bhi bot aur VM ke chalte rehne tak active rahega.

tiger2m

Ye vps proxmox par nhi local node par hoga

Kodari AI
KodariOct 2 at 4:58 am 1
  1. Proxmox provisioning ko local-node virtualization backend se replace karunga.

  2. Commands aur setup config ko local virtualization ke mutabiq update karunga.

Proxmox hata kar bot ko local Linux node ke KVM/libvirt par VPS banane ke liye update kiya hai. /create aur /create-custom local VM banayenge; /start, /stop, /restart aur /ssh bhi usi local node par kaam karenge.

Chalane ke liye local host par KVM/libvirt, virsh, qemu-img aur cloud-localds install karein. .env.example ko .env mein copy karke Discord token, owner ID, cloud image path aur SSH keys set karein. Base image mein cloud-init aur SSH server hona chahiye; SSHX command guest VM mein available honi chahiye. Bot ko libvirt aur VM storage directory ka access bhi dein.

128 GiB RAM, 64 vCPU aur 528 GiB storage tabhi banenge jab local node par itni capacity available ho; bot kam resources hon to VM create nahi karega. 24/7 uptime local host aur bot process ko chalu rakhne par depend karta hai.

tiger2m

<redacted> token h 1320732831424450561 admin user id bot crash kyo hua fix karo

Kodari AI
KodariOct 2 at 5:03 am 1

Startup crash ka likely cause LOCAL_BASE_IMAGE unset hona tha: bot startup par KeyError aa sakta tha. Ab startup missing setting ya image path par clear error deta hai, aur aapka user ID default bot owner set hai. .env.example bhi add kiya hai.

Bot chalane se pehle Discord Developer Portal mein token reset karein—aapne jo token yahan bheja hai, use exposed samjhein. Naya token privately .env mein rakhein; chat ya GitHub par share/commit na karein. .env.example ko .env bana kar LOCAL_BASE_IMAGE ko apne local node ki cloud-init-enabled Linux image ke actual path se replace karein.

Agar iske baad bhi crash aaye, sanitized traceback bhejein—token hata kar.

tiger2m

Local base image tom hi dalo

Kodari AI
KodariOct 2 at 5:07 am 1
  1. Default local image ke liye verified Ubuntu 24.04 cloud image auto-download karunga.

  2. Custom LOCAL_BASE_IMAGE ho to usi path ko use karunga.

bot.py ab first startup par official Ubuntu 24.04 cloud image ko local data/cloud-images/ mein download karke SHA-256 se verify karega. LOCAL_BASE_IMAGE set karna optional hai; custom image path doge to bot wahi use karega.

Image download ke liye pehli baar internet connection chahiye. VM create karne ke liye local node par KVM/libvirt aur cloud-localds phir bhi install hone chahiye.

tiger2m

raise RuntimeError(f"Configured LOCAL_BASE_IMAGE file nahi mili: {self.base_image}") RuntimeError: Configured LOCAL_BASE_IMAGE file nahi mili: /absolute/path/to/cloud-init-enabled-linux-image.img Bot process crashed Bot stopped

Kodari AI
KodariOct 2 at 5:07 am 1
  1. Placeholder LOCAL_BASE_IMAGE path ko unset treat karunga.

  2. Bot phir verified Ubuntu image auto-download karke startup continue karega.

LOCAL_BASE_IMAGE=/absolute/path/to/cloud-init-enabled-linux-image.img placeholder ab unset treat hoga. Bot startup par verified Ubuntu cloud image auto-download karega, isliye is error par crash nahi hoga.

tiger2m

Local node par enough CPU threads nahi hain. Host threads: 17.

Create karne par ye error aa raha h

Kodari AI
KodariOct 2 at 5:12 am 1
  1. Host thread count ko hard limit se hataunga; libvirt vCPU overcommit allow karta hai.

  2. RAM aur disk capacity checks waise hi rahenge. 64 vCPU virtual cores honge—17 host threads par performance guaranteed nahi.

CPU thread limit hata diya—ab 17 host threads par bhi 64 virtual CPUs assign ho sakte hain. RAM aur storage capacity checks abhi bhi apply honge.

Dhyan rahe: 64 vCPU virtual allocation hai, 64 physical cores nahi; load ke hisaab se VPS slow ho sakta hai. Ab /create dobara try karein.

tiger2m

[Errno 2] No such file or directory: 'qemu-img' Ab te error aa raha h

Kodari AI
KodariOct 2 at 5:14 am 1
  1. Missing qemu-img ke liye clear dependency error dunga, taaki command failure samajh aaye.

  2. Local Ubuntu/Debian node par qemu-utils install karke bot restart karein; bot khud host packages install nahi karega.

qemu-img bot ke local node par installed nahi hai. Ubuntu/Debian host par ye command chalayein, phir bot restart karke /create dobara try karein:

Shell
sudo apt update && sudo apt install -y qemu-utils

bot.py ab missing command ko pakad kar actionable error dikhayega. Agar bot container mein chal raha hai, qemu-utils usi container image/environment mein install hona chahiye jahan bot run hota hai.

tiger2m

VPS create nahi hua: qemu-img install nahi hai ya PATH mein nahi mila. Ubuntu/Debian par sudo apt update && sudo apt install -y qemu-utils chalayein, phir bot restart karein. ye error aa raha h plz fix all things is local node no error

Kodari AI
KodariOct 2 at 5:27 am 1

Ye Python code ka error nahi, bot jis environment mein run ho raha hai wahan qemu-img binary maujood nahi. Sirf bot mein error message badalne se VPS create nahi hoga; dependency usi machine/container mein install honi chahiye jahan python bot.py chal raha hai.

Ubuntu/Debian local node par chalayein:

Shell
sudo apt update
sudo apt install -y qemu-utils libvirt-daemon-system libvirt-clients cloud-image-utils
sudo systemctl enable --now libvirtd
sudo usermod -aG libvirt,kvm "$USER"

Phir logout/login karke, bot chalane wale usi environment mein verify karein:

Shell
command -v qemu-img virsh cloud-localds
virsh -c qemu:///system list --all

Agar bot Docker/container mein hai, host par package install karna kaafi nahi—packages container image ke andar chahiye, aur container ko KVM/libvirt access bhi dena hoga. Agar Kodari-hosted bot environment /dev/kvm ya libvirt access nahi deta, to us environment mein local VPS banana mumkin nahi; bot ko apne KVM-enabled Linux node par chalana hoga.

Aapka Discord token chat mein expose hua tha—use Developer Portal se reset karke naya token .env mein rakhein.

Kodari can make mistakes. Review important code before using.
Files
.gitignore
bot.py
requirements.txt
Code
3 455
bot.py
import asyncio
import hashlib
import json
import logging
import os
import re
import shutil
import urllib.request
from pathlib import Path
from xml.sax.saxutils import escape

import discord
import psutil
from discord import app_commands
from discord.ext import commands
from dotenv import load_dotenv

load_dotenv()
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
log = logging.getLogger("kodari-vps-bot")

DATA_DIR = Path(os.getenv("DATA_DIR", "data"))
VPS_FILE = DATA_DIR / "vps.json"
ADMINS_FILE = DATA_DIR / "admins.json"
DEFAULT_RAM_GIB = 128
DEFAULT_VCPU = 64
DEFAULT_STORAGE_GIB = 528
DEFAULT_OWNER_ID = 1320732831424450561
OWNER_IDS = {int(value.strip()) for value in os.getenv("BOT_OWNER_IDS", "").split(",") if value.strip().isdigit()} or {DEFAULT_OWNER_ID}
SSH_LINK_RE = re.compile(r"https://sshx\.io/[^\s\x1b<>]+")
UBUNTU_IMAGE_NAME = "noble-server-cloudimg-amd64.img"
UBUNTU_IMAGE_URL = f"https://cloud-images.ubuntu.com/noble/current/{UBUNTU_IMAGE_NAME}"
UBUNTU_SHA256_URL = "https://cloud-images.ubuntu.com/noble/current/SHA256SUMS"


def read_json(path: Path, fallback):
    try:
        return json.loads(path.read_text(encoding="utf-8"))
    except FileNotFoundError:
        return fallback


def write_json(path: Path, value) -> None:
    DATA_DIR.mkdir(parents=True, exist_ok=True)
    temporary = path.with_suffix(path.suffix + ".tmp")
    temporary.write_text(json.dumps(value, indent=2), encoding="utf-8")
    temporary.replace(path)


class LocalKVM:
    def __init__(self):
        self.uri = os.getenv("LIBVIRT_URI", "qemu:///system")
        base_image = os.getenv("LOCAL_BASE_IMAGE", "").strip()
        if base_image == "/absolute/path/to/cloud-init-enabled-linux-image.img":
            base_image = ""
        self.use_default_image = not base_image
        self.base_image = (
            Path(base_image).expanduser().resolve()
            if base_image
            else (DATA_DIR / "cloud-images" / UBUNTU_IMAGE_NAME).resolve()
        )
        self.vm_dir = Path(os.getenv("LOCAL_VM_DIR", "./vps-data")).expanduser().resolve()
        self.network = os.getenv("LOCAL_NETWORK", "default")
        self.username = os.getenv("SSH_USERNAME", "ubuntu")

    async def ensure_base_image(self) -> None:
        if self.base_image.is_file():
            return
        if not self.use_default_image:
            raise RuntimeError(f"Configured LOCAL_BASE_IMAGE file nahi mili: {self.base_image}")
        log.info("Downloading verified Ubuntu 24.04 cloud image to %s", self.base_image)
        await asyncio.to_thread(self.download_default_image)

    def download_default_image(self) -> None:
        self.base_image.parent.mkdir(parents=True, exist_ok=True)
        with urllib.request.urlopen(UBUNTU_SHA256_URL, timeout=60) as response:
            checksums = response.read().decode("utf-8")
        expected = next(
            (line.split()[0] for line in checksums.splitlines()
             if len(line.split()) >= 2 and line.split()[-1].lstrip("*") == UBUNTU_IMAGE_NAME),
            None,
        )
        if not expected:
            raise RuntimeError("Ubuntu image ke liye SHA256 checksum nahi mila.")

        temporary = self.base_image.with_suffix(self.base_image.suffix + ".part")
        digest = hashlib.sha256()
        try:
            with urllib.request.urlopen(UBUNTU_IMAGE_URL, timeout=60) as response, temporary.open("wb") as image:
                while chunk := response.read(1024 * 1024):
                    digest.update(chunk)
                    image.write(chunk)
            if digest.hexdigest() != expected:
                raise RuntimeError("Downloaded Ubuntu image ka SHA256 checksum match nahi hua.")
            temporary.replace(self.base_image)
        finally:
            temporary.unlink(missing_ok=True)

    async def run(self, *args: str, timeout: int = 120) -> str:
        try:
            process = await asyncio.create_subprocess_exec(
                *args, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE
            )
        except FileNotFoundError as exc:
            if args[0] == "qemu-img":
                raise RuntimeError(
                    "qemu-img install nahi hai ya PATH mein nahi mila. Ubuntu/Debian par "
                    "`sudo apt update && sudo apt install -y qemu-utils` chalayein, "
                    "phir bot restart karein."
                ) from exc
            raise RuntimeError(f"Required command `{args[0]}` install nahi hai ya PATH mein nahi mila.") from exc
        try:
            stdout, stderr = await asyncio.wait_for(process.communicate(), timeout=timeout)
        except TimeoutError:
            process.kill()
            await process.wait()
            raise TimeoutError(f"Command timed out: {args[0]}")
        if process.returncode:
            detail = stderr.decode(errors="replace").strip() or stdout.decode(errors="replace").strip()
            raise RuntimeError(f"{args[0]} failed: {detail[:800]}")
        return stdout.decode(errors="replace").strip()

    async def virsh(self, *args: str, timeout: int = 120) -> str:
        return await self.run("virsh", "-c", self.uri, *args, timeout=timeout)

    def check_capacity(self, ram_gib: int, vcpu: int, storage_gib: int, state: dict) -> None:
        entries = list(state.values())
        used_ram = sum(int(entry.get("ram_gib", 0)) for entry in entries)
        used_storage = sum(int(entry.get("storage_gib", 0)) for entry in entries)
        host_ram_gib = psutil.virtual_memory().total // (1024 ** 3)
        self.vm_dir.mkdir(parents=True, exist_ok=True)
        free_disk_gib = shutil.disk_usage(self.vm_dir).free // (1024 ** 3)

        if used_ram + ram_gib > max(0, host_ram_gib - 2):
            raise RuntimeError(f"Local node par enough RAM nahi hai. Host RAM: {host_ram_gib} GiB; 2 GiB host reserve rakha gaya hai.")
        if used_storage + storage_gib > free_disk_gib:
            raise RuntimeError(f"Local node par requested storage ke liye enough free disk nahi hai ({free_disk_gib} GiB free).")

    async def create_vm(self, vmid: int, name: str, ram_gib: int, vcpu: int, storage_gib: int) -> str:
        if not self.base_image.is_file():
            raise RuntimeError(f"Base cloud image nahi mili: {self.base_image}")
        public_key = os.getenv("SSH_PUBLIC_KEY", "").strip()
        if not public_key:
            raise RuntimeError("VM banane ke liye .env mein SSH_PUBLIC_KEY configure karein.")
        self.vm_dir.mkdir(parents=True, exist_ok=True)
        slug = re.sub(r"[^a-zA-Z0-9_-]+", "-", name).strip("-_").lower()[:24] or "server"
        domain = f"kodari-{vmid}-{slug}"
        disk_path = self.vm_dir / f"{domain}.qcow2"
        seed_path = self.vm_dir / f"{domain}-seed.iso"
        user_data_path = self.vm_dir / f"{domain}-user-data"
        meta_data_path = self.vm_dir / f"{domain}-meta-data"
        xml_path = self.vm_dir / f"{domain}.xml"
        defined = False

        try:
            image_info = json.loads(await self.run("qemu-img", "info", "--output=json", str(self.base_image)))
            await self.run(
                "qemu-img", "create", "-f", "qcow2", "-F", image_info["format"],
                "-b", str(self.base_image), str(disk_path), f"{storage_gib}G",
            )
            user_data_path.write_text(
                "#cloud-config\n"
                f"hostname: {json.dumps(domain)}\n"
                "users:\n  - default\n"
                f"  - name: {json.dumps(self.username)}\n"
                "    groups: [sudo]\n    shell: /bin/bash\n"
                "    sudo: [\"ALL=(ALL) NOPASSWD:ALL\"]\n"
                "    lock_passwd: true\n    ssh_authorized_keys:\n"
                f"      - {json.dumps(public_key)}\n"
                "ssh_pwauth: false\n",
                encoding="utf-8",
            )
            meta_data_path.write_text(
                f"instance-id: kodari-{vmid}\nlocal-hostname: {domain}\n", encoding="utf-8"
            )
            await self.run("cloud-localds", str(seed_path), str(user_data_path), str(meta_data_path))
            self.vm_dir.mkdir(parents=True, exist_ok=True)
            disk_xml = escape(str(disk_path))
            seed_xml = escape(str(seed_path))
            network_xml = escape(self.network)
            xml_path.write_text(
                f"<domain type='kvm'><name>{domain}</name>"
                f"<memory unit='MiB'>{ram_gib * 1024}</memory>"
                f"<currentMemory unit='MiB'>{ram_gib * 1024}</currentMemory>"
                f"<vcpu placement='static'>{vcpu}</vcpu>"
                "<os><type arch='x86_64' machine='q35'>hvm</type><boot dev='hd'/></os>"
                "<features><acpi/><apic/></features><cpu mode='host-passthrough'/>"
                "<devices>"
                f"<disk type='file' device='disk'><driver name='qemu' type='qcow2'/>"
                f"<source file='{disk_xml}'/><target dev='vda' bus='virtio'/></disk>"
                f"<disk type='file' device='cdrom'><driver name='qemu' type='raw'/>"
                f"<source file='{seed_xml}'/><target dev='sda' bus='sata'/><readonly/></disk>"
                f"<interface type='network'><source network='{network_xml}'/><model type='virtio'/></interface>"
                "<graphics type='none'/><console type='pty'><target type='serial' port='0'/></console>"
                "<serial type='pty'><target port='0'/></serial></devices></domain>",
                encoding="utf-8",
            )
            await self.virsh("define", str(xml_path))
            defined = True
            await self.virsh("start", domain)