Skip to content

Instantly share code, notes, and snippets.

@Malarne
Created January 8, 2019 11:07
Show Gist options
  • Save Malarne/73d294344a24726da406c6f254076322 to your computer and use it in GitHub Desktop.
Save Malarne/73d294344a24726da406c6f254076322 to your computer and use it in GitHub Desktop.
from aiohttp import web
import asyncio
from . import __path__
import os
from shutil import copyfile
import discord
class WebTest:
def __init__(self, bot):
self.app = web.Application()
self.bot = bot
self.port = 6969
self.handler = None
self.runner = None
self.site = None
self.div = ""
def __unload(self):
os.remove(__path__[0] + "/temp.html")
self.bot.loop.create_task(self.runner.cleanup())
async def make_webserver(self):
folder = __path__[0]
basic = os.path.join(folder, "index.html")
copyfile(basic, folder + "/temp.html")
async def page(request):
body = open(folder + "/temp.html", "r", encoding="utf-8").read().format(self.div)
return web.Response(text=body, content_type='text/html')
async def talkhandler(request):
data = await request.post()
msg = data['talk']
idchan = data["channel"]
chan = self.bot.get_channel(int(idchan))
if chan is None:
chan = discord.utils.get(self.bot.get_all_members(), id=int(idchan))
try:
await chan.send(msg)
await asyncio.sleep(1)
return
except:
await asyncio.sleep(1)
return
await asyncio.sleep(3)
self.app.router.add_get('/', page)
self.app.router.add_post('/', talkhandler)
self.runner = web.AppRunner(self.app)
await self.runner.setup()
self.handler = self.app.make_handler(debug=True)
self.site = web.TCPSite(self.runner, 'localhost', self.port)
await self.site.start()
print('WebTest started ...')
async def get_message(self, message):
try:
res = f"{message.channel.name}: {message.author.display_name}>> {message.content}"
self.div += "</br>" + res
await self.reloadhtml()
except:
res = f"MP: {message.author.display_name}>> {message.content}"
self.div += "</br>" + res
await self.reloadhtml()
async def reloadhtml(self):
fl = open(__path__[0] + "/index.html", "r", encoding="utf-8")
content = fl.read()
fl.close()
with open(__path__[0] + "/temp.html", "w", encoding="utf-8") as current:
current.write(content.format(self.div))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment