我真的不想问这个问题,但我遇到了麻烦,当我想尝试在特定频道中发送消息时不断收到错误,这是重要的代码:
channel = client.get_channel(CHANNELID)
@client.event
async def on_message(message):
if message.author.id != BOTID:
await channel.send(f"**{message.author.name}** - {datetime.today().strftime('%Y-%m-%d')} {datetime.today().strftime('%H:%M:%S')} - {message.content}")
await client.process_commands(message)
我得到的错误是
AttributeError: 'NoneType' object has no attribute 'send'
另一个问题,可以让它在不同的服务器上发送吗?
谢谢
答案 0 :(得分:0)
最简单的方法是硬编码公会和频道 ID。像这样:
print(maindf)
A B C
2020-05-04 08:00:00 1.0 10 100
2020-05-04 09:00:00 2.0 20 200
用您选择的 ID 代替 @client.event
async def on_message(message):
if message.author.id != BOTID:
guild = client.get_guild(guildID)
channel = guild.get_channel(channelID)
await channel.send(f"**{message.author.name}** - {datetime.today().strftime('%Y-%m-%d')} {datetime.today().strftime('%H:%M:%S')} - {message.content}")
await client.process_commands(message)
和 guildID
。如果您不知道如何获取 ID:
channelID
答案 1 :(得分:0)
看起来当你定义 channel = client.get_channel(CHANNELID)
时,你的公会缓存没有被填满,因此 get_channel 返回 None。一种选择是像loloToster所说的那样,每次都获得公会和频道。我发现将其设置为 on_ready 更容易:
channel = client.get_channel(CHANNELID) # Will be None originally (I won't write None as if you work with some linters, they will send warnings about 'send' not found in NoneType). Also, get_guild().get_channel() is more efficient as it involves less iteration (although this will only affect u if u have a large number of servers on your bot)
@client.event
async def on_ready():
global channel
channel = client.get_channel(CHANNELID)
@client.event
async def on_message(message):
if message.author != client.user and channel is not None:
await channel.send(f"**{message.author.name}** - {datetime.now().strftime('%Y-%m-%d %H:%M:%S')} - {message.content}")
await client.process_commands(message)
对于您是否可以将其发送到其他服务器的附带问题,当然可以,只需提供另一台服务器中频道的频道 ID 作为 get_channel 的参数
答案 2 :(得分:0)
虽然其他答案都有效且很有见地,但这里有一个更简单的解决方法。
您可以使用 fetch_channel(CHANNELID)
向特定频道发送消息。这是一个 API 调用,因此不存在缓存或其他任何问题。
channel = await client.fetch_channel(CHANNELID)
@client.event
async def on_message(message):
if message.author.id != BOTID:
await channel.send(f"**{message.author.name}** - {datetime.today().strftime('%Y-%m-%d')} {datetime.today().strftime('%H:%M:%S')} - {message.content}")
await client.process_commands(message)