コード例 #1
0
ファイル: index.py プロジェクト: 7keys/netcall-python-server
 def post(self, *args, **kwargs):
     inputdata = tornado.escape.json_decode(self.request.body)
     data = Mydb.add_history(inputdata['fromuser'], inputdata['touser'], inputdata['htype'])
     if data:
         self.write(Message.say(Message.ok))
     else:
         self.write(Message.say(Message.error))
コード例 #2
0
ファイル: server_socket.py プロジェクト: aeftimia/hexchat
    def send_disconnect_error(self, key, from_aliases, to_alias, message=False):

        '''called when a connection times out'''

        (local_address, remote_address) = (key[0], key[2])
        packet = format_header(
            local_address, remote_address, ElementTree.Element("disconnect_error")
            )
        packet.attrib['xmlns']="hexchat:disconnect_error"
        packet = self.master.add_aliases(packet, from_aliases)
        logging.debug(
            "%s:%d" % local_address + \
            " sending disconnect_error request to %s:%d" % remote_address
            )

        if message:
            msg = Message()
            msg['type'] = 'chat'
        else:
            msg = Iq()
            msg['type'] = 'set'

        msg['to'] = to_alias
        msg.append(packet)

        self.master.send(msg, from_aliases, now=True)
コード例 #3
0
ファイル: marketprices.py プロジェクト: mementum/bfplusplus
    def OnGetMarketPrices(self, event):
        message, response, exception = self.SplitEventResponse(event)

        if not response:
            if exception:
                self.LogMessages(exception)
            return

        marketComp = self.marketCache[message.marketTuple]
        compPerc = float(self.m_sliderCompensate.GetValue()) / 100.0
        ticksAway = 0 if not self.compTicksAway else self.compTicksAwayCount
        marketComp.updateMarketPrices(response.marketPrices, compPerc, self.compIndex,
                                      ticksAway=ticksAway)

        if self.bfModulesActive or self.recordModule or self.excelModActive:
            clone = marketComp.clone()
            if self.recordModule:
                self.recordModule.passMessage(clone)
            for bfModule in self.bfModules.itervalues():
                bfModule.passMessage(clone)
            if self.excelModActive and not self.excelModPaused:
                excelMsg = Message(marketComp=clone)
                excelMsg.workbooks = self.workbooks
                excelMsg.sheets = self.sheets
                self.excelModule.passMessage(excelMsg)

        self.UpdateMarket(message.marketTuple)
        self.UpdateMarketPrices(message.marketTuple)
        self.UpdateMarketProfitAndLoss(message.marketTuple)
        self.UpdateMUBetsCompensations(message.marketTuple)
        self.StopBetCheck()
コード例 #4
0
ファイル: excel.py プロジェクト: mementum/bfplusplus
    def OnButtonClickExcelPlay(self, event):
        event.Skip()

        self.LoadExcelModule()
        if self.excelModule is None:
            return

        if not self.excelModActive:
            self.excelModCell = self.m_textCtrlExcelCell.GetValue()
            self.m_textCtrlExcelCell.Enable(False)

            message = Message(subAction='setActiveCell')
            message.cell = self.excelModCell
            self.excelModule.passMessage(message)

            self.m_bpButtonExcelStop.Enable(True)
            self.m_bpButtonExcelUpdateWorkbooks.Enable(False)
            self.excelModActive = True

        else: # pause mode
            pass

        self.excelModPaused = False
        self.m_bpButtonExcelPlay.Enable(False)
        self.m_bpButtonExcelPause.Enable(True)
        self.excelModule.play()
コード例 #5
0
ファイル: login.py プロジェクト: mementum/bfplusplus
    def OnButtonClickLogin(self, event):
        event.Skip()
        self.blockLogin.Show(True)

        username = self.m_comboBoxUsername.GetValue()
        password = self.m_textCtrlPassword.GetValue()

        if self.useFreeApi:
            productId = bfpy.freeApiId
        else:
            try:
                productId = int(self.m_textCtrlProductId.GetValue())
            except ValueError:
                wx.MessageBox('Wrong Product Id.', 'Login cannot proceed!')
                return

        self.productId = productId

        message = Message(action='login')
        message.username = username
        message.password = password
        message.productId = productId
        message.vendorSoftwareId = self.vendorSoftwareId

        self.thMisc.passMessage(message)
