尝试每小时向频道发送消息

Trying to send message to a channel every hour

我正在尝试创建一个简单的 Discord 机器人,它每小时向一个频道发送一条消息,当我在终端中测试它时它工作正常,每 2 秒打印一次 'test'。但是当我想添加行 'await bot.channel.send('here')' 它只在终端中打印一次 'test' 而在不和谐频道中没有任何内容

import discord,asyncio,os
from discord.ext import commands, tasks


token = 'xxx'
bot = commands.Bot(command_prefix='.')

@bot.event
async  def on_ready():
    change_status.start()
    print('bot in active')

@tasks.loop(seconds=2)
async def change_status():
    channel = bot.get_channel = xxx
    await bot.change_presence(activity=discord.Game('online'))
    print('test')
    await bot.channel.send('here')
bot.run(token)

你犯了以下错误:

channel = bot.get_channel = xxx

问题在于 bot.get_channel 是一个函数。这意味着您实际上需要执行以下操作:

channel = bot.get_channel(xxx)

为什么会出错是因为你没有正确执行bot.get_channel()函数。这样channel的值就变成了xxx。 但是为了向通道发送消息,您需要通道对象。只有正确执行函数才能得到。

如果你这样做了:

channel = bot.get_channel(id)
await channel.send('Your message')

然后 bot.get_channel(id) 返回一个通道对象,您可以将其分配给变量通道。您稍后可以使用它向该频道发送消息。

另外需要注意的是,bot.channel与通道变量不同。所以如果你在频道中有一个频道对象。您不能使用 bot.channel.send() 发送内容。你需要做 channel.send().

阅读文档非常有用: https://discordpy.readthedocs.io/en/latest/api.html?highlight=get_channel#discord.Client.get_channel