如何停止discord.py后台任务

时间:2020-09-11 01:58:43

标签: discord.py twilio-api

我写了一个discord机器人,它允许用户输入命令$order,该命令继续使用aiohttp库在网站上提交订单。约30分钟后,文本消息被发送到Twilio号码,关键字为“到达”。然后,我想提及/向输入命令的用户发送消息。

到目前为止,我成功轮询“到达”消息的唯一方法是在@tasks.loop()命令中定义$order装饰函数。但是我无法使任务循环停止。我认为停止它的最佳方法是轮询直到我的订单列表为空,然后停止。目前,这就是我要在下面的代码段中实现的。

或者,我想利用分配给Twilio资源的webhooks使用回调。但是,我只能使用Flask应用程序路由Webhook,无法弄清楚如何在订单准备就绪时将其发送给用户。

这是我的清单,尝试在列表为空后停止任务:

order_list = []
@bot.command(description = 'Used to submit an order')
async def order(ctx):
    account, check = await asyncmain.main()  # account is a class that holds the\ twilio client and phone number used to submit order. returns the account object \
and True if requests have been completed as expected
    if check == 1:
        await ctx.author.send('your order has been submitted')
    else:
        await ctx.author.send('your order could not be completed. please message staff or retry')
    
    order_list.append((account, ctx)) # append account and context tuple. allows me to know what user to message when order completed

    if order_list:
        # if order_list not empty, make task to start polling twilio messages
        @tasks.loop(minutes = 10, reconnect = True)
        async def run_loop():
            print('in loop')
            for each in order_list:
                account_to_check, account_ctx = each
                message_list = account_to_check.get_messages()
                for texts in message_list:
                    if 'arriving' in texts.body:
                        await account_ctx.message.author.send('your order ready')
                        order_list.remove((account_to_check, account_ctx)) # remove order from list once order is arriving

        if not order_list:
            print('stopping loop since order_list empty')
            run_loop.stop()
            # in my testing this loop will keep running and printing "stopping loop"
    return None

在此先感谢您的帮助或指导

0 个答案:

没有答案