コード例 #6
0
ファイル: threadmodule.py プロジェクト: mementum/bfplusplus
 def modMessage(self, subAction, **kwargs):
     message = Message(action='module', subAction=subAction)
     message.exception = None
     message.response = Message()
     for name, value in kwargs.iteritems():
         setattr(message.response, name, value)
     self.sendMessage(message, self.pyEventId)
コード例 #7
0
ファイル: threadmodule.py プロジェクト: mementum/bfplusplus
 def getAccountFunds(self, exchangeId):
     message = Message(action='module', subAction='getAccountFunds')
     message.exception = None
     message.response = Message()
     message.response.exchangeId = exchangeId
     message.response.modId = self.modId
     self.sendMessage(message, self.pyEventId)
コード例 #8
0
ファイル: server_socket.py プロジェクト: aeftimia/hexchat
    def send_disconnect_error(self,
                              key,
                              from_aliases,
                              to_alias,
                              message=False):
        '''called when a connection times out'''

        (local_address, remote_address) = (key[0], key[2])
        packet = format_header(local_address, remote_address,
                               ElementTree.Element("disconnect_error"))
        packet.attrib['xmlns'] = "hexchat:disconnect_error"
        packet = self.master.add_aliases(packet, from_aliases)
        logging.debug(
            "%s:%d" % local_address + \
            " sending disconnect_error request to %s:%d" % remote_address
            )

        if message:
            msg = Message()
            msg['type'] = 'chat'
        else:
            msg = Iq()
            msg['type'] = 'set'

        msg['to'] = to_alias
        msg.append(packet)

        self.master.send(msg, from_aliases, now=True)
コード例 #9
0
ファイル: index.py プロジェクト: 7keys/netcall-python-server
 def post(self, username):
     pic = self.request.body
     data = Mydb.addHeadpic(username, pic)
     if (data):
         self.write(Message.say(Message.ok))
     else:
         self.write(Message.say(Message.error))
コード例 #10
0
ファイル: placebet.py プロジェクト: mementum/bfplusplus
    def PlaceBets(self, marketTuple, placeBets, modId=None, fillOrKill=None, fillOrKillTime=None):
        message = Message(action='placeBets', marketTuple=marketTuple, placeBets=placeBets, modId=modId)
        message.fillOrKill = self.fillOrKill if fillOrKill is None else fillOrKill
        message.fillOrKillTime = self.fillOrKillTime if not fillOrKillTime else fillOrKillTime

        self.thMisc.passMessage(message)

        marketComp = self.marketCache[marketTuple]
        placeBetMessages = list()
        for placeBet in placeBets:
            placeBetStr = 'PlaceBet: MktId %d / Runner: %s / Persistence: %s / Type: %s / Price %.2f / Size %.2f, / Fill or Kill: %s'
            placeBetStr = placeBetStr % (placeBet.marketId,
                                         marketComp.getRunnerLabelById(placeBet.selectionId, placeBet.asianLineId),
                                         self.persistenceTypeStr[placeBet.betPersistenceType],
                                         self.betTypeLegend[placeBet.betType],
                                         placeBet.price,
                                         placeBet.size,
                                         str(fillOrKill))
            placeBetMessages.append(placeBetStr)

        self.LogMessages(placeBetMessages)

        if self.optNet and not self.saveCount:
            self.GetMUBets(marketTuple)
            self.GetMarketProfitAndLoss(marketTuple)

        self.saveCount = self.optNetGuard
        self.saveCountPNL = int(self.optNetGuard / 2) + 1

        delay = marketComp.delay
        if delay:
            self.saveCount += delay
コード例 #11
0
ファイル: events.py プロジェクト: mementum/bfplusplus
    def GetEvents(self, eventId, treeItem=None, marketTuple=None):
        self.blockGetEvents.Show(True)

	message = Message(action='getEvents', eventId=eventId)
        message.treeItem = treeItem
        message.marketTuple=marketTuple

	self.thMisc.passMessage(message)
コード例 #12
0
ファイル: threadmodule.py プロジェクト: mementum/bfplusplus
 def updateBets(self, marketTuple, updateBets):
     message = Message(action='module', subAction='updateBets')
     message.exception = None
     message.response = Message()
     message.response.marketTuple = marketTuple
     message.response.updateBets = updateBets
     message.response.modId = self.modId
     self.sendMessage(message, self.pyEventId)
コード例 #13
0
ファイル: threadmodule.py プロジェクト: mementum/bfplusplus
 def cancelBets(self, marketTuple, cancelBets):
     message = Message(action='module', subAction='cancelBets')
     message.exception = None
     message.response = Message()
     message.response.marketTuple = marketTuple
     message.response.cancelBets = cancelBets
     message.response.modId = self.modId
     self.sendMessage(message, self.pyEventId)
コード例 #14
0
ファイル: client.py プロジェクト: FukeKazki/python-bbs
def main():
    action = input('何をしますか?\n1: 読み込み\n2: 書き込み\n3: 削除\n')
    sock = Client(("localhost", 50000))

    if action == Action.WRITE.value:
        handle_name = input('handle_name: ')
        content = input('content: ')
        password = getpass('password: '******'書き込みに失敗しました。')
        else:
            print('書き込みに成功しました。')

    elif action == Action.READ.value:
        body = Body(action=Action.READ.value)

        sock.send_body(body)

        response = sock.recv_response()

        if response.state == State.FAILED.value:
            print('受信に失敗しました。')

        for message in response.messages:
            print('--------------------')
            print(f"ID: {message.id}")
            print(f"TIME: {message.time}")
            print(f"HANDLE NAME: {message.handle_name}")
            print(f"CONTENT: {message.content}")

    elif action == Action.DELETE.value:
        identify = input('id: ')
        password = getpass('password: '******'IDもしくはPASSWORDが間違っています。')
        else:
            print('削除に成功しました。')

    else:
        pass
コード例 #15
0
ファイル: index.py プロジェクト: 7keys/netcall-python-server
 def post(self):
     inputdata = tornado.escape.json_decode(self.request.body)
     user = Mydb.getUserByUsername(inputdata['username'])
     friend = Mydb.getUserByUsername(inputdata['friendname'])
     data = Mydb.delFriends(user['id'], friend['id'])
     if data:
         self.write(Message.say(Message.ok))
     else:
         self.write(Message.say(Message.error))
コード例 #16
0
ファイル: index.py プロジェクト: 7keys/netcall-python-server
 def post(self, *args, **kwargs):
     inputdata = tornado.escape.json_decode(self.request.body)
     data = Mydb.addUser(
         inputdata['username', inputdata['password'], inputdata['nickname'], inputdata['mobile'],
                   inputdata['number'], inputdata['pwd']])
     if data:
         self.write(Message.say(Message.ok, data))
     else:
         self.write(Message.say(Message.error))
コード例 #17
0
ファイル: index.py プロジェクト: 7keys/netcall-python-server
 def post(self, *args, **kwargs):
     inputdata = tornado.escape.json_decode(self.request.body)
     username = inputdata['username']
     password = inputdata['password']
     data = Mydb.Login(username, password)
     if data:
         self.write(Message.say(Message.ok, data))
     else:
         self.write(Message.say(Message.error))
コード例 #18
0
ファイル: threadmodule.py プロジェクト: mementum/bfplusplus
 def placeBets(self, marketTuple, placeBets, fillOrKill=False, fillOrKillTime=15):
     message = Message(action='module', subAction='placeBets')
     message.exception = None
     message.response = Message()
     message.response.marketTuple = marketTuple
     message.response.placeBets = placeBets
     message.response.fillOrKill = fillOrKill
     message.response.fillOrKillTime = fillOrKillTime
     message.response.modId = self.modId
     self.sendMessage(message, self.pyEventId)
コード例 #19
0
ファイル: index.py プロジェクト: 7keys/netcall-python-server
    def get(self, t, id):
        if t == 'username':
            result = Mydb.getUserByUsername(id)
        elif t == 'clientnumber':
            result = Mydb.getUserByClientnumber(id)

        if result:
            self.write(Message.say(Message.ok, result))
        else:
            self.write(Message.say(Message.error))
