You need to enable JavaScript to run this app. discord.py开发消息关键词检测、自动匹配创建文本频道时触发TypeError报错
优惠活动
大模型
产品
解决方案
定价
更多

discord.py开发消息关键词检测、自动匹配创建文本频道时触发TypeError报错

报错定位与修复方案

报错核心根源

代码错误将discord.Guild类本身赋值给全局guild变量,而非实际运行时的服务器实例。此时调用guild.text_channels拿到的是类定义上的property描述符,不是可迭代的频道列表,直接触发TypeError: 'property' object is not iterable报错。

其余逻辑问题

  • 数据源错误:获取频道列表需要从触发关键词的消息所属服务器(即message.guild)拉取,而非全局定义的Guild类
  • 方法语法错误:discord.py创建文本频道的正确方法为create_text_channel(),不存在create.text_channel的链式调用写法
  • 冗余空值风险:代码中channel.id = channel.id语句无实际作用,在频道不存在(channel为None)时会直接触发空值访问异常
  • 逻辑遗漏:频道缺失时,创建完成后没有保存新频道的实例,后续发消息无法定位目标
  • 通知目标偏差:需求要求向#pawel频道发送通知,原代码逻辑是向触发关键词的原消息频道发内容,不符合预期
  • 意图配置缺失:当前discord.py版本默认未开启消息内容读取权限,需要在代码中声明对应intent,同时在Discord开发者门户开启对应开关,否则无法正常读取消息内容

可直接运行的修正代码

import discord
import os

# 声明所需权限
intents = discord.Intents.default()
intents.message_content = True

client = discord.Client()

@client.event
async def on_ready():
    print("We're live!")

pawel_keyword = "pawel"

@client.event
async def on_message(message):
    # 忽略机器人自身发送的消息
    if message.author == client.user:
        return
    # 忽略无关联服务器的私聊消息
    if not message.guild:
        return

    # 匹配关键词(不区分大小写)
    if pawel_keyword in message.content.lower():
        # 从当前服务器查找pawel频道
        target_channel = discord.utils.get(message.guild.text_channels, name="pawel")
        # 频道不存在则自动创建
        if not target_channel:
            target_channel = await message.guild.create_text_channel("pawel")
        # 向目标频道发送通知
        await target_channel.send(f"检测到包含关键词的消息,详情可查看:{message.jump_url}")

client.run(os.getenv('TOKEN'))

注意:运行前需要到Discord开发者门户的机器人设置页,开启MESSAGE CONTENT INTENT权限,否则会因权限限制无法读取消息内容触发报错。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.03 16:24:04