Skip to content

Instantly share code, notes, and snippets.

@bearlikelion
Created April 5, 2019 19:07
Show Gist options
  • Save bearlikelion/e1f53aeb2f731f78ee70eebae723f5a5 to your computer and use it in GitHub Desktop.
Save bearlikelion/e1f53aeb2f731f78ee70eebae723f5a5 to your computer and use it in GitHub Desktop.
bot.py
import time
import logging
import threading
import pymsteams
from django.apps import apps
class Bot:
threadName = "-BOT"
log = logging.getLogger()
BotModel = apps.get_model('chatner', 'Bot')
QueueModel = apps.get_model('chatner', 'Queue')
def getActive(self, bRunning=True):
"""Return list of Bot Models where bRunning
bRunning (bool, optional): Defaults to True. Filter for running
Returns:
[models.Bot[]]: Array of bRunning bot Models
"""
return self.BotModel.objects.filter(isRunning=bRunning)
def getThreads(self):
"""Get threads containing self.threadName
Returns:
[threading.Thread[]]: Array of threads containing self.threadName
"""
threads = []
t = threading.enumerate()
for thread in t:
if thread.name in self.threadName:
threads.append(thread)
return threads
def restart(self, queue):
"""Restart bot for Queue
Args:
queue (models.Queue): Queue's bot to restart
"""
self.log.info('Restarting bot %s' % queue)
_name = '%s-%s%s' % (queue.team, queue.name, self.threadName)
self.stopThread(name=_name)
time.sleep(1) # HACK: Wait for thread to save Running is false
self.startBotForQueue(queue=queue)
def resumeBots(self):
"""Start any bots where isRunning=true
"""
_bots = self.getActive()
for _bot in _bots:
self.log.info('Resuming running bot [%s]' % _bot)
self.startBotForQueue(queue=_bot.queue)
def startBotForQueue(self, queue):
"""Start bot for queue
Args:
queue (models.Queue): Queue to create or start a bot for
"""
# Find bot where queue=queue or create a new bot
_bot, created = self.BotModel.objects.get_or_create(queue=queue)
self.log.info('Starting Bot: %s' % _bot)
# Create a threaded bot
t = threading.Thread(target=self.createBotThread,
name=_bot,
kwargs={
'queue': queue,
'bot': _bot
})
t.start()
def stopThread(self, name):
"""Stop thread by name
Args:
name (string): Name of thread to stop
Returns:
[bool]: if thread was stopped
"""
self.log.info('[%s] Stopping thread' % name)
threads = self.getThreads()
for thread in threads:
if name == thread.name:
thread.exit.set()
return True
return False
def createBotThread(self, queue, bot):
"""Create a new thread for queue bot
Args:
queue (models.Queue): Queue we are creating the bot for
bot (models.Bot): Bot we are creating the thread for
"""
t = threading.currentThread()
t.exit = threading.Event()
# Set bot.isRunning in the database
if not bot.isRunning:
bot.isRunning = True
bot.save()
self.log.info('[%s] is running' % bot)
# Connect to msTeams
msTeams = pymsteams.connectorcard(queue.webhook)
message = 'Sleep: %s' % (queue.sleep)
while not t.exit.is_set():
self.log.info(message)
# msTeams.send()
# TODO: John's bot code to scrape CRM and Post to Teams
t.exit.wait(queue.sleep)
else:
if bot.isRunning is True:
bot.isRunning = False
bot.save()
self.log.info('[%s] has stopped' % bot)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment