예제 #1
0
def message_actions():
    # Parse the request payload
    payload = json.loads(request.form["payload"])

    selection_item = payload["actions"][0]["name"]

    selection_value = payload["actions"][0]["value"]

    reply_action = MessageManager(payload)
    # get tag using trained model

    if selection_item == "isQuestion":
        if selection_value == "yes":

            question_content = payload["original_message"]["attachments"][0][
                "fallback"]
            # print(question_content)
            tag = prediction_model.get_Question_tags(question_content)
            print(type(tag))
            linklist, titlelist = stackOverFlowApi.get_Frequent_Questions_of_a_tag(
                tag)
            taglist = stackOverFlowApi.get_related_tag(tag)
            message = reply_action.selectIsQuestion(tag, linklist, titlelist,
                                                    taglist)
            response = slack_client.api_call(
                "chat.postMessage",
                **message,
                attachments=reply_action.getSearchingBlock(question_content))

            return ""
        elif selection_value == 'no':
            #reply_is_question = MessageActions(payload)
            message = reply_action.selectIsnotQuestion()
            response = slack_client.api_call("chat.update",
                                             **message,
                                             attachments=[])
            return ""
        else:
            return ""

    if selection_item == "search":
        if selection_value == "yes":
            # reply_is_selection = MessageActions(payload)
            question_content = payload["original_message"]["attachments"][0][
                "fallback"]
            # get search link
            link = stackOverFlowApi.search_question_on_stackoverflow(
                question_content)
            message = reply_action.selectIsSearch(link)
            response = slack_client.api_call("chat.postMessage", **message)
        else:
            response = slack_client.api_call(
                "chat.postMessage",
                channel=payload["channel"]["id"],
                ts=payload["message_ts"],
                text="It's great to help you! :smile:")
            return ""

    return ""
예제 #2
0
    def __init__(self, sourlient):

        AFTNPaths.normalPaths(sourlient.name)
        PXPaths.normalPaths()
        self.sysman = SystemManager()                      # General system manager
        self.sourlient = sourlient                         # Sourlient (Source/Client) object containing configuration infos.

        self.logger = sourlient.logger                     # Logger object
        self.subscriber = sourlient.subscriber             # Determine if it will act like a subscriber or a provider(MHS)
        self.host = sourlient.host                         # Remote host (name or ip)
        self.portR = sourlient.portR                       # Receiving port
        self.portS = sourlient.portS                       # Sending port
        
        self.batch = sourlient.batch                       # Number of files we read in a pass (20)
        self.timeout = sourlient.timeout                   # Timeout time in seconds (default = 10 seconds)
        self.sleepBetweenConnect = int('10')               # Time (in seconds) between connection trials 
        self.slow = sourlient.slow                         # Sleeps are added when we want to be able to decrypt log entries
        self.igniter = None                                # Igniter object (link to pid)

        self.writePath = AFTNPaths.RECEIVED                # Where we write messages we receive
        self.archivePath = AFTNPaths.SENT                  # Where we put sent messages
        self.specialOrdersPath = AFTNPaths.SPECIAL_ORDERS  # Where we put special orders

        # Paths creation
        self.sysman.createDir(PXPaths.TXQ + self.sourlient.name)
        self.sysman.createDir(self.writePath)
        self.sysman.createDir(self.archivePath)
        self.sysman.createDir(self.specialOrdersPath)


        self.mm = MessageManager(self.logger, self.sourlient)  # AFTN Protocol is implemented in MessageManager Object
        self.remoteAddress = None                          # Remote address (where we will connect())
        self.socket = None                                 # Socket object
        self.dataFromFiles = []                            # A list of tuples (content, filename) obtained from a DiskReader 

        self.reader = DiskReader(PXPaths.TXQ + self.sourlient.name, self.sourlient.batch,
                                 self.sourlient.validation, self.sourlient.diskReaderPatternMatching,
                                 self.sourlient.mtime, True, self.logger, eval(self.sourlient.sorter), self.sourlient)
        
        self.debug = True  # Debugging switch
        self.justConnect = False  # Boolean that indicates when a connexion just occur
        
        self.totBytes = 0

        #self.printInitInfos()
        self.makeConnection()
