繁体   English   中英

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

[英]discord.py fails to execute tasks.loop command

我正在尝试编写一个不和谐的机器人,它会抓取朋友的网站并在发布新帖子时发出通知。 爬虫工作得很好,但是当我想宣布在特定频道上发布了新帖子时出现了问题。 我尝试通过以下命令在特定频道中宣布消息:

@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('')

当我运行它时,控制台正确打印出“Started”,但随后直接跳转到“错误导致循环停止!”。
我究竟做错了什么?

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

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("")

文档

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM