import discord from discord.ext import commands import asyncio # 設置 intents intents = discord.Intents.default() intents.messages = True intents.guilds = True # 創建 Bot 實例 bot = commands.Bot(command_prefix='!', intents=intents) @bot.event async def on_ready(): print(f'Logged in as {bot.user.name}') print('機器人上線!') # 啟動控制台輸入任務 asyncio.create_task(console_input()) @bot.command() @commands.has_permissions(manage_messages=True) async def clear(ctx, amount: int): if amount <= 0: await ctx.send("請輸入正整數!") return await ctx.channel.purge(limit=amount + 1) # 刪除指定數量的消息 await ctx.send(f'已刪除 {amount} 條消息。', delete_after=5) async def console_input(): while True: try: # 等待控制台輸入 command = await asyncio.get_event_loop().run_in_executor(None, input, "輸入指令: ") command = command.strip().lower() if command == 'test': print("選擇伺服器:") for idx, guild in enumerate(bot.guilds): print(f"{idx + 1}. {guild.name} (ID: {guild.id})") guild_idx = int(input("請輸入伺服器編號: ")) - 1 guild = bot.guilds[guild_idx] print(f"選擇的伺服器: {guild.name}") print("選擇頻道:") for idx, channel in enumerate(guild.text_channels): print(f"{idx + 1}. {channel.name} (ID: {channel.id})") channel_idx = int(input("請輸入頻道編號: ")) - 1 channel = guild.text_channels[channel_idx] print("1. 正常刪除") print("2. 偷偷刪除") choose = input("請輸入功能").strip() if choose == '1': amount = int(input("刪除訊息數量: ")) # 獲取頻道對應的訊息上下文 async for message in channel.history(limit=amount + 1): await message.delete() await channel.send(f'已刪除 {amount} 條消息。', delete_after=5) print(f"已刪除 {amount} 條消息",delete_after=5) elif choose == "2": amount = int(input("刪除訊息數量: ")) # 獲取頻道對應的訊息上下文 async for message in channel.history(limit=amount + 1): await message.delete() await channel.send(f'已刪除 {amount} 條消息。', delete_after=5) print(f"已刪除 {amount} 條消息",delete_after=5) else: print("錯誤選項") continue else: print("錯誤的指令") except Exception as e: print(f"發生錯誤: {e}")