Skip to content

Instantly share code, notes, and snippets.

@anshulxyz
Last active September 9, 2020 04:16
Show Gist options
  • Save anshulxyz/437dc88597f661bb8f18570ab4f0d2bc to your computer and use it in GitHub Desktop.
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.
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())
@anshulxyz
Copy link
Author

anshulxyz commented Aug 26, 2020

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment