【问题标题】:How do I send a message to a specific channel? Discord/Python如何向特定频道发送消息?不和谐/蟒蛇
【发布时间】:2020-07-14 07:33:46
【问题描述】:

如何向特定频道发送消息? 为什么我会收到此错误?我的ChannelID 是对的

代码:

from discord.ext import commands


client = commands.Bot(command_prefix='!')
channel = client.get_channel('693503765059338280')



@client.event
async def on_ready():
    print('Bot wurde gestartet: ' + client.user.name)
#wts        
@client.command()
async def test(ctx,name_schuh,preis,festpreis):
    await channel.send(discord.Object(id='693503765059338280'),"Name:" + name_schuh +"\n Preis: " + preis +"\n Festpreis: " + festpreis)

错误:

raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'send'



【问题讨论】:

    标签: python discord discord.py


    【解决方案1】:

    clientchannel 超出范围。您可以使用global 关键字来进行肮脏的黑客攻击:

    from discord.ext import commands
    
    client = commands.Bot(command_prefix='!')
    channel = client.get_channel(693503765059338280)
    
    @client.event
    async def on_ready():
        global client
        print('Bot wurde gestartet: ' + client.user.name)
    
    #wts        
    @client.command()
    async def test(ctx,name_schuh,preis,festpreis):
        global client
        global channel
        await channel.send(discord.Object(id=693503765059338280),"Name:" + name_schuh +"\n Preis: " + preis +"\n Festpreis: " + festpreis)
    

    但更好的选择是保存实例的处理程序类。

    【讨论】:

    • 行不通。 channel = client.get_channel() 在上面的代码中返回None
    • 仍将返回None,因为它在机器人连接之前被调用。它看不到任何频道,因此get_channel 将始终返回None
    【解决方案2】:

    错误的原因是因为在机器人连接之前调用了channel = client.get_channel(),这意味着它将始终返回None,因为它看不到任何通道(未连接)。

    将其移至命令函数内部,使其在调用命令时获取channel 对象。

    另请注意,从 1.0 版开始,snowflakes are now int type instead of str type。这意味着您需要使用client.get_channel(693503765059338280) 而不是client.get_channel('693503765059338280')

    from discord.ext import commands
    
    
    client = commands.Bot(command_prefix='!')
    
    
    @client.event
    async def on_ready():
        print('Bot wurde gestartet: ' + client.user.name)
    
    @client.command()
    async def test(ctx,name_schuh,preis,festpreis):
        channel = client.get_channel(693503765059338280)
        await channel.send("Name:" + name_schuh +"\n Preis: " + preis +"\n Festpreis: " + festpreis)
    
    client.run('token')
    

    【讨论】:

      猜你喜欢
      • 2019-04-11
      • 2020-11-06
      • 2018-12-09
      • 2021-01-01
      • 2021-05-08
      • 2021-01-19
      • 2021-08-09
      • 2021-06-22
      相关资源
      最近更新 更多