python - 开始学习新的 Python 3.5 Asyncio(协程)的好地方 | Discord.py BOT 崩溃

标签 python api python-asyncio coroutine discord

所以,我似乎没有找到任何关于在 python 中使用新的 asyncio 模块(async、await 等)的好的教程。另外,从我看过的所有教程来看,这个概念的描述很差,我似乎无法理解协程的想法。我的意思是,这个概念背后的想法并不难,但是没有一个地方可以让我准确地了解协程可以做什么和不能做什么,以及如何使用它们。

例如,我为目前正在构建的 Discord BOT 编写了一个名为 YouTubeAPI 的小类。 Discord.py 库的所有功能都使用 asyncio,但我的类没有。我的类 (YouTubeAPI) 的唯一目的是从 YouTube Data API V3 检索有关用户发布的最新视频的数据。实际上,我正在尝试构建一个 BOT,让我随时了解某人发布的所有视频。

但是为了让 BOT 正常工作,我需要创建一个 update() 函数来定期获取所有视频,以便我可以获得最新的视频。问题是更新函数需要包装在 while True 循环(或类似的东西)中,以便我可以保持列表最新。如果我构建一个无限循环,那么我将遇到 BOT 问题(使 BOT 崩溃且无法使用)。

所以,我想也许我可以学习新的 asyncio 模块并以这种方式解决问题。遗憾的是我什么也没找到。

下面是一些删除了所有 API key 的代码,以便您可以更轻松地看到我的问题:

from Api_Test import YoutubeAPI
import discord
import asyncio

YoutubeName = 'Vsauce'
GOOGLE_API = 'API KEY'

print('Collecting YouTube Data.')
api = YoutubeAPI(GOOGLE_API, YoutubeName) # create object that will get all info for the name 'Vsauce'
print('YouTube Data collected succesfully.')
print('Starting bot.')

def getLastVideo():
    return api.videosData[0] # api.videosData looks like: [[title, link],[title, link],[title, link],]

client = discord.Client()

@client.event
async def on_ready():
    print('Logged in as')
    print(client.user.name)
    print(client.user.id)
    print('------')
    await client.send_message('Now testing: Last {} videos!'.format(YoutubeName))


#While Loop that keeps the api.videosData up-to-date and runs "await client.send_message('new video: title + ink')" if new video found in the list

client.run('Discord BOT token')

如果这篇文章听起来解释得很模糊,我感到非常抱歉,但我完全不知道如何使用 asyncio 或类似的东西,而且我发现自己几乎找不到关于这个新概念的文档。

最佳答案

您可以使用ensure_future()来运行while循环。 这里,循环在调用 on_ready 时开始,并运行直到机器人关闭

@client.event
async def on_ready():
    print('Logged in as')
    print(client.user.name)
    print(client.user.id)
    print('------')
    await client.send_message('Now testing: Last {} videos!'.format(YoutubeName))

    asyncio.ensure_future(update_data(), client.loop) # Starts the infinite loop when the bot starts

async def update_data():
    while True:
        # Do the things you need to do in this loop
        await asyncio.sleep(1) # sleep for 1 second

client.run('Discord BOT token')

关于python - 开始学习新的 Python 3.5 Asyncio(协程)的好地方 | Discord.py BOT 崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42147092/

相关文章:

python - 目录监控中的看门狗不起作用

python - 如何在 Bokeh 中绘制水平条形图(Python)

Python asyncio子进程连续写入stdin和读取stdout/stderr

python-3.x - 具有多个客户端和无限循环的 Python 异步协议(protocol)行为

python-3.x - 如何确保按给定的顺序处理所有命令(和错误)

python - 如何在 Python 中编写位长度不是 8 的倍数的二进制文件?

python - 如何访问 Python 3 中重新引发的异常?

.net - 实现调试器支持: choice of debugging API

php - 如何使用 Gitlab API(使用 PHP curl)获取 Gitlab 存储库中子目录的内容

ios - GSSendEvent - 注入(inject)触摸事件 iOS