Skip to content

Commit

Permalink
Refactored bot so that it now runs in a separate thread. Communicatio…
Browse files Browse the repository at this point in the history
…n happens through a queue.
  • Loading branch information
bernardopires committed Jan 14, 2015
1 parent 9a81d00 commit 27d3ca3
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 12 deletions.
47 changes: 43 additions & 4 deletions bot.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,53 @@
import settings
import threading
import Queue
import socket

from irc import IRCBot, run_bot


class TwitchBot(IRCBot):
chat_logger = None

def __init__(self, conn, chat_logger, *args, **kwargs):
class TwitchBot(IRCBot, threading.Thread):
def __init__(self, conn, chat_logger, command_queue, *args, **kwargs):
super(TwitchBot, self).__init__(conn, *args, **kwargs)

self.chat_logger = chat_logger
self.command_queue = command_queue
self.disconnect = threading.Event()

def run(self):
patterns = self.conn.dispatch_patterns()

while not self.disconnect.is_set():
data = self.conn.get_data()
if not data:
print 'disconnected'
self.conn.close()
self.connect_and_join_channels(self.channels)
continue

self.conn.dispatch_data(data, patterns)

try:
command = self.command_queue.get(False)
self.process_command(command)
except Queue.Empty:
continue

def join(self, timeout=None):
self.conn.close()
self.disconnect.set()
super(TwitchBot, self).join(timeout)

def connect_and_join_channels(self, channels):
if not self.conn.connect():
pass # throw exception

for channel in channels:
self.conn.join(channel)
self.channels = channels

def process_command(command):
pass

def log(self, sender, message, channel):
if sender == settings.IRC['NICK']:
Expand Down
21 changes: 13 additions & 8 deletions main.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import Queue
import settings
import time

from irc import run_bot, IRCConnection
from bot import TwitchBot
Expand All @@ -14,17 +16,20 @@ def main():
settings.DATABASE['NAME'],
settings.DATABASE['USER'],
settings.DATABASE['PASSWORD'])
bot = TwitchBot(conn, logger)
command_queue = Queue.Queue()
bot = TwitchBot(conn, logger, command_queue)
bot.daemon = True

channels = get_top_channels(25)
channels = get_top_channels(20)
bot.connect_and_join_channels(channels)
bot.start()
while True:
if not conn.connect():
try:
time.sleep(1)
except KeyboardInterrupt:
print 'Exiting gracefully...'
bot.join()
break

for channel in channels:
conn.join(channel)

conn.enter_event_loop()

if __name__ == "__main__":
main()

0 comments on commit 27d3ca3

Please sign in to comment.