コード例 #20
0
ファイル: excel.py プロジェクト: mementum/bfplusplus
    def OnButtonClickExcelUpdateWorkbooks(self, event):
        event.Skip()

        self.m_checkListExcelSheets.Clear()
        self.m_checkListExcelWorkbooks.Clear()

        self.workbooks = dict()
        self.sheets = defaultdict(dict)

        self.LoadExcelModule()
        if self.excelModule is not None:
            message = Message()
            message.subAction = 'getExcelSheets'
            self.excelModule.passMessage(message)
コード例 #21
0
ファイル: patternsearch.py プロジェクト: mementum/bfplusplus
    def LoadPatterns(self):
        self.m_listCtrlFavs.DeleteAllItems()
        self.m_listCtrlFavs.InsertStringItem(0, '')
        self.m_listCtrlFavs.SetStringItem(0, 1, '--Processing--')
        self.m_listCtrlFavs.Refresh()

        if not hasattr(self, 'thFavourites'):
            self.thFavourites = threadsbf.ThreadFavs(self, self.OnFavourites)

        message = Message(action='favourites')
        message.marketData = self.marketData
        message.patterns = self.loadPatterns.values()
        self.blockFavs.Show(True)

        self.thFavourites.passMessage(message)
コード例 #22
0
    def add_task(self):
        try:
            task_name = self.elements['task_text'].get_text()
            day = self.elements['day_combobox'].get_text()
            time_from = Time_Converter.extract(self.elements['from_text'].get_text())
            time_to = Time_Converter.extract(self.elements['to_text'].get_text())
            color = self.elements['color_combobox'].get_text()

            for name, element in self.elements.items():
                if name != 'name_text': element.clear()
            task = Task(task_name, day, time_from, time_to, color)
            self.schedule.add_task(task)
        except:
            Message.show_error('Wrong input was inserted.')
        return self.schedule
コード例 #23
0
ファイル: pageblock.py プロジェクト: wyl-hit/job
 def __init__(self, crawler):
     super(PythonJavascript, self).__init__()
     print "PythonJavascript __init__ start"
     self.crawler = crawler
     self.message = Message(self.crawler.message_type, {
         "url": "",
         "vectors": []
     }).message
コード例 #24
0
ファイル: patternsearch.py プロジェクト: mementum/bfplusplus
    def DoSearch(self):
        text2search = self.m_textCtrlSearch.GetValue()
        if not text2search:
            return

        self.m_listCtrlFavs.DeleteAllItems()
        self.m_listCtrlFavs.InsertStringItem(0, '')
        self.m_listCtrlFavs.SetStringItem(0, 1, '--Processing--')
        self.m_listCtrlFavs.Refresh()

        if not hasattr(self, 'thSearch'):
            self.thSearch = threadsbf.ThreadSearch(self, self.OnFavourites)

        message = Message(action='search')
        message.marketData = self.marketData
        message.search = text2search
        self.blockFavs.Show(True)

        self.thSearch.passMessage(message)
コード例 #25
0
ファイル: ui.py プロジェクト: sammiej/vpn
def sendClick():
    data = screen["dataToSend"].get()
    if data:
        screen["dataToSend"].set("")
        logger.info("sending: {}".format(data))
        try:
            msg = Message(Message.SEND, data)
            Q.put_nowait(msg)
        except Full:
            logger.error("Network queue is full!")
コード例 #26
0
ファイル: bot.py プロジェクト: pelusodan/ReactAnalytics
 def message_posted(slack_event):
     try:
         event = slack_event['event']
         channel_id = event['channel']
         user_id = event['user']
         time_stamp = event['ts']
         text = event['text']
         msg = Message('', channel_id, time_stamp, user_id, text)
         db.add_message(msg)
     except:
         logging.getLogger(__name__).error('Failed to unpack slack event')
コード例 #27
0
ファイル: client.py プロジェクト: FukeKazki/python-line
def write(sock):
    while True:
        content = input()

        message = Message(content=content)

        body = Body(message=message)

        sock.send_body(body)

        if content == 'bye':
            break
