You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

107 lines
3.3 KiB

import asyncio
import json
import logging
import os
import websockets
from config import Config
from commands import Commands
from extracommands import ExtraCommands
from clients.discord import DiscordClient
from clients.twitch import TwitchClient
TIMEOUT = 0.2
def main():
level = logging.DEBUG if bool(int(os.getenv('DEBUG', 0))) else logging.INFO
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter('CMD: %(levelname)s: %(message)s'))
commands_logger = logging.getLogger('commands')
commands_logger.addHandler(handler)
commands_logger.setLevel(level)
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter('DISCORD: %(levelname)s: %(message)s'))
discord_logger = logging.getLogger('discord')
discord_logger.addHandler(handler)
discord_logger.setLevel(level)
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter('TWITCH: %(levelname)s: %(message)s'))
twitch_logger = logging.getLogger('irc.client')
twitch_logger.addHandler(handler)
twitch_logger.setLevel(level)
config = Config()
config.reload()
commands = Commands(config, commands_logger)
extra_commands = ExtraCommands()
extra_commands.reload()
twitch_client = TwitchClient(config, twitch_logger, commands, extra_commands)
discord_client = DiscordClient(config, discord_logger, commands, extra_commands)
async def monitor_config_files():
while True:
try:
config.reload_if_needed()
except Exception as e:
commands_logger.info('Exception', exc_info=e)
try:
extra_commands.reload_if_needed()
except Exception as e:
commands_logger.info('Exception', exc_info=e)
await asyncio.sleep(TIMEOUT)
async def run_twitch_client():
twitch_client.connect_()
while True:
try:
twitch_client.process_data()
except Exception as e:
twitch_logger.info('Exception', exc_info=e)
await asyncio.sleep(TIMEOUT)
async def run_discord_client():
while True:
try:
await discord_client.start_()
except Exception as e:
discord_logger.info('Exception', exc_info=e)
await discord_client.logout()
async def run_periodic_commands():
interval = config['PeriodicCommands'].getint('interval')
while True:
await asyncio.sleep(interval)
twitch_client.run_periodic_command()
async def monitor_twitch_events():
url = config['TwitchEvents'].get('wss_url')
key = config['TwitchEvents'].get('wss_key')
async with websockets.connect(url, extra_headers={'X-Events-Key': key}) as ws:
while True:
event = json.loads(await ws.recv())
twitch_client.process_twitch_event(event)
loop = asyncio.get_event_loop()
try:
asyncio.ensure_future(monitor_config_files())
asyncio.ensure_future(run_twitch_client())
asyncio.ensure_future(run_discord_client())
asyncio.ensure_future(run_periodic_commands())
asyncio.ensure_future(monitor_twitch_events())
loop.run_forever()
finally:
loop.close()
if __name__ == "__main__":
main()