Discord Bot登录日志不显示且命令异常问题求助
Discord Bot 在线但无登录日志、命令失效问题修复
核心问题分析
你的Bot出现「在线但无登录日志、大部分命令失效仅私信指令可用」的问题,根源在于代码中的以下错误:
- 重复实例化Bot对象,导致Intents配置未正确绑定到实际运行的Bot实例
on_message事件未调用命令处理器,前缀命令(如!give)无法被识别- Windows日志路径未正确转义,可能导致日志无法写入
- 存在冗余的异常处理代码,且命令中硬编码密钥常量
修复步骤
清理重复Bot实例
删除多余的client = discord.Client(...)和client=commands.Bot(...)代码,只保留一个Bot实例,并将自定义Intents配置应用到该实例。添加命令处理逻辑
在on_message事件的末尾添加await bot.process_commands(message),确保前缀命令能被Bot正常识别处理。修正日志路径
将Windows路径改为双反斜杠或原始字符串,避免转义错误:logging.basicConfig(filename=r'C:\Users\User\OneDrive\Desktop\botlog\bot.log', level=logging.INFO, format='%(asctime)s [%(levelname)s] - %(message)s')移除冗余代码
删除on_message中重复的异常处理块,统一使用定义好的YOUTUBE_API_DEVELOPER_KEY常量,避免硬编码。
完整修正代码
import discord import random import logging from google_auth_oauthlib.flow import InstalledAppFlow from googleapiclient.discovery import build from googleapiclient.errors import HttpError from discord.ext import commands # 修正日志路径(原始字符串避免转义) logging.basicConfig(filename=r'C:\Users\User\OneDrive\Desktop\botlog\bot.log', level=logging.INFO, format='%(asctime)s [%(levelname)s] - %(message)s') # 配置Intents并创建唯一Bot实例 intents = discord.Intents.default() intents.guild_messages = True intents.dm_messages = True intents.message_content = True intents.presences = False intents.typing = False bot = commands.Bot(command_prefix="!", intents=intents) # 配置常量 redirect_uri = 'http://localhost:8080/' DISCORD_BOT_TOKEN = 'TOKEN_HERE' YOUTUBE_CLIENT_ID = 'ID' YOUTUBE_CLIENT_SECRET = 'SECRET' YOUTUBE_API_SERVICE_NAME = 'youtube' YOUTUBE_API_VERSION = 'v3' YOUTUBE_API_DEVELOPER_KEY = 'DEVKEY' BOT_BIO = "we're here for a reason" # YouTube API认证 flow = InstalledAppFlow.from_client_secrets_file( 'client_secrets.json', ['https://www.googleapis.com/auth/youtube.force-ssl']) credentials = flow.run_local_server() youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION, developerKey=YOUTUBE_API_DEVELOPER_KEY) @bot.event async def on_ready(): logging.info(f'Logged in as {bot.user.name} ({bot.user.id})') print(f'Logged in as {bot.user.name} ({bot.user.id})') # 终端也输出登录信息,方便调试 @bot.event async def on_message(message): if message.author == bot.user: return if message.content == "give gdyt": try: logging.info("Received 'give gdyt' command") search_response = youtube.search().list( q="Geometry Dash", type="video", order="relevance", part="id", maxResults=50 ).execute() videos = search_response.get("items") if videos: video = random.choice(videos) video_id = video["id"]["videoId"] youtube_link = f"https://www.youtube.com/watch?v={video_id}" await message.channel.send(youtube_link) logging.info(f"Sent YouTube link: {youtube_link}") else: await message.channel.send("No results found.") logging.info("No YouTube results found.") except HttpError as e: error_message = str(e) logging.error(f"An error occurred while fetching YouTube data: {error_message}") await message.channel.send("An error occurred while fetching YouTube data. Please check the logs for details.") # 必须添加这一行,否则前缀命令无法被处理 await bot.process_commands(message) @bot.command(name="give", description="Get a random YouTube video based on your prompt") async def give_youtube_video(ctx, youtube_prompt: str): try: # 使用定义好的常量,避免硬编码 youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION, developerKey=YOUTUBE_API_DEVELOPER_KEY) search_response = youtube.search().list( q=youtube_prompt, type="video", part="id", maxResults=50 ).execute() videos = search_response.get("items", []) if not videos: await ctx.send("L prompt, no videos.") return video = random.choice(videos) video_id = video["id"]["videoId"] video_url = f"https://www.youtube.com/watch?v={video_id}" await ctx.send(f"Here's your video: {video_url}") logging.info(f"YouTube video sent: {video_url}") except HttpError as e: await ctx.send(f"There was an oopsie while fetching your video. Try again either now or later.") logging.error(f"An error occurred while fetching YouTube data: {str(e)}") bot.run(DISCORD_BOT_TOKEN)
内容的提问来源于stack exchange,提问作者martinhafizi
相关产品推荐
相关产品推荐