コード例 #28
0
    def convert_schedule(self):
        name = self.elements['name_text'].get_text()
        canvas = self.elements['canvas']

        canvas.canvas.postscript(file='data.ps', colormode='color')
        img = Image.open('data.ps')
        img.save('data.png', quality = 200)
        
        img = cv2.imread('data.png')
        img = imutils.rotate_bound(img, 90)
        cv2.imwrite('data.png', img)

        img = Image.open('data.png')
        img = img.convert('RGB')
        img.save(path.format('Schedules', name+'.pdf'))

        os.remove('data.ps')
        os.remove('data.png')

        Message.show_message('Schedule converted successfully.')
        return self.schedule
コード例 #29
0
ファイル: updatebet.py プロジェクト: mementum/bfplusplus
    def UpdateBets(self, marketTuple, updateBets, modId=None):

        message = Message(action='updateBets', marketTuple=marketTuple, updateBets=updateBets)
        message.modId = modId
        self.thMisc.passMessage(message)

        marketComp = self.marketCache[marketTuple]
        updateBetMessages = list()
        for updateBet in updateBets:
            updateBetStr = 'UpdateBet: BetId %d /Old/ Price %.2f / Size: %.2f / Persistence: %s /New/ Price %.2f / Size: %.2f / Persistence: %s'
            updateBetStr = updateBetStr % (updateBet.betId,
                                           updateBet.oldPrice, updateBet.oldSize, self.persistenceTypeStr[updateBet.oldBetPersistenceType],
                                           updateBet.newPrice, updateBet.newSize, self.persistenceTypeStr[updateBet.newBetPersistenceType])
            updateBetMessages.append(updateBetStr)

        self.saveCount = self.optNetGuard
        self.saveCountPNL = int(self.optNetGuard / 2) + 1
        delay = marketComp.delay
        if delay:
            self.saveCount += delay

        self.LogMessages(updateBetMessages)
コード例 #30
0
ファイル: threadsbf.py プロジェクト: mementum/bfplusplus
    def runAction(self, message):
        if not message.timeout:
            self.timeout = None
            return None

        self.timeout = message.timeout / float(self.maxExchanges)
        thMisc = threadbase.ThreadBase.threadManager['Misc']

        # Fetch data from both exchanges on first run
        if not self.timeLast:
            self.timeLast = time.clock()
            for exchangeId in self.exchanges:
                miscMsg = Message(action='getAllMarkets')
                miscMsg.exchangeId = exchangeId
                thMisc.passMessage(miscMsg)
            return None

        timeNow = time.clock()
        timeSpan = timeNow - self.timeLast

        if timeSpan < self.timeout:
            # Time gone is less than set timeout
            # re-set timeout to the remaining time
            # and go
            self.timeout -= timeSpan
            return None

        # the elapsed time is greater or equal than timeout
        self.timeLast = timeNow

	miscMsg = Message(action='getAllMarkets')
        self.lastExchange += 1
        if self.lastExchange == self.maxExchanges:
            self.lastExchange = 0
        miscMsg.exchangeId = self.exchanges[self.lastExchange]
        thMisc.passMessage(miscMsg)

        return None
コード例 #31
0
ファイル: system.py プロジェクト: Flonki/MyBot
    def run(self, message, args: list):
        text = ""
        title = args[1]
        args.pop(0)
        args.pop(0)

        for arg in args:
            text = text + arg + " "
        embed = discord.Embed(title=title, description=text, color=0x00ff00)

        data.messages.append(
            Message(embed, data.client.get_channel(717753910865166376)))

        return "Created Message in Chat"
コード例 #32
0
ファイル: server_socket.py プロジェクト: aeftimia/hexchat
    def send_connect(self, key, aliases, message=False):

        '''Send a connect request'''

        (local_address, remote_address) = (key[0], key[2])
        packet = format_header(local_address, remote_address, ElementTree.Element("connect"))
        packet.attrib['xmlns'] = "hexchat:connect"

        packet = self.master.add_aliases(packet, aliases)

        logging.debug("%s:%d" % local_address + " sending connect request to %s:%d" % remote_address)

        if message: #send by message
            msg = Message()
            msg['type'] = 'chat'
        else:  #send by iq
            msg = Iq()
            msg['type'] = 'set'

        msg['to'] = key[1]
        msg.append(packet)

        self.master.send(msg, aliases, now=True)
