Last active
September 9, 2020 04:16
-
-
Save anshulxyz/437dc88597f661bb8f18570ab4f0d2bc to your computer and use it in GitHub Desktop.
Run HTTP server aiohttp inside of your discord bot to handle HTTP requests. Cog based example.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from aiohttp import web | |
import asyncio | |
import discord | |
from discord.ext import commands | |
class HTTPCog(commands.Cog): | |
def __init__(self, bot): | |
self.bot = bot | |
async def webserver(self): | |
async def handler(request): | |
print("hehe") | |
return web.Response(text="Hello, world") | |
async def post_handler(request): | |
print(await request.json()) | |
return web.Response(text="post request") | |
app = web.Application() | |
app.router.add_get('/', handler) | |
app.router.add_post('/', post_handler) | |
runner = web.AppRunner(app) | |
await runner.setup() | |
self.site = web.TCPSite(runner, '127.0.0.1', 8080) | |
await self.bot.wait_until_ready() | |
await self.site.start() | |
def __unload(self): | |
asyncio.ensure_future(self.site.stop()) | |
def setup(bot): | |
http_cog = HTTPCog(bot) | |
bot.add_cog(http_cog) | |
bot.loop.create_task(http_cog.webserver()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For prior discussion refer to this gist https://gist.github.com/Peppermint777/c8465f9ce8b579a8ca3e78845309b832