-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
59 lines (51 loc) · 2.16 KB
/
main.py
File metadata and controls
59 lines (51 loc) · 2.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import os
import json
import random
import discord
from discord.ext import commands
# --- Load jokes ---
def load_jokes(path: str = "jokes.json"):
try:
with open(path, "r", encoding="utf-8") as f:
jokes = json.load(f)
if not isinstance(jokes, list) or not jokes:
raise ValueError("jokes.json must be a non-empty JSON array of strings.")
return jokes
except Exception as e:
print(f"[ERROR] Failed to load jokes: {e}")
# Fallback to a tiny default list so the bot still runs
return ["I don’t have any jokes yet—but at least I’m self-aware!"]
JOKES = load_jokes()
# --- Bot setup ---
intents = discord.Intents.default()
bot = commands.Bot(command_prefix="!", intents=intents)
# Tip: put your server (guild) ID here for super-fast command sync during development.
# Replace 123456789012345678 with your guild ID, or leave as None for global sync.
GUILD_ID = None # e.g., 123456789012345678
@bot.event
async def on_ready():
try:
if GUILD_ID:
guild = discord.Object(id=GUILD_ID)
bot.tree.copy_global_to(guild=guild)
await bot.tree.sync(guild=guild)
print(f"Synced commands to guild {GUILD_ID}. Logged in as {bot.user}.")
else:
await bot.tree.sync() # global sync (can take up to an hour to appear)
print(f"Synced global commands. Logged in as {bot.user}.")
except Exception as e:
print(f"[ERROR] Sync failed: {e}")
# --- Slash command: /joke ---
@bot.tree.command(name="joke", description="Tell a random joke from my list")
async def joke(interaction: discord.Interaction):
joke_text = random.choice(JOKES)
# Set ephemeral=True if you want only the command invoker to see it
await interaction.response.send_message(f"{joke_text} 🦉", ephemeral=False)
# Optional: category support, e.g., /joke_category category:programming
# If you later change jokes.json to a dict of categories, you can add a second command.
# --- Run bot ---
if __name__ == "__main__":
token = os.getenv("DISCORD_TOKEN")
if not token:
raise RuntimeError("Set DISCORD_TOKEN environment variable.")
bot.run(token)