コード例 #33
0
    def process_form(self, username=None, password=None, **kwargs):
        msg = Message()

        if not username: msg.add = _("Must specify a username!")
        if not password: msg.add = _("Must specify a password!")

        if username and password:
            output, error = actions.superuser_run(
                "xmpp-register", [username, password])
            if error:
                raise Exception("something is wrong: " + error)

            if "successfully registered" in output:
                msg.add = _("Registered account for %s." % username)
            else:
                msg.add = _("Failed to register account for %s: %s" % (username, output))

        cfg.log(msg.text)
        main = self.main(username, msg=msg.text)
        return self.fill_template(
            title="XMPP Server Configuration",
            main=main,
            sidebar_left=self.sidebar_left,
            sidebar_right=self.sidebar_right)
コード例 #34
0
ファイル: server_socket.py プロジェクト: aeftimia/hexchat
    def send_connect(self, key, aliases, message=False):
        '''Send a connect request'''

        (local_address, remote_address) = (key[0], key[2])
        packet = format_header(local_address, remote_address,
                               ElementTree.Element("connect"))
        packet.attrib['xmlns'] = "hexchat:connect"

        packet = self.master.add_aliases(packet, aliases)

        logging.debug("%s:%d" % local_address +
                      " sending connect request to %s:%d" % remote_address)

        if message:  #send by message
            msg = Message()
            msg['type'] = 'chat'
        else:  #send by iq
            msg = Iq()
            msg['type'] = 'set'

        msg['to'] = key[1]
        msg.append(packet)

        self.master.send(msg, aliases, now=True)
コード例 #35
0
ファイル: guestbookAdmin.py プロジェクト: pjhades/GAE-blog
	def get(self):
		# Get current page
		try:
			pageno = int(self.request.get('pageno'))
		except ValueError:
			pageno = 1

		query = Message.all().order('-time_stamp')
		group = query.fetch(1000)

		msg_list = []
		pagei = 0
		start = 0
		length = len(group)

		while group != [] and msg_list == []:
			# Pick out each page
			while start + self.msg_per_page - 1 < length:
				pagei = pagei + 1
				if pagei == pageno:
					msg_list = group[start : start + self.msg_per_page]
				start = start + self.msg_per_page
			if len(group[start : start + self.msg_per_page]) > 0:
				pagei = pagei + 1
				if pagei == pageno:
					msg_list = group[start : start + self.msg_per_page]

			last_time = group[-1].time_stamp
			query.filter('time_stamp <', last_time)
			group = query.fetch(1000)

		show_left_arrow = 1 if pageno > 1 else 0
		show_right_arrow = 1 if pageno < pagei else 0
		show_left_dot = 1 if pageno >= 5 else 0
		show_right_dot = 1 if pageno <= pagei - 4 else 0

		pageno_list = [i for i in range(max(1, pageno - 3), min(pagei + 1, pageno + 4))]

		for message in msg_list:
			temp = remove_html_tag(message.msg).replace('\n', ' ')
			message.msg = escape_str(temp[:20]) + '...' if len(temp) > 20 else escape_str(temp[:20])

		template_values = {
			'messages': msg_list,
			'page_current': pageno,
			'page_total': pagei,
			'pageno_list': pageno_list,
			'show_left_arrow': show_left_arrow,
			'show_right_arrow': show_right_arrow,
			'show_left_dot': show_left_dot,
			'show_right_dot': show_right_dot,
			'colno': len(pageno_list) + show_left_arrow + show_right_arrow + 
			                           show_left_dot + show_right_dot,
			'page_prev': max(1, pageno - 1),
			'page_next': min(pagei, pageno + 1),

			'logout_url': users.create_logout_url('/'),
			'page_name': 'guestbookAdmin'
		}

		path = os.path.join(os.path.dirname(__file__), 'pages/guestbookAdmin.html')
		self.response.headers['Content-Type'] = 'text/html;charset=utf-8'
		self.response.out.write(template.render(path, template_values))
コード例 #36
0
def remove_password(message: Message) -> Message:
	message.password = None
	return message