예제 #3
0
    def run(self):
        port = serial.Serial(self.serial_port,
                             baudrate=self.serial_baudrate,
                             timeout=self.serial_timeout,
                             parity=self.serial_parity,
                             stopbits=serial.STOPBITS_TWO,
                             bytesize=serial.SEVENBITS)

        # database creation
        conn = DatabaseConnector.connectSQLiteDB('meshDB.db')

        # MessageManager creation
        self.messageManager = MessageManager(conn)

        # reading loop
        print("Python version detected : " + str(sys.version_info.major))
        while True:
            print("--- Listening...")
            rline = self.readlineCR(port)
            currentDate = datetime.datetime.utcnow()
            try:
                print("Parsing line: " + rline)
                message = self.messageManager.parse_line(currentDate, rline)

                # CSV writing
                #self.df.loc[self.row_iter] =  [datetime.datetime.utcnow(), node_number, sensor_type, float(sensor_value)]
                #self.df.to_csv('./test.csv',index = False)

                # DB writing
                self.messageManager.postMessage(message)

            except ValueError:
                print("ValueError Exception")
                print(str(len(rline)) + " " + rline)
            except Exception as e:
                print("Erreur" + e)
                conn.rollback()
                # raise e

            print("--- Received: " + rline + "\n")

        # closing of the database
        conn.close()
예제 #4
0
    def setUpClass( self ):
        self.msg = MessageManager( 'debug', None ) 
        self.msg.show( "Info! SetUp started", 'info', True )
        #Initialize QGIS app
        app = QgsApplication([], True)
        QgsApplication.setPrefixPath("/usr", True)
        QgsApplication.initQgis()
        
        #Configure QSettings (organization and application name)
        self.settings = QSettings("GeoTux", "QGIS-Plugin-Test") 

        #Load layer, add field f1, and add layer to Registry
        baseDir = os.path.dirname( os.path.realpath( __file__ ) )
        self.layerPath = os.path.join( baseDir, 'test_data', 'test_points.shp' )
        self.layer = QgsVectorLayer( self.layerPath, 'puntos', 'ogr' )   
        self.layer.dataProvider().addAttributes([QgsField('f1', QVariant.Double)])
        self.layer.updateFields()
        QgsMapLayerRegistry.instance().addMapLayer( self.layer )  
        
        #Instantiate AutoFieldManager
        self.autoFieldManager = AutoFieldManager( self.msg, None, '/AutoFieldsTest', 'GeoTux', 'QGIS-Plugin-Test' )
예제 #5
0
from MessageManager import MessageManager
from DatabaseConnector import DatabaseConnector


if  __name__ =='__main__':
    if len(sys.argv) > 1: # /dev/ttyACM0
        A = Server(sys.argv[1])
        A.run()
    else:
        print("Missing serial port pathname")
        
        # database creation
        conn = DatabaseConnector.connectSQLiteDB('meshDB.db')

        # MessageManager creation
        messageManager = MessageManager(conn)

        # DB reading
        messageManager.getAllMessages()

        # CSV writing
        df = messageManager.getAllMessagesintoPandaDataframe()
        df.to_csv('csvFile.csv', index = False)

        # DB update
        newMessage = Message('3', datetime.datetime.utcnow(), '0000', '0000', '0000')
        messageManager.putMessage(newMessage)

        # DB post
        newMessage = Message('4', datetime.datetime.utcnow(), '0000', '0000', '0000')
        messageManager.postMessage(newMessage)
예제 #6
0
import os

from MessageManager import MessageManager
from AdvancedScheduleManager import AdvancedScheduleManager
from redis_manager import RedisManager

with open("./sources/line_bot_token.json", 'r') as f:

    json_data = json.load(f)
    access_token = json_data["access_token"]
    channel_secret = json_data["channel_secret"]

line_bot_api = LineBotApi(access_token)
handler = WebhookHandler(channel_secret)

messageManager = MessageManager(line_bot_api)

# redisManager = RedisManager()

advancedScheduleManager = AdvancedScheduleManager(bot=messageManager)


