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


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)

当我打印";通道";,我得到了";无";并且程序崩溃,说";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!")

有用链接:

  • discord.ext.tasks.loop-不一致.py文档
  • on_ready事件-不一致.py文档
  • bot.get_guild(id)-不一致.py文档
  • guild.get_channel(id)-不一致.py文档
  • "我不能用不和来获得某个公会。py"-堆栈溢出

最新更新