コード例 #37
0
ファイル: currentbets.py プロジェクト: mementum/bfplusplus
    def GetCurrentBets(self, exchangeId):
	message = Message(action='getCurrentBets')
        message.exchangeId = exchangeId

	self.thMisc.passMessage(message)
コード例 #38
0
ファイル: index.py プロジェクト: 7keys/netcall-python-server
 def get(self, username):
     result = Mydb.getFriends(username)
     if result:
         self.write(Message.say(Message.ok, result))
     else:
         self.write(Message.say(Message.error))
コード例 #39
0
ファイル: index.py プロジェクト: 7keys/netcall-python-server
 def get(self, username):
     data = Mydb.get_history(username)
     if data:
         self.write(Message.say(Message.ok, data))
     else:
         self.write(Message.say(Message.error))
コード例 #40
0
ファイル: bot.py プロジェクト: pelusodan/ReactAnalytics
 def message_removed(self, slack_event):
     db.remove_message(
         Message('', slack_event['channel'], slack_event['ts'], '', ''))
コード例 #41
0
ファイル: threadmodule.py プロジェクト: mementum/bfplusplus
 def logMessage(self, logMsg):
     message = Message(action='module', subAction='logMsg')
     message.exception = None
     message.response = Message()
     message.response.logMsg = logMsg
     self.sendMessage(message, self.pyEventId)
コード例 #42
0
ファイル: allmarkets.py プロジェクト: mementum/bfplusplus
    def GetAllMarkets(self, exchangeId, **kwargs):
	message = Message(action='getAllMarkets', **kwargs)
        message.exchangeId = exchangeId
	self.thMisc.passMessage(message)
