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

Discord机器人启动发消息报错:AttributeError: 'NoneType'无send属性

Discord机器人启动后无法向指定频道发送消息的解决办法

问题场景

想要实现Discord机器人启动后在指定频道发送消息,已确认机器人具备该频道的查看与发言权限,但运行时报错:

Traceback (most recent call last):
  File "/home/runner/GAH-Bot/venv/lib/python3.10/site-packages/discord/client.py", line 409, in _run_event
    await coro(*args, **kwargs)
  File "main.py", line 19, in on_ready
    await channel.send('Hi')
AttributeError: 'NoneType' object has no attribute 'send'

原代码如下:

import discord
from discord.ext import commands
from datetime import datetime

intents = discord.Intents().all()
bot = commands.Bot(command_prefix="!", intents=intents, case_insensitive=True)
client = discord.Client(intents=intents)


@bot.event
async def on_ready():
  print('We have logged in as {0.user}'.format(bot))
  current_time = datetime.now().strftime("%H:%M:%S")
  channel = bot.get_channel('1069075658979954700')
  embed = discord.Embed(title="GAH Verification",
                        description="I have awoken",
                        color=discord.Color.green())
  embed.set_footer(text=current_time)
  await channel.send('Hi')


bot.run(
  "MTA2OTI2NDQ0MTQwMjcyODU3MQ.GV353u.XXagXFsp3Ax4vRxvt3y5s6P9FPPDrOeMh2M7jI")

错误原因

  1. 频道ID类型错误:bot.get_channel()要求传入整数类型的频道ID,原代码中传入的是字符串,导致无法匹配到对应频道,返回None,调用send()时触发AttributeError。
  2. 冗余客户端实例:同时初始化了commands.Bot和discord.Client两个客户端实例,这是不必要的,commands.Bot已经继承自discord.Client,保留一个即可。

修复后的代码

import discord
from discord.ext import commands
from datetime import datetime

intents = discord.Intents().all()
# 只保留commands.Bot实例即可
bot = commands.Bot(command_prefix="!", intents=intents, case_insensitive=True)


@bot.event
async def on_ready():
  print('We have logged in as {0.user}'.format(bot))
  current_time = datetime.now().strftime("%H:%M:%S")
  # 将频道ID改为整数类型
  channel = bot.get_channel(1069075658979954700)
  embed = discord.Embed(title="GAH Verification",
                        description="I have awoken",
                        color=discord.Color.green())
  embed.set_footer(text=current_time)
  # 增加频道存在性判断,避免意外报错
  if channel:
    await channel.send('Hi', embed=embed)
  else:
    print("无法找到指定频道")


bot.run(
  "MTA2OTI2NDQ0MTQwMjcyODU3MQ.GV353u.XXagXFsp3Ax4vRxvt3y5s6P9FPPDrOeMh2M7jI")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 21:25:24