forked from raelga/pybot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
brain.py
90 lines (70 loc) · 2.54 KB
/
brain.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#!/usr/bin/env python
"""
brain.py Wrapper to allow dynamic plug-in architecture in bots.
Author: Rael Garcia <self@rael.io>
Date: 06/2016
Usage: Import the module to a bot.
Tested on: Python 3 / OS X 10.11.5
"""
import os
import time
import importlib
import logging
import threading
# Enable logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
logger = logging.getLogger(__name__)
def memories() :
"""Load python modules from memory folder"""
# Invalidates current cache
importlib.invalidate_caches()
# Path where the modules are stored
memory_path = "memory"
knowledge = list()
# If the folder exists, get the files
if os.path.isdir(memory_path):
memories = os.listdir(memory_path)
else:
logger.warn("%s missing, i'm useless :(" % memory_path)
return knowledge
# For each .py file, get name and load the module
for memory in memories :
if memory.find("__") == -1 and memory.find(".pyc") == -1 :
pypos = memory.find(".py")
memory_name = memory[:pypos]
try:
memory = importlib.import_module(memory_path + "." + memory_name)
knowledge.append(importlib.reload(memory))
except:
logger.error("%s is confusing, skipping" % (memory_name))
return knowledge
import queue
def thougth(working_memory, knowledge, action, input):
"""Thread oriented function, store return value on a queue"""
# Try to execute the 'action' method for each module
try:
response = getattr(knowledge, action)(input)
if response: working_memory.put(response)
except:
logger.warn("%s not know how to %s" % (knowledge.__name__, action))
def process(action, input) :
"""Execute the action on each module"""
thoughts = list()
working_memory = queue.Queue()
for knowledge in memories() :
thought = threading.Thread(target=thougth, args=(working_memory, knowledge, action, input))
thoughts.append(thought)
thought.start()
for thought in thoughts:
thought.join()
output = list()
while not working_memory.empty():
output.append(working_memory.get())
return output
def ears(words) :
"""Call hear action on each module"""
return process("hear", words)
def remember(when, where, who, what) :
"""Store messages somewhere."""
logger.info("%s, %s, %s,\"%s\";" % (when, where, who, what))