You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python搭建Discord机器人?运行时第5行报错求助

解决Discord机器人第5行初始化错误

错误原因

Discord.py v2.0及以上版本强制要求初始化discord.Client()时传入intents(意图)参数,用来明确机器人需要访问的事件权限,不传入会直接触发初始化错误。

修正后的代码

import discord
import os

# 初始化默认意图,开启消息内容权限(必须,否则无法读取消息内容)
intents = discord.Intents.default()
intents.message_content = True

# 传入intents创建Client实例
client = discord.Client(intents=intents)

@client.event
async def on_ready():
    print('We have logged in as {0.user}'.format(client))

@client.event
async def on_message(message):
    if message.author == client.user:
        return
    if message.content.startswith('Hello'):
        await message.channel.send('Hello')

# 用os.getenv更安全,环境变量不存在时返回None而非直接崩溃
client.run(os.getenv('token'))

额外注意事项

  • 确保你的Discord机器人在开发者后台中开启了「Message Content Intent」权限,路径:Bot -> Privileged Gateway Intents -> 开启Message Content Intent。
  • 避免使用os.environ['token'],如果环境变量未设置会直接抛出KeyError,全程用os.getenv('token')更稳妥,变量不存在时会返回None,方便排查问题。

内容的提问来源于stack exchange,提问作者Zector Lab

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 21:25:38