gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 04:32:57 25 4
gpt4 key购买 nike

我正在尝试在 Cog 中集成一个基本的 aiohttp 网络服务器(使用 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())

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

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

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

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

最佳答案

    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())

谢谢 Patrick Haugh !!

关于python - Discord-py Rewrite - Cog 中的基本 aiohttp 网络服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52336409/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com