WaspInACup commited on
Commit
d5130ce
·
verified ·
1 Parent(s): 5f133ea

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +236 -26
app.py CHANGED
@@ -1,44 +1,254 @@
1
  import os
 
 
2
  import threading
3
  from flask import Flask
4
  import discord
 
5
 
6
  # 1. Setup a tiny web server on port 7860 so Hugging Face keeps the Space awake
7
- app = Flask(__name__)
8
 
9
- @app.route("/")
10
  def home():
11
- return "🤖 Discord Bot is alive and running 24/7!"
12
 
13
  def run_web():
14
- app.run(host="0.0.0.0", port=7860)
 
 
 
 
 
15
 
16
- # 2. Setup your Discord Bot
17
  intents = discord.Intents.default()
18
- intents.message_content = True
19
- client = discord.Client(intents=intents)
20
 
21
- @client.event
22
- async def on_ready():
23
- print(f"Logged in successfully as {client.user}!")
 
24
 
25
- @client.event
26
- async def on_message(message):
27
- if message.author == client.user:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
  return
29
- # Simple test command
30
- if message.content.startswith("!hello"):
31
- await message.channel.send(f"Hello {message.author.mention}! I am running for free in the cloud on Hugging Face!")
32
 
33
- # 3. Run both the web server and the Discord bot simultaneously
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
  if __name__ == "__main__":
35
- # Start the web server in a background thread
36
- web_thread = threading.Thread(target=run_web)
 
 
 
 
37
  web_thread.start()
38
-
39
- # Grab your token securely from Hugging Face Secrets
40
- TOKEN = os.getenv("DISCORD_TOKEN")
41
- if TOKEN:
42
- client.run(TOKEN)
43
- else:
44
- print("ERROR: DISCORD_TOKEN secret was not found!")
 
1
  import os
2
+ import re
3
+ import math
4
  import threading
5
  from flask import Flask
6
  import discord
7
+ from discord import app_commands
8
 
9
  # 1. Setup a tiny web server on port 7860 so Hugging Face keeps the Space awake
10
+ flask_app = Flask(__name__)
11
 
12
+ @flask_app.route("/")
13
  def home():
14
+ return "🤖 HexBot Discord Bot is alive and running 24/7!"
15
 
16
  def run_web():
17
+ flask_app.run(host="0.0.0.0", port=7860)
18
+
19
+
20
+ # 2. Discord Bot Logic (HexBot)
21
+ TOKEN = os.getenv("DISCORD_TOKEN")
22
+ GUILD_ID = os.getenv("GUILD_ID") # Optional for fast sync
23
 
 
24
  intents = discord.Intents.default()
25
+ intents.members = True
 
26
 
27
+ class MyClient(discord.Client):
28
+ def __init__(self):
29
+ super().__init__(intents=intents)
30
+ self.tree = app_commands.CommandTree(self)
31
 
