add 初版程式碼
This commit is contained in:
@@ -0,0 +1,75 @@
|
||||
"""
|
||||
Discord Bot - 主程式
|
||||
開發者:唐宋
|
||||
"""
|
||||
import os
|
||||
import discord
|
||||
from discord.ext import commands
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# 載入環境變數
|
||||
load_dotenv()
|
||||
|
||||
# 設定 bot token
|
||||
TOKEN = os.getenv('DISCORD_BOT_TOKEN')
|
||||
|
||||
# 設定 bot
|
||||
intents = discord.Intents.default()
|
||||
intents.message_content = True
|
||||
intents.guilds = True
|
||||
|
||||
bot = commands.Bot(command_prefix='!', intents=intents)
|
||||
|
||||
# 機器人啟動時執行
|
||||
@bot.event
|
||||
async def on_ready():
|
||||
print(f'✅ {bot.user.name} 已上線!')
|
||||
print(f'📝 機器人 ID: {bot.user.id}')
|
||||
print(f'🌐 連接到的伺服器數量: {len(bot.guilds)}')
|
||||
|
||||
await bot.change_presence(activity=discord.Activity(
|
||||
type=discord.ActivityType.watching,
|
||||
name='等待指令'
|
||||
))
|
||||
|
||||
# 載入 Cog
|
||||
try:
|
||||
await bot.load_extension("cogs.base") # 使用標準 load_extension
|
||||
await bot.load_extension("cogs.lottery") # 例如你剛剛的 Lottery Cog
|
||||
print('✅ Cogs 已載入')
|
||||
except Exception as e:
|
||||
print(f'❌ 載入 Cogs 時發生錯誤: {e}')
|
||||
|
||||
# 同步 Slash Commands 到指定伺服器
|
||||
try:
|
||||
guild = discord.Object(id=605678541530726421)
|
||||
synced = await bot.tree.sync(guild=guild)
|
||||
print(f'✅ 已同步 {len(synced)} 個 Slash Commands 到伺服器 {guild.id}')
|
||||
for cmd in synced:
|
||||
print(f' /{cmd.name} - {cmd.description}')
|
||||
except Exception as e:
|
||||
print(f'❌ 同步 Slash Commands 時發生錯誤: {e}')
|
||||
|
||||
# 歡迎訊息
|
||||
@bot.event
|
||||
async def on_member_join(member):
|
||||
"""當新成員加入伺服器時"""
|
||||
await member.send(f'👋 歡迎加入 {member.guild.name}!')
|
||||
print(f'✨ 新成員加入: {member.name}')
|
||||
|
||||
# 錯誤處理
|
||||
@bot.event
|
||||
async def on_command_error(ctx, error):
|
||||
"""處理指令錯誤"""
|
||||
if isinstance(error, commands.CommandNotFound):
|
||||
await ctx.send('❌ 請輸入正確的指令!使用 `!help` 查看所有指令。')
|
||||
else:
|
||||
print(f'❌ 發生錯誤: {error}')
|
||||
|
||||
# 啟動機器人
|
||||
if __name__ == '__main__':
|
||||
if not TOKEN:
|
||||
print('❌ 錯誤:未找到 DISCORD_BOT_TOKEN')
|
||||
print('請確保 .env 檔案已正確設定!')
|
||||
else:
|
||||
bot.run(TOKEN)
|
||||
Reference in New Issue
Block a user