問題描述
我正在嘗試在 Cog 中集成一個基本的 aiohttp 網(wǎng)絡服務器(使用 discord-py 重寫).我正在為 cog 使用以下代碼:
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())
它在啟動機器人時工作正常.但是如果我在機器人運行時重新加載 cog,我會遇到一個問題:
It works fine upon starting the bot. But if I reload the cog while the bot is running, I encounter an issue:
OSError: [Errno 10048] 嘗試綁定地址時出錯('192.168.1.111', 8999):每個socket地址只使用一次(協(xié)議/網(wǎng)絡地址/端口)通常是允許的
OSError: [Errno 10048] error while attempting to bind on address ('192.168.1.111', 8999): only one usage of each socket address (protocol/network address/port) is normally permitted
每次重新加載 cog 時,我都想不出一種簡單/優(yōu)雅的方式來釋放和重新綁定.
我很想對此提出一些建議.最終目標是擁有一個支持 youtube pubsubhubbub 訂閱的 cog.
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.
可能只是有一種更好的方法可以將基本的網(wǎng)絡服務器集成到我的機器人中.例如,我可以在啟動機器人時使用一個守護進程(fork)(我已經(jīng)有一個使用 HTTPServer 編寫的網(wǎng)絡服務器和一個可以處理 pubsubhubbub youtube 訂閱的 BaseHTTPRequestHandler),但不知何故,我決定使用 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 Rewrite - Cog 中的基本 aiohttp 網(wǎng)絡服務器的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!