32
+ async def setup_hook(self):
33
+ if GUILD_ID:
34
+ guild = discord.Object(id=int(GUILD_ID))
35
+ self.tree.copy_global_to(guild=guild)
36
+ await self.tree.sync(guild=guild)
37
+ print(f"Synced commands to guild {GUILD_ID}")
38
+ else:
39
+ await self.tree.sync()
40
+ print("Synced global commands (can take up to 1 hour to appear)")
41
+
42
+ client = MyClient()
43
+
44
+ HEX_REGEX = re.compile(r'^#?([0-9A-Fa-f]{6})$')
45
+
46
+ CSS_COLORS = {
47
+ "#f0f8ff": "Alice Blue", "#faebd7": "Antique White", "#00ffff": "Aqua", "#7fffd4": "Aquamarine",
48
+ "#f0ffff": "Azure", "#f5f5dc": "Beige", "#ffe4c4": "Bisque", "#000000": "Black",
49
+ "#ffebcd": "Blanched Almond", "#0000ff": "Blue", "#8a2be2": "Blue Violet", "#a52a2a": "Brown",
50
+ "#deb887": "Burlywood", "#5f9ea0": "Cadet Blue", "#7fff00": "Chartreuse", "#d2691e": "Chocolate",
51
+ "#ff7f50": "Coral", "#6495ed": "Cornflower Blue", "#fff8dc": "Cornsilk", "#dc143c": "Crimson",
52
+ "#00008b": "Dark Blue", "#008b8b": "Dark Cyan", "#a9a9a9": "Dark Gray", "#006400": "Dark Green",
53
+ "#bdb76b": "Dark Khaki", "#8b008b": "Dark Magenta", "#556b2f": "Dark Olive Green", "#ff8c00": "Dark Orange",
54
+ "#9932cc": "Dark Orchid", "#8b0000": "Dark Red", "#e9967a": "Dark Salmon", "#8fbc8f": "Dark Sea Green",
55
+ "#483d8b": "Dark Slate Blue", "#2f4f4f": "Dark Slate Gray", "#00ced1": "Dark Turquoise", "#9400d3": "Dark Violet",
56
+ "#ff1493": "Deep Pink", "#00bfff": "Deep Sky Blue", "#696969": "Dim Gray", "#1e90ff": "Dodger Blue",
57
+ "#b22222": "Fire Brick", "#fffaf0": "Floral White", "#228b22": "Forest Green", "#ff00ff": "Fuchsia",
58
+ "#dcdcdc": "Gainsboro", "#f8f8ff": "Ghost White", "#ffd700": "Gold", "#daa520": "Goldenrod",
59
+ "#808080": "Gray", "#008000": "Green", "#adff2f": "Green Yellow", "#f0fff0": "Honeydew",
60
+ "#ff69b4": "Hot Pink", "#cd5c5c": "Indian Red", "#4b0082": "Indigo", "#fffff0": "Ivory",
61
+ "#f0e68c": "Khaki", "#e6e6fa": "Lavender", "#fff0f5": "Lavender Blush", "#7cfc00": "Lawn Green",
62
+ "#fffacd": "Lemon Chiffon", "#add8e6": "Light Blue", "#f08080": "Light Coral", "#e0ffff": "Light Cyan",
63
+ "#fafad2": "Light Goldenrod Yellow", "#d3d3d3": "Light Gray", "#90ee90": "Light Green", "#ffb6c1": "Light Pink",
64
+ "#ffa07a": "Light Salmon", "#20b2aa": "Light Sea Green", "#87cefa": "Light Sky Blue", "#778899": "Light Slate Gray",
65
+ "#b0c4de": "Light Steel Blue", "#ffffe0": "Light Yellow", "#00ff00": "Lime", "#32cd32": "Lime Green",
66
+ "#faf0e6": "Linen", "#800000": "Maroon", "#66cdaa": "Medium Aquamarine", "#0000cd": "Medium Blue",
67
+ "#ba55d3": "Medium Orchid", "#9370db": "Medium Purple", "#3cb371": "Medium Sea Green", "#7b68ee": "Medium Slate Blue",
68
+ "#00fa9a": "Medium Spring Green", "#48d1cc": "Medium Turquoise", "#c71585": "Medium Violet Red", "#191970": "Midnight Blue",
69
+ "#f5fffa": "Mint Cream", "#ffe4e1": "Misty Rose", "#ffe4b5": "Moccasin", "#ffdead": "Navajo White",
70
+ "#000080": "Navy", "#fdf5e6": "Old Lace", "#808000": "Olive", "#6b8e23": "Olive Drab",
71
+ "#ffa500": "Orange", "#ff4500": "Orange Red", "#da70d6": "Orchid", "#eee8aa": "Pale Goldenrod",
72
+ "#98fb98": "Pale Green", "#afeeee": "Pale Turquoise", "#db7093": "Pale Violet Red", "#ffefd5": "Papaya Whip",
73
+ "#ffdab9": "Peach Puff", "#cd853f": "Peru", "#ffc0cb": "Pink", "#dda0dd": "Plum",
74
+ "#b0e0e6": "Powder Blue", "#800080": "Purple", "#663399": "Rebecca Purple", "#ff0000": "Red",
75
+ "#bc8f8f": "Rosy Brown", "#4169e1": "Royal Blue", "#8b4513": "Saddle Brown", "#fa8072": "Salmon",
76
+ "#f4a460": "Sandy Brown", "#2e8b57": "Sea Green", "#fff5ee": "Seashell", "#a0522d": "Sienna",
77
+ "#c0c0c0": "Silver", "#87ceeb": "Sky Blue", "#6a5acd": "Slate Blue", "#708090": "Slate Gray",
78
+ "#fffafa": "Snow", "#00ff7f": "Spring Green", "#4682b4": "Steel Blue", "#d2b48c": "Tan",
79
+ "#008080": "Teal", "#d8bfd8": "Thistle", "#ff6347": "Tomato", "#40e0d0": "Turquoise",
80
+ "#ee82ee": "Violet", "#f5deb3": "Wheat", "#ffffff": "White", "#f5f5f5": "White Smoke",
81
+ "#ffff00": "Yellow", "#9acd32": "Yellow Green",
82
+ }
83
+
84
+ def hex_to_rgb(hex_code: str) -> tuple[int, int, int]:
85
+ hex_code = hex_code.lstrip("#")
86
+ return tuple(int(hex_code[i:i+2], 16) for i in (0, 2, 4))
87
+
88
+ def get_color_name(requested_hex: str) -> str:
89
+ requested_hex = requested_hex.lower()
90
+ if requested_hex in CSS_COLORS:
91
+ return CSS_COLORS[requested_hex]
92
+ try:
93
+ import webcolors
94
+ try:
95
+ name = webcolors.hex_to_name(requested_hex, spec='css3')
96
+ if requested_hex in CSS_COLORS:
97
+ return CSS_COLORS[requested_hex]
98
+ return name.replace("-", " ").title()
99
+ except ValueError:
100
+ pass
101
+ requested_rgb = webcolors.hex_to_rgb(requested_hex)
102
+ min_dist = None
103
+ closest_name = None
104
+ for hex_val, name in webcolors.CSS3_HEX_TO_NAMES.items():
105
+ r, g, b = webcolors.hex_to_rgb(hex_val)
106
+ dist = (r - requested_rgb.red)**2 + (g - requested_rgb.green)**2 + (b - requested_rgb.blue)**2
107
+ if min_dist is None or dist < min_dist:
108
+ min_dist = dist
109
+ closest_name = name
110
+ if closest_name:
111
+ for h, pretty in CSS_COLORS.items():
112
+ if pretty.lower().replace(" ", "") == closest_name.lower():
113
+ return pretty
114
+ return closest_name.replace("-", " ").title()
115
+ except ImportError:
116
+ pass
117
+
118
+ req_r, req_g, req_b = hex_to_rgb(requested_hex)
119
+ min_dist = None
120
+ closest = None
121
+ for hex_val, name in CSS_COLORS.items():
122
+ r, g, b = hex_to_rgb(hex_val)
123
+ dist = (r - req_r)**2 + (g - req_g)**2 + (b - req_b)**2
124
+ if min_dist is None or dist < min_dist:
125
+ min_dist = dist
126
+ closest = name
127
+ return closest or "Custom Color"
128
+
129
+ def parse_hex_color(hex_code: str) -> tuple[discord.Color, str, str]:
130
+ match = HEX_REGEX.match(hex_code.strip())
131
+ if not match:
132
+ raise ValueError("Invalid hex")
133
+ hex_value = match.group(1)
134
+ normalized = f"#{hex_value.upper()}"
135
+ normalized_lower = f"#{hex_value.lower()}"
136
+ color_int = int(hex_value, 16)
137
+ color_name = get_color_name(normalized_lower)
138
+ return discord.Color(color_int), normalized, color_name
139
+
140
+ @client.tree.command(name="color", description="Create a color role from a hex code - auto-named to the color name")
141
+ @app_commands.describe(hex_code="Hex color code e.g. #FF5733 or FF5733")
142
+ async def color_command(interaction: discord.Interaction, hex_code: str):
143
+ if not interaction.guild:
144
+ await interaction.response.send_message("This command only works in a server!", ephemeral=True)
145
+ return
146
+ await interaction.response.defer(ephemeral=True)
147
+ if not interaction.guild.me.guild_permissions.manage_roles:
148
+ await interaction.followup.send("❌ I need the **Manage Roles** permission.", ephemeral=True)
149
+ return
150
+ try:
151
+ color, normalized_hex, color_name = parse_hex_color(hex_code)
152
+ except ValueError:
153
+ await interaction.followup.send("❌ Invalid hex! Use 6 chars like `#FF5733`", ephemeral=True)
154
  return
 
 
 