@csrf_exempt
def callback(request: HttpRequest) -> HttpResponse:

    if request.method == "POST":
        # get X-Line-Signature header value

        signature = request.META['HTTP_X_LINE_SIGNATURE']

        # get request body as text
예제 #7
0
def main(argv):
    print('Kamonohashi Slackbot')

    # KQI実行のための環境変数追加
    if os.name == 'posix':
        # linux: kqiが格納されている場所 (デフォルトの想定場所)
        # 本当は外だしすべき
        kqicli = '/home/(username)/.local/bin'
        os.environ['PATH'] = os.environ['PATH'] + ':' + kqicli

    # 設定ファイルの読込み
    sec = JsonManager(filepath=os.path.join(FLAGS.config_root, 'secure.json'))
    cfg = JsonManager(filepath=os.path.join(FLAGS.config_root, 'config.json'))
    msg = MessageManager(filepath=os.path.join(FLAGS.config_root, 'message.json'), kamonohashi_uri=sec['KAMONOHASHI']['Server'], postmessage_uri=sec['SlackURI'])

    # 監視状態変数
    watch_status = { 
        'dailyjob' : False,
        'watching' : False,
        'waketime' : datetime.now()
    }
    # テナント状態変数
    tenant_status = {
        'count' : {},
        'state' : {}
    }
    tenant_active_job = {}
    # 監視開始
    print('Watch Loop Start')
    while True:
        sec.Load()
        kqi.Login(sec['KAMONOHASHI']['Application']['Username'], sec['KAMONOHASHI']['Application']['Password'])
        tenants = kqi.GetTenantDict()
        print('Daily Loop Start')
        while datetime.now().day == watch_status['waketime'].day:
            # JSONファイルの更新確認
            msg.Load()
            if cfg.Load():
                # 設定ファイルの更新があればテナント情報も再取得する
                tenants = kqi.GetTenantDict()
            # 監視状態更新
            watch_status = UpdateWatchStatus(watch_status, GetWatchCondition(cfg), msg)
            # 監視状態変数のクリア
            tenant_status['count'] = {}
            # 監視状態がアクティブの場合はテナント毎に監視処理を行う
            for tenant in tenants:
                tenant_condition = {}
                if str(tenant) in cfg['Tenant']:
                    tenant_condition = cfg['Tenant'][str(tenant)]
                kqi.SwitchTenant(tenant)
                # 監視状態かどうか
                tenant_status = UpdateTenantTrainStatus(tenant_status, tenant_condition, tenant, tenants, watch_status, msg, kqi)
                tenant_status = UpdateTenantInferStatus(tenant_status, tenant_condition, tenant, tenants, watch_status, msg, kqi)
            # サーバーヘルス監視(特に監視したいのはGPU温度)
            # T.B.D
            # すべての監視対象テナントでしばらくメッセージ送信していない場合は実行中に応じてメッセージを投げる
            if watch_status['watching'] and msg.IsPassedTime(seconds=120 * 60):
                msg.SendMessage(msg.CreateTenantsRunningInfo(tenants, tenant_status['count']))
                msg.UpdateTimestamp()
            # 連続で処理すると負荷がかかるため、指定したポーリング間隔で待機
            time.sleep(cfg['Polling'])
        # 日の処理完了を抜けた場合はリセットする
        watch_status['dailyjob'] = False
        watch_status['waketime'] = datetime.now()
