【问题标题】:discord.py fails to execute tasks.loop commanddiscord.py 无法执行 tasks.loop 命令
【发布时间】:2020-08-29 18:35:06
【问题描述】:

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

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

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

【问题讨论】:

    标签: python discord.py


    【解决方案1】:

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

    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

    【讨论】:

      猜你喜欢
      • 2020-12-31
      • 2020-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-18
      • 2020-06-19
      • 2016-08-20
      • 2020-03-08
      相关资源
      最近更新 更多