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 。

我想我不是以正确的方式做这种混合......

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值