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

2024-10-02 00:37:51 发布

您现在位置:Python中文网/ 问答频道 /正文

如何向特定频道发送消息? 为什么我会犯这个错误?我的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'




Tags: namefromclientasyncdefbot错误channel
2条回答

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)

但是更好的选择是一个包含实例的处理程序类

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

将其移动到命令函数内部,使其在调用命令时获得channel对象

还请注意,自1.0版以来,snowflakes are now ^{} type instead of ^{} 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')

相关问题 更多 >

    热门问题