如何将消息发送到特定频道?不和谐/ Python

时间:2020-04-02 10:45:01

标签: python discord discord.py

如何将消息发送到特定频道? 为什么会出现此错误?我的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'



2 个答案:

答案 0 :(得分:0)

发生错误的原因是因为在连接机器人之前调用了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')

答案 1 :(得分:-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)

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