Discordbot database setup inital/partial

This commit is contained in:
Jeremy Zhang 2017-05-03 22:16:49 -07:00
parent 1e1a3ab43e
commit 7762862623
5 changed files with 92 additions and 25 deletions

View File

@ -1,2 +1,3 @@
discord.py discord.py
sqlalchemy-aio sqlalchemy
asyncio_extras

View File

@ -1,4 +1,11 @@
from titanembeds.bot import client from titanembeds import Titan
from config import config import gc
client.run(config["bot-token"]) def main():
print("Starting...")
te = Titan()
te.run()
gc.collect()
if __name__ == '__main__':
main()

View File

@ -0,0 +1 @@
from titanembeds.bot import Titan

View File

@ -1,17 +1,57 @@
from config import config from config import config
from titanembeds.database import DatabaseInterface
import discord import discord
import aiohttp
import asyncio
client = discord.Client() class Titan(discord.Client):
def __init__(self):
super().__init__()
self.aiosession = aiohttp.ClientSession(loop=self.loop)
self.http.user_agent += ' TitanEmbeds-Bot'
self.database = DatabaseInterface(self)
@client.event def _cleanup(self):
async def on_ready(): try:
print('Titan -- DiscordBot') self.loop.run_until_complete(self.logout())
print('Logged in as the following user:') except: # Can be ignored
print(client.user.name) pass
print(client.user.id) pending = asyncio.Task.all_tasks()
print('------') gathered = asyncio.gather(*pending)
await test() try:
gathered.cancel()
self.loop.run_until_complete(gathered)
gathered.exception()
except: # Can be ignored
pass
async def test(): def run(self):
from titanembeds.database import db, Guilds, session try:
session.query(Guilds).all() self.loop.run_until_complete(self.start(config["bot-token"]))
except discord.errors.LoginFailure:
print("Invalid bot token in config!")
finally:
try:
self._cleanup()
except Exception as e:
print("Error in cleanup:", e)
self.loop.close()
async def on_ready(self):
print('Titan [DiscordBot]')
print('Logged in as the following user:')
print(self.user.name)
print(self.user.id)
print('------')
await self.change_presence(
game=discord.Game(name="Get your own @ https://TitanEmbeds.tk/"), status=discord.Status.online
)
try:
await self.database.connect(config["database-uri"])
except Exception:
self.logger.error("Unable to connect to specified database!")
traceback.print_exc()
await self.logout()
return

View File

@ -1,17 +1,35 @@
from config import config from contextlib import contextmanager
from sqlalchemy_aio import ASYNCIO_STRATEGY from asyncio_extras import threadpool
import sqlalchemy as db import sqlalchemy as db
from sqlalchemy.engine import Engine, create_engine
from sqlalchemy.orm import sessionmaker, Session
from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base() Base = declarative_base()
from .guilds import Guilds from titanembeds.database.guilds import Guilds
engine = db.create_engine(config["database-uri"]) class DatabaseInterface(object):
# Courtesy of https://github.com/SunDwarf/Jokusoramame
def __init__(self, bot):
self.bot = bot
Base.metadata.create_all(engine) self.engine = None # type: Engine
self._sessionmaker = None # type: sessionmaker
from sqlalchemy.orm import sessionmaker async def connect(self, dburi):
DBSession = sessionmaker() async with threadpool():
DBSession.bind = engine self.engine = create_engine(dburi)
session = DBSession() self._sessionmaker = sessionmaker(bind=self.engine, expire_on_commit=False)
@contextmanager
def get_session(self) -> Session:
session = self._sessionmaker() # type: Session
try:
yield session
session.commit()
except:
session.rollback()
raise
finally:
session.close()