首页 > 解决方案 > 尝试每小时向频道发送消息

问题描述

我正在尝试创建一个简单的 Discord 机器人,它每小时向频道发送一条消息,当我在终端中对其进行测试时,它工作正常,每 2 秒打印一次“测试”。但是当我想添加'await bot.channel.send('here')'行时,它只在终端打印'test'一次,而在discord频道中什么也没有

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)

标签: pythondiscorddiscord.pydiscord.py-rewrite

解决方案


您正在做以下错误:

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 与 channel 变量不同。因此,如果您在通道中有一个通道对象。您不能使用 bot.channel.send() 发送内容。你需要做channel.send()。

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


推荐阅读