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

时间:2019-12-22 11:36:33

标签: python discord discord.py discord.py-rewrite

我正在尝试创建一个简单的Discord机器人,该机器人每小时都会向频道发送一条消息,当我在终端中对其进行测试时,它可以正常工作,每2秒打印一次“测试”。但是,当我想添加行'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)

1 个答案:

答案 0 :(得分:0)

您犯了以下错误:

channel = bot.get_channel = xxx

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

channel = bot.get_channel(xxx)

为什么出错是因为您没有正确执行bot.get_channel()函数。因此,通道的值变为xxx。 但是,为了将消息发送到通道,您需要通道对象。您只能通过正确执行函数来获取此信息。

因此,如果您这样做:

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

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

要注意的另一件事是bot.channel与channel变量不同。因此,如果您在channel中有一个channel对象。您不能使用bot.channel.send()发送任何内容。您需要执行channel.send()。

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