
from twitchio.ext import commands

import asyncio
import os

import asyncpg
import dotenv

class Bot(commands.Bot):
	
	def __init__(self, loop = None, **kwargs):
		self.version = "3.0.0-a.1"
		
		loop = loop or asyncio.get_event_loop()
		
		# Credentials
		for credential in ("DATABASE_PASSWORD", "POSTGRES_HOST"):
			setattr(self, credential, os.getenv(credential))
		if not self.POSTGRES_HOST:
			self.POSTGRES_HOST = "localhost"
		self.DATABASE_HOST = self.POSTGRES_HOST
		
		# PostgreSQL database connection
		self.db = self.database = self.database_connection_pool = None
		self.connected_to_database = asyncio.Event()
		self.connected_to_database.set()
		loop.run_until_complete(self.initialize_database())
		
		super().__init__(loop = loop, **kwargs)
	
	async def connect_to_database(self):
		if self.database_connection_pool:
			return
		if self.connected_to_database.is_set():
			self.connected_to_database.clear()
			self.database_connection_pool = await asyncpg.create_pool(user = "harmonbot", 
																		password = self.DATABASE_PASSWORD, 
																		database = "harmonbot", host = self.DATABASE_HOST)
			self.db = self.database = self.database_connection_pool
			self.connected_to_database.set()
		else:
			await self.connected_to_database.wait()
	
	async def initialize_database(self):
		await self.connect_to_database()
		await self.db.execute("CREATE SCHEMA IF NOT EXISTS twitch")
		await self.db.execute(
			"""
			CREATE TABLE IF NOT EXISTS twitch.channels (
				channel		TEXT PRIMARY KEY
			)
			"""
		)
	
	async def event_ready(self):
		print(f"Ready | {self.nick}")

dotenv.load_dotenv()
bot = Bot(irc_token = os.getenv("TWITCH_BOT_ACCOUNT_OAUTH_TOKEN"), 
			client_id = os.getenv("TWITCH_CLIENT_ID"), 
			nick = "harmonbot", prefix = '!', initial_channels = ("harmonbot",))
bot.run()


@@ -144,16 +144,39 @@
  = None,
+ initial_channels = %5B%5D,
  **kwarg
@@ -207,11 +207,11 @@
 0.0-
-a.1
+b.0
 %22%0A%09%09
@@ -253,16 +253,60 @@
 _loop()%0A
+%09%09initial_channels = list(initial_channels)%0A
 %09%09%0A%09%09# C
@@ -783,47 +783,280 @@
 %09%0A%09%09
-super().__init__(loop = loop, **kwargs)
+records = loop.run_until_complete(self.db.fetch(%22SELECT channel FROM twitch.channels%22))%0A%09%09initial_channels.extend(record%5B%22channel%22%5D for record in records)%0A%09%09super().__init__(loop = loop, initial_channels = initial_channels, **kwargs)%0A%09%09# TODO: Handle channel name changes?
 %0A%09%0A%09
@@ -2072,43 +2072,8 @@
  '!'
-, initial_channels = (%22harmonbot%22,)
 )%0Abo

Use database for initial channels