问题描述
我正在尝试将基本的aiohttp Web服务器集成到Cog中(使用discord-py重写)。我对齿轮使用了以下代码:
I am trying to integrate a basic aiohttp webserver in a Cog (using discord-py rewrite). I am using the following code for the cog:
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())
启动机器人后工作正常。
但是如果在机器人运行时重新加载齿轮,则会遇到问题:
It works fine upon starting the bot.But if I reload the cog while the bot is running, I encounter an issue:
我想不出一种简单/优雅的方式来释放和重新绑定齿轮,每次重新加载齿轮。
我很乐意为此提供一些建议。最终目标是拥有支持youtube pubsubhubbub订阅的嵌齿轮。
I cannot think of an simple/elegant way to release and re bind every time the cog is reloaded.
I would love some suggestions on this. The end goal is to have a cog that supports youtube pubsubhubbub subscriptions.
可能只是有一种将基本网络服务器集成到我的机器人中的更好的方法。我可以在启动机器人时使用恶魔(叉子)(例如,我已经有一个使用HTTPServer和BaseHTTPRequestHandler编写的网络服务器,可以处理pubsubhubbub youtube订阅),但是我不知何故决定使用aiohttp将其集成到cog中:)
It might just be that there is a better way to integrate a basic webserver to my bot. I could use a deamon (fork) upon starting the bot for example (I already have a webserver written using HTTPServer with a BaseHTTPRequestHandler that can handle pubsubhubbub youtube subscriptions) but somehow I have my mind set on integrating it in a cog using 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())
感谢!
这篇关于Discord-py重写-Cog中的基本aiohttp Web服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!