Discord-py Rewrite - Cog 中的基本 aiohttp 网络服务器



我正在尝试将基本的aiohttp网络服务器集成到Cog中(使用discord-py重写)。我正在为齿轮使用以下代码:

from aiohttp import web
import discord
from discord.ext import commands
class Youtube():
def __init__(self, bot):
self.bot = bot
async def webserver(self):
async def handler(request):
return web.Response(text="Hello, world")
app = web.Application()
app.router.add_get('/', handler)
runner = web.AppRunner(app)
await runner.setup()
site = web.TCPSite(runner, '192.168.1.111', 8999)
await self.bot.wait_until_ready()
await site.start()
def setup(bot):
yt = Youtube(bot)
bot.add_cog(yt)
bot.loop.create_task(yt.webserver())

启动机器人后它工作正常。 但是,如果我在机器人运行时重新加载齿轮,则会遇到一个问题:

OSError:尝试在地址上绑定时出现 [Errno 10048] 错误 ('192.168.1.111', 8999):每个套接字地址只有一种用法 (协议/网络地址/端口)通常是允许的

我想不出一种简单/优雅的方式来释放和重新绑定每次重新加载齿轮。
我希望对此有一些建议。最终目标是拥有一个支持youtube pubsubhubbub订阅的齿轮。

可能只是有一种更好的方法可以将基本 Web 服务器集成到我的机器人中。例如,我可以在启动机器人时使用 deamon (fork)(我已经有一个使用 HTTPServer 编写的网络服务器和一个可以处理 pubsubhubbub youtube 订阅的 BaseHTTPRequestHandler),但不知何故,我的想法是使用 aiohttp :) 将其集成到一个齿轮中

from aiohttp import web
import asyncio
import discord 
from discord.ext import commands

class Youtube():

def __init__(self, bot):
self.bot = bot

async def webserver(self):
async def handler(request):
return web.Response(text="Hello, world")

app = web.Application()
app.router.add_get('/', handler)
runner = web.AppRunner(app)
await runner.setup()
self.site = web.TCPSite(runner, '192.168.1.111', 8999)
await self.bot.wait_until_ready()
await self.site.start()

def __unload(self):
asyncio.ensure_future(self.site.stop())

def setup(bot):
yt = Youtube(bot)
bot.add_cog(yt)
bot.loop.create_task(yt.webserver())

谢谢帕特里克·霍!

最新更新