Spaces:
Runtime error
Runtime error
Download app.py from WaspInACup/hivebot: direct link, hf CLI and curl.
- Browser
- Download file 12.3 kB
-
https://huggingface.co/spaces/WaspInACup/hivebot/resolve/main/app.py
- Command line
-
hf download hf://spaces/WaspInACup/hivebot/app.py
-
curl -L -o app.py https://huggingface.co/spaces/WaspInACup/hivebot/resolve/main/app.py
12.3 kB
| import os | |
| import re | |
| import math | |
| import threading | |
| from flask import Flask | |
| import discord | |
| from discord import app_commands | |
| # Dummy ZeroGPU decorator function to satisfy Hugging Face's free tier checker | |
| try: | |
| import spaces | |
| def dummy_gpu_func(): | |
| pass | |
| except ImportError: | |
| pass | |
| # 1. Setup a tiny web server on port 7860 so Hugging Face keeps the Space awake | |
| flask_app = Flask(__name__) | |
| def home(): | |
| return "🤖 HexBot Discord Bot is alive and running 24/7!" | |
| def run_web(): | |
| flask_app.run(host="0.0.0.0", port=7860) | |
| # 2. Discord Bot Logic (HexBot) | |
| TOKEN = os.getenv("DISCORD_TOKEN") | |
| GUILD_ID = os.getenv("GUILD_ID") # Optional for fast sync | |
| intents = discord.Intents.default() | |
| intents.members = True | |
| class MyClient(discord.Client): | |
| def __init__(self): | |
| super().__init__(intents=intents) | |
| self.tree = app_commands.CommandTree(self) | |
| async def setup_hook(self): | |
| if GUILD_ID: | |
| guild = discord.Object(id=int(GUILD_ID)) | |
| self.tree.copy_global_to(guild=guild) | |
| await self.tree.sync(guild=guild) | |
| print(f"Synced commands to guild {GUILD_ID}") | |
| else: | |
| await self.tree.sync() | |
| print("Synced global commands (can take up to 1 hour to appear)") | |
| client = MyClient() | |
| HEX_REGEX = re.compile(r'^#?([0-9A-Fa-f]{6})$') | |
| CSS_COLORS = { | |
| "#f0f8ff": "Alice Blue", "#faebd7": "Antique White", "#00ffff": "Aqua", "#7fffd4": "Aquamarine", | |
| "#f0ffff": "Azure", "#f5f5dc": "Beige", "#ffe4c4": "Bisque", "#000000": "Black", | |
| "#ffebcd": "Blanched Almond", "#0000ff": "Blue", "#8a2be2": "Blue Violet", "#a52a2a": "Brown", | |
| "#deb887": "Burlywood", "#5f9ea0": "Cadet Blue", "#7fff00": "Chartreuse", "#d2691e": "Chocolate", | |
| "#ff7f50": "Coral", "#6495ed": "Cornflower Blue", "#fff8dc": "Cornsilk", "#dc143c": "Crimson", | |
| "#00008b": "Dark Blue", "#008b8b": "Dark Cyan", "#a9a9a9": "Dark Gray", "#006400": "Dark Green", | |
| "#bdb76b": "Dark Khaki", "#8b008b": "Dark Magenta", "#556b2f": "Dark Olive Green", "#ff8c00": "Dark Orange", | |
| "#9932cc": "Dark Orchid", "#8b0000": "Dark Red", "#e9967a": "Dark Salmon", "#8fbc8f": "Dark Sea Green", | |
| "#483d8b": "Dark Slate Blue", "#2f4f4f": "Dark Slate Gray", "#00ced1": "Dark Turquoise", "#9400d3": "Dark Violet", | |
| "#ff1493": "Deep Pink", "#00bfff": "Deep Sky Blue", "#696969": "Dim Gray", "#1e90ff": "Dodger Blue", | |
| "#b22222": "Fire Brick", "#fffaf0": "Floral White", "#228b22": "Forest Green", "#ff00ff": "Fuchsia", | |
| "#dcdcdc": "Gainsboro", "#f8f8ff": "Ghost White", "#ffd700": "Gold", "#daa520": "Goldenrod", | |
| "#808080": "Gray", "#008000": "Green", "#adff2f": "Green Yellow", "#f0fff0": "Honeydew", | |
| "#ff69b4": "Hot Pink", "#cd5c5c": "Indian Red", "#4b0082": "Indigo", "#fffff0": "Ivory", | |
| "#f0e68c": "Khaki", "#e6e6fa": "Lavender", "#fff0f5": "Lavender Blush", "#7cfc00": "Lawn Green", | |
| "#fffacd": "Lemon Chiffon", "#add8e6": "Light Blue", "#f08080": "Light Coral", "#e0ffff": "Light Cyan", | |
| "#fafad2": "Light Goldenrod Yellow", "#d3d3d3": "Light Gray", "#90ee90": "Light Green", "#ffb6c1": "Light Pink", | |
| "#ffa07a": "Light Salmon", "#20b2aa": "Light Sea Green", "#87cefa": "Light Sky Blue", "#778899": "Light Slate Gray", | |
| "#b0c4de": "Light Steel Blue", "#ffffe0": "Light Yellow", "#00ff00": "Lime", "#32cd32": "Lime Green", | |
| "#faf0e6": "Linen", "#800000": "Maroon", "#66cdaa": "Medium Aquamarine", "#0000cd": "Medium Blue", | |
| "#ba55d3": "Medium Orchid", "#9370db": "Medium Purple", "#3cb371": "Medium Sea Green", "#7b68ee": "Medium Slate Blue", | |
| "#00fa9a": "Medium Spring Green", "#48d1cc": "Medium Turquoise", "#c71585": "Medium Violet Red", "#191970": "Midnight Blue", | |
| "#f5fffa": "Mint Cream", "#ffe4e1": "Misty Rose", "#ffe4b5": "Moccasin", "#ffdead": "Navajo White", | |
| "#000080": "Navy", "#fdf5e6": "Old Lace", "#808000": "Olive", "#6b8e23": "Olive Drab", | |
| "#ffa500": "Orange", "#ff4500": "Orange Red", "#da70d6": "Orchid", "#eee8aa": "Pale Goldenrod", | |
| "#98fb98": "Pale Green", "#afeeee": "Pale Turquoise", "#db7093": "Pale Violet Red", "#ffefd5": "Papaya Whip", | |
| "#ffdab9": "Peach Puff", "#cd853f": "Peru", "#ffc0cb": "Pink", "#dda0dd": "Plum", | |
| "#b0e0e6": "Powder Blue", "#800080": "Purple", "#663399": "Rebecca Purple", "#ff0000": "Red", | |
| "#bc8f8f": "Rosy Brown", "#4169e1": "Royal Blue", "#8b4513": "Saddle Brown", "#fa8072": "Salmon", | |
| "#f4a460": "Sandy Brown", "#2e8b57": "Sea Green", "#fff5ee": "Seashell", "#a0522d": "Sienna", | |
| "#c0c0c0": "Silver", "#87ceeb": "Sky Blue", "#6a5acd": "Slate Blue", "#708090": "Slate Gray", | |
| "#fffafa": "Snow", "#00ff7f": "Spring Green", "#4682b4": "Steel Blue", "#d2b48c": "Tan", | |
| "#008080": "Teal", "#d8bfd8": "Thistle", "#ff6347": "Tomato", "#40e0d0": "Turquoise", | |
| "#ee82ee": "Violet", "#f5deb3": "Wheat", "#ffffff": "White", "#f5f5f5": "White Smoke", | |
| "#ffff00": "Yellow", "#9acd32": "Yellow Green", | |
| } | |
| def hex_to_rgb(hex_code: str) -> tuple[int, int, int]: | |
| hex_code = hex_code.lstrip("#") | |
| return tuple(int(hex_code[i:i+2], 16) for i in (0, 2, 4)) | |
| def get_color_name(requested_hex: str) -> str: | |
| requested_hex = requested_hex.lower() | |
| if requested_hex in CSS_COLORS: | |
| return CSS_COLORS[requested_hex] | |
| try: | |
| import webcolors | |
| try: | |
| name = webcolors.hex_to_name(requested_hex, spec='css3') | |
| if requested_hex in CSS_COLORS: | |
| return CSS_COLORS[requested_hex] | |
| return name.replace("-", " ").title() | |
| except ValueError: | |
| pass | |
| requested_rgb = webcolors.hex_to_rgb(requested_hex) | |
| min_dist = None | |
| closest_name = None | |
| for hex_val, name in webcolors.CSS3_HEX_TO_NAMES.items(): | |
| r, g, b = webcolors.hex_to_rgb(hex_val) | |
| dist = (r - requested_rgb.red)**2 + (g - requested_rgb.green)**2 + (b - requested_rgb.blue)**2 | |
| if min_dist is None or dist < min_dist: | |
| min_dist = dist | |
| closest_name = name | |
| if closest_name: | |
| for h, pretty in CSS_COLORS.items(): | |
| if pretty.lower().replace(" ", "") == closest_name.lower(): | |
| return pretty | |
| return closest_name.replace("-", " ").title() | |
| except ImportError: | |
| pass | |
| req_r, req_g, req_b = hex_to_rgb(requested_hex) | |
| min_dist = None | |
| closest = None | |
| for hex_val, name in CSS_COLORS.items(): | |
| r, g, b = hex_to_rgb(hex_val) | |
| dist = (r - req_r)**2 + (g - req_g)**2 + (b - req_b)**2 | |
| if min_dist is None or dist < min_dist: | |
| min_dist = dist | |
| closest = name | |
| return closest or "Custom Color" | |
| def parse_hex_color(hex_code: str) -> tuple[discord.Color, str, str]: | |
| match = HEX_REGEX.match(hex_code.strip()) | |
| if not match: | |
| raise ValueError("Invalid hex") | |
| hex_value = match.group(1) | |
| normalized = f"#{hex_value.upper()}" | |
| normalized_lower = f"#{hex_value.lower()}" | |
| color_int = int(hex_value, 16) | |
| color_name = get_color_name(normalized_lower) | |
| return discord.Color(color_int), normalized, color_name | |
| async def color_command(interaction: discord.Interaction, hex_code: str): | |
| if not interaction.guild: | |
| await interaction.response.send_message("This command only works in a server!", ephemeral=False) | |
| return | |
| await interaction.response.defer(ephemeral=False) | |
| if not interaction.guild.me.guild_permissions.manage_roles: | |
| await interaction.followup.send("❌ I need the **Manage Roles** permission.", ephemeral=False) | |
| return | |
| try: | |
| color, normalized_hex, color_name = parse_hex_color(hex_code) | |
| except ValueError: | |
| await interaction.followup.send("❌ Invalid hex! Use 6 chars like `#FF5733`", ephemeral=False) | |
| return | |
| role_name = color_name | |
| reused = False | |
| try: | |
| target_role = None | |
| for r in interaction.guild.roles: | |
| if r.colour.value == color.value and r.colour.value != 0: | |
| target_role = r | |
| reused = True | |
| break | |
| if not target_role: | |
| for r in interaction.guild.roles: | |
| if r.name.lower() == role_name.lower() and r.colour.value != 0: | |
| target_role = r | |
| reused = True | |
| break | |
| if not target_role: | |
| target_role = await interaction.guild.create_role( | |
| name=role_name, | |
| colour=color, | |
| reason=f"Color role {normalized_hex} ({color_name}) requested by {interaction.user}" | |
| ) | |
| reused = False | |
| try: | |
| if target_role.position >= interaction.guild.me.top_role.position: | |
| await target_role.edit(position=interaction.guild.me.top_role.position - 1) | |
| except: | |
| pass | |
| for role in interaction.user.roles: | |
| if role.id == target_role.id: | |
| continue | |
| if role.name in CSS_COLORS.values() or HEX_REGEX.match(role.name): | |
| try: | |
| await interaction.user.remove_roles(role, reason="Switching color role") | |
| except: | |
| pass | |
| if target_role not in interaction.user.roles: | |
| await interaction.user.add_roles(target_role, reason=f"User requested {normalized_hex} -> {color_name}") | |
| if reused: | |
| desc = f"Gave you existing **{target_role.mention}** (`{normalized_hex}`) - reusing server role to avoid duplicates." | |
| title = f"You're now {color_name}! (reused)" | |
| else: | |
| desc = f"Created **{target_role.mention}** (`{normalized_hex}`) and gave it to you." | |
| title = f"You're now {color_name}!" | |
| embed = discord.Embed(title=title, description=desc, color=color) | |
| embed.add_field(name="Color Name", value=f"**{color_name}**", inline=True) | |
| embed.add_field(name="Hex", value=f"`{normalized_hex}`", inline=True) | |
| embed.add_field(name="Role", value=target_role.mention, inline=True) | |
| if reused: | |
| embed.add_field(name="♻️ Reused", value="This role already existed", inline=True) | |
| embed.set_footer(text=f"Requested by {interaction.user.display_name}") | |
| await interaction.followup.send(embed=embed, ephemeral=False) | |
| except discord.Forbidden: | |
| await interaction.followup.send("❌ I can't manage that role. Drag my bot role **above** the color roles in Server Settings > Roles.", ephemeral=False) | |
| except Exception as e: | |
| await interaction.followup.send(f"❌ Error: `{e}`", ephemeral=False) | |
| async def remove_color_command(interaction: discord.Interaction): | |
| if not interaction.guild: | |
| await interaction.response.send_message("Only in servers!", ephemeral=False) | |
| return | |
| await interaction.response.defer(ephemeral=False) | |
| removed = 0 | |
| for role in interaction.user.roles: | |
| if role.name in CSS_COLORS.values() or HEX_REGEX.match(role.name): | |
| try: | |
| await interaction.user.remove_roles(role) | |
| removed += 1 | |
| except: | |
| pass | |
| if removed == 0: | |
| await interaction.followup.send("You don't have any color roles.", ephemeral=False) | |
| else: | |
| await interaction.followup.send(f"Removed {removed} color role(s).", ephemeral=False) | |
| async def on_ready(): | |
| print(f"Logged in as {client.user} (ID: {client.user.id})") | |
| print("HexBot is ready!") | |
| # 3. Main Entrypoint: Start Web Server + Bot Client | |
| if __name__ == "__main__": | |
| if not TOKEN: | |
| print("ERROR: DISCORD_TOKEN secret was not found!") | |
| exit(1) | |
| # Start Flask web server in a background thread | |
| web_thread = threading.Thread(target=run_web, daemon=True) | |
| web_thread.start() | |
| print("Flask web server started on port 7860 for Hugging Face uptime keep-alive.") | |
| # Run the Discord bot in the main thread | |
| print("Starting Discord bot client...") | |
| client.run(TOKEN) |