コード例 #43
0
    def on_chat_message(self, message):
        msg = Message(message)
        if not msg.istext:
            print('Chat:', msg.content_type, msg.chat_type, msg.chat_id)
            self.active = False
            return

        self.dataManager.write_message(msg.object)
        rawcommand = msg.raw
        command = msg.normalised
        self.sendername = msg.sendername
        try:
            print('Chat:', msg.chat_type, msg.chat_id, msg.normalised)
        except UnicodeDecodeError:
            print('Chat:', msg.chat_type, msg.chat_id, msg.normalised.encode('utf-8'))

        #slash commands first
        if msg.raw.startswith("/"):
            for k in self.slashcommands.keys():
                cmd = msg.raw.split()[0]
                if cmd[1:] == k:
                    msg.command = msg.raw[len(k)+2:].strip()
                    v = self.slashcommands[k](self, msg)
                    if v: self.sendMessage(msg.chat_id, v)
                    return

        #if modules.games.is_games_message(msg):
        #    modules.games.parse_message(self, msg)
        #    return
        
        #Morning message
        if msg.date-self.morning_message_timer> 3600*16: #16 hours since last message
            h = get_current_hour()
            if h>6 and h <12: #it is morning
                v = self.morning_message(self.homegroup,command)
                if v:
                    self.morning_message_timer = msg.date
                    self.sendMessage(self.homegroup,v)
                    return

        if msg.chat_id in self.silentchats:
            self.active = False
            return
        
        #now for the fun stuff :)

        #custom user responses
        c = prepare_query(msg.raw)
        if c in self.aliasdict:
            t = msg.date
            if t-self.lastupdate > 1800: #every half hour update my willingness to say stuff
                self.update_querycounts(int((t-self.lastupdate)/1800))
                self.lastupdate = t
            if self.react_to_query(c):
                p = self.pick(self.userresponses[self.aliasdict[c]])
                p = p.replace("!name", msg.sendername)
                if p: self.sendMessage(msg.chat_id, p)
                return
            
        #respond to cussing
        if startswith(msg.normalised.replace(", "," "), self.commands['cuss_out']):
            self.sendMessage(msg.chat_id, self.pick(self.responses['cuss_out']))
            return
        command = msg.normalised
        for i in self.commands['introductions']:
            if command.startswith(i):
                command = command[len(i)+1:].strip()
                break
        else:
            if not self.active: return #no introduction given and not active
        if command.startswith(","): command = command[1:].strip()
        if command.startswith("."): command = command[1:].strip()

        #No further command is given so we just say hi
        if not command:
            try:
                name = msg.sendername
                if name == "Olaf": name = "Slomp"
                val = self.pick(self.responses["hi"]).replace("!name",name)
                self.sendMessage(msg.chat_id, val)
                if probaccept(0.07):
                    time.sleep(1.0)
                    self.sendMessage(msg.chat_id, modules.entertainment.get_joke())
                return
            except KeyError:
                self.active = False
                return

        #check if the command corresponds to a module
        for cmd in self.commandcategories.keys():
            s = startswith(command, self.commands[cmd])
            if s:
                msg.command = command[len(s)+1:].strip()
                r = self.commandcategories[cmd](self, msg)
                if r and type(r)==str: self.sendMessage(msg.chat_id, r)
                return
        
        #try approximate custom matches
        options = difflib.get_close_matches(command,self.aliasdict.keys(),n=1,cutoff=0.9)
        if not options: options = difflib.get_close_matches(prepare_query(msg.raw),self.aliasdict.keys(),n=1,cutoff=0.9)
        if options:
            if self.react_to_query(options[0]):
                p = self.pick(self.userresponses[self.aliasdict[options[0]]])
                p = p.replace("!name", msg.sendername)
                if p: self.sendMessage(msg.chat_id, p)
                return

        #haha... kont
        if command.find("kont")!=-1:
            self.sendMessage(msg.chat_id, "Hahaha, je zei kont")
            return
        if command.find("cont")!=-1:
            self.sendMessage(msg.chat_id, "Hahaha, je zei cont")
            return
        
        #questions and other random reactions
        if len(command)>6:
            chat_id = msg.chat_id
            if command[-5:].find("?")!=-1 or command[-5:].find("/")!=-1 or command[-5:].find(">")!=-1: #? and common misspellings
                if (command.find("wat vind")!=-1 or command.find("hoe denk")!=-1 or command.find("vind je")!=-1
                    or command.find("wat is je mening")!=-1 or command.find("wat denk")!=-1):
                    self.sendMessage(chat_id, self.pick(self.responses["question_opinion"]))
                elif startswith(command, ["heb","ben ","zijn ","was ","waren ","is ","ga","zal ","moet "]):
                    self.sendMessage(chat_id, self.pick(self.responses["question_degree"]))
                elif command.find("hoeveel")!=-1 or command.find("hoe veel")!=-1 or command.find("hoe vaak")!=-1:
                    self.sendMessage(chat_id, self.pick(self.responses["question_amount"]))
                elif command.find("waarom")!=-1:
                    self.sendMessage(chat_id, self.pick(self.responses["question_why"]))
                elif command.find("wat ")!=-1:
                    self.sendMessage(chat_id, self.pick(self.responses["question_what"]))
                elif command.find("waarvoor ")!=-1:
                    self.sendMessage(chat_id, self.pick(self.responses["question_waarvoor"]))
                elif command.find("waar ")!=-1:
                    self.sendMessage(chat_id, self.pick(self.responses["question_where"]))
                elif command.find("wanneer")!=-1 or command.find("hoe laat")!=-1:
                    self.sendMessage(chat_id, self.pick(self.responses["question_when"]))
                elif command.find("hoe ")!=-1:
                    self.sendMessage(chat_id, self.pick(self.responses["question_how"]))
                elif command.find("welk")!=-1:
                    self.sendMessage(chat_id, self.pick(self.responses["question_which"]))
                elif command.find("wie")!=-1:
                    self.sendMessage(chat_id, self.pick(self.responses["question_who"]))
                else: #yes/no question
                    self.sendMessage(chat_id, self.pick(self.responses["question_degree"]))
                return
            self.active = False
            if probaccept(0.05):
                self.sendMessage(chat_id, modules.entertainment.get_openingline())
            elif probaccept(0.15):
                self.sendMessage(chat_id,self.pick(self.responses["negative_response"]))
            elif probaccept(0.08):
                r = random.randint(0,len(self.userresponses)-1) # this works because the keys of userresponses are consecutive integers
                self.sendMessage(chat_id, self.pick(self.userresponses[r]))
            return
        
        self.active = False
        return