155
 
156
+ role_name = color_name
157
+ reused = False
158
+ try:
159
+ target_role = None
160
+ for r in interaction.guild.roles:
161
+ if r.colour.value == color.value and r.colour.value != 0:
162
+ target_role = r
163
+ reused = True
164
+ break
165
+ if not target_role:
166
+ for r in interaction.guild.roles:
167
+ if r.name.lower() == role_name.lower() and r.colour.value != 0:
168
+ target_role = r
169
+ reused = True
170
+ break
171
+ if not target_role:
172
+ target_role = await interaction.guild.create_role(
173
+ name=role_name,
174
+ colour=color,
175
+ reason=f"Color role {normalized_hex} ({color_name}) requested by {interaction.user}"
176
+ )
177
+ reused = False
178
+ try:
179
+ if target_role.position >= interaction.guild.me.top_role.position:
180
+ await target_role.edit(position=interaction.guild.me.top_role.position - 1)
181
+ except:
182
+ pass
183
+
184
+ for role in interaction.user.roles:
185
+ if role.id == target_role.id:
186
+ continue
187
+ if role.name in CSS_COLORS.values() or HEX_REGEX.match(role.name):
188
+ try:
189
+ await interaction.user.remove_roles(role, reason="Switching color role")
190
+ except:
191
+ pass
192
+
193
+ if target_role not in interaction.user.roles:
194
+ await interaction.user.add_roles(target_role, reason=f"User requested {normalized_hex} -> {color_name}")
195
+
196
+ if reused:
197
+ desc = f"Gave you existing **{target_role.mention}** (`{normalized_hex}`) - reusing server role to avoid duplicates."
198
+ title = f"You're now {color_name}! (reused)"
199
+ else:
200
+ desc = f"Created **{target_role.mention}** (`{normalized_hex}`) and gave it to you."
201
+ title = f"You're now {color_name}!"
202
+
203
+ embed = discord.Embed(title=title, description=desc, color=color)
204
+ embed.add_field(name="Color Name", value=f"**{color_name}**", inline=True)
205
+ embed.add_field(name="Hex", value=f"`{normalized_hex}`", inline=True)
206
+ embed.add_field(name="Role", value=target_role.mention, inline=True)
207
+ if reused:
208
+ embed.add_field(name="♻️ Reused", value="This role already existed", inline=True)
209
+ embed.set_footer(text=f"Requested by {interaction.user.display_name}")
210
+
211
+ await interaction.followup.send(embed=embed, ephemeral=True)
212
+ except discord.Forbidden:
213
+ await interaction.followup.send("❌ I can't manage that role. Drag my bot role **above** the color roles in Server Settings > Roles.", ephemeral=True)
214
+ except Exception as e:
215
+ await interaction.followup.send(f"❌ Error: `{e}`", ephemeral=True)
216
+
217
+ @client.tree.command(name="removecolor", description="Remove your color roles")
218
+ async def remove_color_command(interaction: discord.Interaction):
219
+ if not interaction.guild:
220
+ await interaction.response.send_message("Only in servers!", ephemeral=True)
221
+ return
222
+ await interaction.response.defer(ephemeral=True)
223
+ removed = 0
224
+ for role in interaction.user.roles:
225
+ if role.name in CSS_COLORS.values() or HEX_REGEX.match(role.name):
226
+ try:
227
+ await interaction.user.remove_roles(role)
228
+ removed += 1
229
+ except:
230
+ pass
231
+ if removed == 0:
232
+ await interaction.followup.send("You don't have any color roles.", ephemeral=True)
233
+ else:
234
+ await interaction.followup.send(f"Removed {removed} color role(s).", ephemeral=True)
235
+
236
+ @client.event
237
+ async def on_ready():
238
+ print(f"Logged in as {client.user} (ID: {client.user.id})")
239
+ print("HexBot is ready!")
240
+
241
+ # 3. Main Entrypoint: Start Web Server + Bot Client
242
  if __name__ == "__main__":
243
+ if not TOKEN:
244
+ print("ERROR: DISCORD_TOKEN secret was not found!")
245
+ exit(1)
246
+
247
+ # Start Flask web server in a background thread
248
+ web_thread = threading.Thread(target=run_web, daemon=True)
249
  web_thread.start()
250
+ print("Flask web server started on port 7860 for Hugging Face uptime keep-alive.")
251
+
252
+ # Run the Discord bot in the main thread
253
+ print("Starting Discord bot client...")
254
+ client.run(TOKEN)