예제 #8
0
  def initGui( self ):

    self.messageManager = MessageManager(self.messageMode, self.iface)

    self.autoFieldManager = AutoFieldManager(self.messageManager, self.iface)
    self.autoFieldManager.readAutoFields()

    ''' if the widget is loaded .... then unlosad'''

    # Get list of all Dockwidgets
    existe = False
    for x in self.iface.mainWindow().findChildren(QDockWidget):
        name = x.objectName()

        if (name == "SeismicRiskDockWidget"):
            existe = True
            #self.iface.removeDockWidget(x)


    if (not existe):
        self.dockWidget = SeismicRiskDockWidget(self.iface.mainWindow(), self.iface, self.autoFieldManager,
                                             self.messageManager, self.language)
        self.iface.addDockWidget(Qt.RightDockWidgetArea, self.dockWidget)

    self.actionDock = QAction(QIcon( ":/plugins/SeismicRisk/icon.png"), \
        "Seismic Risk plugin...", self.iface.mainWindow() )
    self.actionDock.triggered.connect( self.toggleDockWidget )



    # Add custom submenu to Vector menu
    self.iface.addPluginToVectorMenu( "&Seismic Risk ", self.actionDock )


    ''' section pick layers '''

    # icon_path = ':/plugins/pickLayer/icon.png'
    #icon_path = ':/plugins/PruebaAutoFields/icons/info.png'
    #icon_path = os.path.join(self.plugin_dir, "icons", "pickLayer.png")
    icon_path = os.path.join(self.plugin_dir, "icons", "points.png")

    # map tool action
    print " 66 iconpath " + icon_path
    self.mapToolAction = QAction(QIcon(icon_path), "Get seismic risk", self.iface.mainWindow())
    self.mapToolAction.setCheckable(True)


    self.mapTool = IdentifyGeometry(self.mapCanvas)
    self.mapTool.geomIdentified.connect(self.editFeature)

    self.mapTool.setAction(self.mapToolAction)
    self.mapToolAction.triggered.connect(self.setMapTool)
    #self.iface.addToolBarIcon(self.mapToolAction)
    self.iface.addPluginToMenu("&Pick to Layer in autofields", self.mapToolAction)

    '''  fin section pick layers'''
  
    # Remove Redo buttons from menus and toolbars, they can lead to crashes due 
    #   to a corrupted undo stack.
    redoActionList = [action for action in self.iface.advancedDigitizeToolBar().actions() if action.objectName() == u'mActionRedo']
    if redoActionList:
        self.iface.advancedDigitizeToolBar().removeAction( redoActionList[0] )
        self.iface.editMenu().removeAction( redoActionList[0] )    

    QSettings().setValue( "/shortcuts/Redo", "" ) # Override Redo shortcut

    # This block (2 options for disabling the Undo panel) didn't work
    #QSettings().setValue( '/UI/Customization/enabled', True )
    #QSettings( "QGIS", "QGISCUSTOMIZATION2" ).setValue( '/Customization/Panels/Undo', False )
    #undoDock = self.iface.mainWindow().findChild( QDockWidget, u'Undo' )
    #self.iface.removeDockWidget( undoDock )  
  
    # Create action that will start plugin configuration
    #self.action = QAction(QIcon( ":/plugins/AutoFields/icon.png"), "AutoFields plugin...", self.iface.mainWindow() )



    icon_path = os.path.join(self.plugin_dir, "icons", "lines.png")

    print " path " + icon_path

    self.action = QAction(QIcon(icon_path), "Seismic Risk plugin...", self.iface.mainWindow())

    #self.iface.addToolBarIcon(self.action)
    self.iface.addPluginToMenu("&Show seismic Risk Calculator", self.mapToolAction)

    # connect the action to the run method
    self.action.triggered.connect( self.show )

    # Add a custom toolbar
    self.toolbar = self.iface.addToolBar("SeismicRisk")
    self.toolbar.setObjectName("SeismicRisk")
    self.toolbar.addAction(self.action)
    self.toolbar.addAction(self.mapToolAction)

    # Add custom submenu to Vector menu
    self.iface.addPluginToVectorMenu( "&AutoFields for calculating resilience", self.action )
    
    # Add a custom toolbar
    #self.toolbar = self.iface.addToolBar( "SeismicRisk" )
    #self.toolbar.setObjectName("SeismicRisk")
    self.messageManager = MessageManager( self.messageMode, self.iface )
    
    self.autoFieldManager = AutoFieldManager( self.messageManager, self.iface )
    self.autoFieldManager.readAutoFields()

    self.dockWidget = SeismicRiskDockWidget( self.iface.mainWindow(), self.iface, self.autoFieldManager, self.messageManager, self.language )
    self.iface.addDockWidget( Qt.RightDockWidgetArea, self.dockWidget )