如何在任务循环中向特定的不和谐频道发送消息?

How do I send a message to a specific discord channel while in a task loop?

import discord
from discord.ext import commands, tasks
from discord_webhook import DiscordWebhook

client = discord.Client()
bot = commands.Bot(command_prefix="$")

@tasks.loop(seconds=15.0)
async def getAlert():
   #do work here
   channel = bot.get_channel(channel_id_as_int)
   await channel.send("TESTING")

getAlert.start()
bot.run(token)

当我打印“通道”时,我得到“None”并且程序崩溃并显示“AttributeError:'NoneType' 对象没有属性 'send'”。

我猜我是在频道可用之前得到它,但我不确定。任何人都知道我如何才能将消息发送到特定频道?

您的机器人无法立即获取频道,尤其是当它不在机器人的缓存中时。相反,我建议获取服务器 ID,让机器人从 ID 获取服务器,然后从该服务器获取频道。请查看下面修改后的代码。

@tasks.loop(seconds=15.0)
async def getAlert():
   #do work here
   guild = bot.get_guild(server_id_as_int)
   channel = guild.get_channel(channel_id_as_int)
   await channel.send("TESTING")

(编辑:包括评论中的答案,以便其他人可以参考)

您还应确保您的 getAlert.start() 处于 on_ready() 事件中,因为机器人需要启动并进入 discord 才能访问任何公会或频道。

@bot.event
async def on_ready():
   getAlert.start()
   print("Ready!")

有用的链接