Asyncio并等待问题(Discord bot)

时间:2018-06-22 15:25:02

标签: python

好吧,所以,我为我的机器人做了一个相对较小的功能,可以从API发布消息,直到该API的过程完成并且从一种类型的JSON代码更改为另一种类型(即,显示不同的东西)< / p>

请给我以下内容:RuntimeWarning: coroutine 'discord_status_request' was never awaited

代码如下:

@client.command(name='addip')
async def discord_add_ip(ip):
    monitors.add(ip)
    await client.say('Added IP: {}'.format(ip))
    print(monitors)
    if len(monitors) < 2:
        discord_status_request()
        print('Initiating monitoring process.')


#@asyncio.coroutine
async def discord_status_request():
    global old_response
    global enablemonitoring
    for i in monitors:
        if enablemonitoring == True:
            while True:
                loop_break = False
                response = requests.get(url_input.format(i)).json()
                status_text = str("-" + "\n" + "Start year: " + str(response['start_year'])) + \
                              str('\n' + 'Start time: ' + str(
                              response['start_time'])) + \
                              str('\n' + 'Percentage: ' + str(response['percent'])) + \
                              str('\n' + 'Current year: ' + str(
                              response['current_year'])) + \
                              str('\n' + 'Scheme №: ' + str(
                              response['scheme_number'])) + \
                              str('\n' + 'Stop year: ' + str(response['stop_year']))
                new_response = response.get('percent')
                if new_response == old_response:
                    print('Comparison: nothing new.')
                    time.sleep(10)
                else:
                    old_response = new_response
                    print('Comparison success!')
                    try:
                        client.say(status_text)
                    except KeyError:
                        client.say("Finished calculating. :white_check_mark:")
                        if len(monitors) == 0:
                            loop_break = True
                        monitors.remove(i)
                print('Taking a break.')
                time.sleep(10)
                if loop_break:
                    break

我已经查找了错误,并发现了以下内容:https://xinhuang.github.io/posts/2017-07-31-common-mistakes-using-python3-asyncio.html

所以我添加了这个:

task = loop.create_task(discord_status_request())
loop.run_until_complete(task)  #(I imported AbstractEventLoop as loop)

但是,您猜到了,create_task需要coro,run_until_complete需要将来。我需要科罗和未来。那这些到底是什么?无法理解。

1 个答案:

答案 0 :(得分:0)

这将根据您所运行的python版本而改变。

但是如果您要使用@ asyncio.coroutine 那么您只需使用async关键字即可

@asyncio.coroutine
def discord_status_request():
   yield from function()

您还将使用关键字的收益率,因此您可能希望使用async.coroutine查找收益率

否则,您应该这样做

async def discord_status_request():
   await function() 

这是从python 3.5开始的方式

异步def在语法上将一个函数定义为协程,尽管它不能包含任何形式的yield表达式;只允许return和await从协程返回值。

我认为这就是你的要求