天天看點

python 異步架構 不能混用同步代碼_python-3.x

我正在制作一個Discord機器人,它在收到Github挂鈎時發送PM。

它使用Discord.py和BottlePy,最後一個在專用線程中運作。 因為兩個架構都有一個阻塞主循環。

在BottlePy回調中,我調用了一些Discord.py異步代碼。

我不知道什麼是Python異步,當與同步代碼混合時,這看起來很複雜......

這是完整的源代碼:

import discord

import bottle

import threading

import asyncio

client = discord.Client()

server = bottle.Bottle()

async def dm_on_github_async(userid,request):

print("Fire Discord dm to "+str(userid))

global client

user = client.get_user(userid)

if (user==None):

abort(500, "User lookup failed");

dm_channel = user.dm_channel

if (dm_channel==None):

dm_channel = await user.create_dm()

if (dm_channel==None):

abort(500, "Fail to create DM channel");

print("DM channel is "+str(asyncio.wait(dm_channel.id)))

await dm_channel.send("There's a Github shot !")

await dm_channel.send(str(request.body))

return

@server.post("/dm_on_github/")

def dm_on_github(userid):

return asyncio.run(dm_on_github_async(userid,bottle.request))

@client.event

async def on_ready():

print('We have logged in as {0.user} '.format(client))

#@client.event

#async def on_message(message):

# if message.author == client.user:

# return

#

# if message.content.startswith('$hello'):

# await message.channel.send('Hello!')

# # This sample was working very well

class HTTPThread(threading.Thread):

def run(self):

global server

server.run(port=8080)

server_thread = HTTPThread()

print("Starting HTTP server")

server_thread.start()

print("Starting Discord client")

client.run('super secret key')

print("Client terminated")

server.close()

print("Asked server to terminate")

server_thread.join()

print("Server thread successful join")

我希望我的Python機器人将HTTP請求的主體作為PM發送。

我得到一個RuntimeError: Timeout context manager should be used inside a task在return asyncio.run(dm_on_github_async(userid,bottle.request)) RuntimeError: Timeout context manager should be used inside a task中RuntimeError: Timeout context manager should be used inside a task 。

我想我不是以正确的方式做這種混合......