discord.py无法执行task.loop命令

时间:2020-08-29 10:18:31

标签: python discord.py

我正在尝试编写一个discord bot,该bot爬网朋友的网站并宣布何时发布新帖子。搜寻器工作正常,但是当我要宣布在特定频道上发布了新帖子时,问题就来了。我尝试通过以下命令在特定频道中发布消息:

@bot.command()
async def test(ctx):
    channel = bot.get_channel(my_channel_id_here)
    await channel.send('hello')

当我运行命令时,消息成功运行。
我希望脚本每隔几分钟循环一次,以检查是否已发布新内容,因此希望将此代码粘贴到代码的@tasks.loop(seconds=45.0)部分中。我尝试了以下操作:

import discord
from discord.ext import tasks, commands
from discord.ext.commands import Bot
import time
import asyncio

bot = commands.Bot(command_prefix='>')

@bot.command()
async def test(ctx):
    channel = bot.get_channel(my_channel_id_here)
    await channel.send('hello')

@tasks.loop(seconds=45.0)
async def website(bot):
    
    print("started")
        
    channel = bot.get_channel(my_channel_id_here)
    await channel.send('hello')

@website.after_loop
async def after_website():
    print('Error has caused the loop to stop!')

website.start(bot)

bot.run('')

运行此命令时,控制台会正确打印出“已启动”,但随后会跳至“错误导致循环停止!”。
我在做什么错了?

1 个答案:

答案 0 :(得分:0)

在开始循环之前检查您的机器人是否准备就绪:

import discord
from discord.ext import tasks, commands
from discord.ext.commands import Bot
import time
import asyncio

bot = commands.Bot(command_prefix='>')


@bot.command()
async def test(ctx):
    channel = bot.get_channel(my_channel_id)
    await channel.send('hello')


@tasks.loop(seconds=45.0)
async def website():
    print("started")
    channel = bot.get_channel(my_channel_id)
    await channel.send('hello')


@website.before_loop
async def before_website():
    await bot.wait_until_ready()


@website.after_loop
async def after_website():
    print('Error has caused the loop to stop!')


website.start()
bot.run("")

Documentation