Discord.py 中的异步 REST API

she*_*ale 5 python python-asyncio aiohttp discord.py discord.py-rewrite

我正在寻找一种Discord.py使用 rewrite 分支将 REST API 集成到我的. 我想用它aiohttp来处理请求,但我不确定应该采用哪种方法。例如,目标是向 API 发出 GET 请求,该请求将返回机器人所在的公会列表。或者作为另一个示例,POST 请求将要求机器人将给定消息写入特定通道。总的来说,它是关于从网页向机器人发出指令。

我尝试将 aiohttp 应用路由器和运行器放在我的 Discord.py 客户端类中。Web 服务器确实在运行,我创建了一个异步函数来返回机器人所在的公会,但看起来该函数不会接受我在转到http://127.0.0.1/guilds. 从而导致missing 1 required positional argument错误。

import discord
import asyncio
from aiohttp import web

class MyClient(discord.Client):
    async def on_ready(self):
        print('Logged on as {0}!'.format(self.user))

    async def get_guilds(self, request):
        response_obj = self.guilds
        return web.json_response(response_obj,status=200,content_type='application/json')

    app = web.Application()
    app.router.add_get('/guilds', get_guilds)
    web.run_app(app, port=80)

client = MyClient()
client.run(TOKEN)
Run Code Online (Sandbox Code Playgroud)

此外,aiohttp 服务器不是异步运行的。我希望on_ready(self)运行,但它从来没有。我究竟做错了什么 ?

she*_*ale 3

好吧,我找到了办法。

机器人.py

from asyncio import gather, get_event_loop
from logging import basicConfig, INFO
from discord.ext.commands import Bot
from aiohttp.web import AppRunner, Application, TCPSite
from sys import argv

from api import routes

basicConfig(level=INFO)

async def run_bot():

    app = Application()
    app.add_routes(routes)

    runner = AppRunner(app)
    await runner.setup()
    site = TCPSite(runner, '0.0.0.0', 8080)
    await site.start()

    bot = Bot(command_prefix="$")
    app['bot'] = bot

    try:
        await bot.start(TOKEN)

    except:
        bot.close(),
        raise

    finally:
        await runner.cleanup()

if __name__ == '__main__':
    loop = get_event_loop()
    loop.run_until_complete(run_bot())
Run Code Online (Sandbox Code Playgroud)

api.py

routes = RouteTableDef()

@routes.get('/guilds')
async def get_guilds(request):
    client = request.app['bot']
    guilds = []
    for guild in client.guilds:
        guilds.append(guild.id)

    response = Handler.success(guilds)
    return json_response(response, status=200, content_type='application/json')
Run Code Online (Sandbox Code Playgroud)