【问题标题】:'NoneType' object has no attribute 'send' - Discord Bot“NoneType”对象没有“发送”属性 - Discord Bot
【发布时间】:2019-12-12 02:28:11
【问题描述】:

当我通过 DM 向我的不和谐机器人提供命令“!say”时,我正在尝试让我的不和谐机器人向我的服务器中的频道发送消息。

我尝试了很多不同的代码,但通常以属性错误“X 对象没有属性 Y”结束

from discord.ext import commands

bot = commands.Bot(command_prefix='!')

@bot.command()
async def say(ctx):
    channel = bot.get_channel('584307345065246725')
    await channel.send(ctx)

当我 DM 机器人时,总是会出现错误消息,期待它发送所需的消息。

【问题讨论】:

  • 您传递给get_channel 的id 应该是一个int,而不是一个字符串。此外,ctx 将是一个调用上下文对象,它不能用作消息的内容。您到底想发送什么?

标签: discord.py


【解决方案1】:

您的代码 sn-p 发生了一件非常简单的事情,需要先对其进行更正,然后它才能执行您尝试执行的操作。

首先,看看API section 对应的Client.get_channel(你正在调用它):

get_channel(id)
Returns a channel with the given ID.

Parameters
id (int) – The ID to search for.

Returns
The returned channel or None if not found.

Return type
Optional[Union[abc.GuildChannel, abc.PrivateChannel]]

因此,当您这样做时:channel = bot.get_channel('584307345065246725'),您传递的参数不正确。根据 API,唯一的参数必须是 int,但您传递的是字符串。只需去掉单引号就可以了。

Protip:在“返回”下,API 声明如果找不到频道,它可以返回 None,这就是发生在你身上的事情,因为你正在传递一个细绳。因此,channel 成为您在错误中看到的 NoneType 对象。因此,当您执行 channel.send... 时,您就会明白这一点。

【讨论】:

    【解决方案2】:

    频道 ID 是一个 int,而不是一个字符串

    @bot.command()
    async def say(ctx):
        channel = bot.get_channel(584307345065246725)
        await channel.send(ctx)
    

    我不太明白为什么你不能这样做:

    from discord.ext import commands
    
    bot = commands.Bot(command_prefix='!')
    
    @bot.command(pass_context=True)
    async def say(ctx):
        await ctx.send(ctx)
    

    但是我可能弄错了你要做什么。

    【讨论】:

      猜你喜欢
      • 2020-10-22
      • 2021-07-10
      • 1970-01-01
      • 2021-11-12
      • 1970-01-01
      • 2022-12-09
      • 2021-08-11
      • 2021-08-19
      • 2021-12-10
      相关资源
      最近更新 更多