Esempio n. 1
0
class QuicktimeEvent(Bot):

    _active = True

    # @classmethod
    # def description(cls):
    #   return "`Pig` Has a {}% chance of replacing {}'s message with pig latin".format(cls._frequency * 100, cls._target)

    def run(self):

        if not self._event.isFrom(
                'cja'):  #or not self._event.isInChannel('Secret'):
            return


#     todo move to action queue probably
        postData = {
            'channel':
            self._event.channel(),
            'as_user':
            False,
            'user':
            self._event.user(),
            'username':
            '******',
            'icon_emoji':
            ':warning:',
            'text':
            'DODGE!',
            'attachments': [{
                "callback_id":
                "quicktime",
                "attachment_type":
                "default",
                "text":
                '',
                "fallback":
                "Well this is awkward :bug:",
                "actions": [{
                    "name": "game",
                    "text": "Dive",
                    "style": "danger",
                    "type": "button",
                    "value": "dive"
                }]
            }],
            'token':
            os.environ.get('SECRET')
        }
        self._log = Log()
        self._pool = Pool(1)
        url = 'https://www.slack.com/api/chat.postEphemeral?{}'.format(
            urllib.parse.urlencode(postData))
        self._log.logEvent("{}: {}-bot makes an ephemeral post".format(
            self._event.channelName(), 'QuicktimeEvent'))
        self._pool.apply_async(requests.get, args=[url], callback=())
        return
Esempio n. 2
0
class ActionQueue:
    def __init__(self, pool=None, event=None):
        self._log = Log()
        if pool:
            self._pool = pool
        else:
            self._pool = Pool(1)
        self._originalEvent = event

        self._replacements = []
        self._replies = []
        self._reactions = []
        self._commands = []

    def addReplacement(self,
                       bot,
                       channel,
                       id,
                       thread,
                       message,
                       identity=None,
                       attachments=[]):
        if not self._isAllowedToPostInThisChannel(channel):
            return
        self._replacements.append({
            'bot': bot,
            'channel': channel,
            'id': id,
            'threadId': thread,
            'message': message,
            'identity': identity,
            'attachments': attachments
        })

    def addReaction(self, bot, channel, timestamp, reaction, priority=1):
        if not self._isAllowedToPostInThisChannel(channel):
            return
        self._reactions.append({
            'bot': bot,
            'channel': channel,
            'timestamp': timestamp,
            'reaction': reaction,
            'priority': priority
        })

    def addReply(self, bot, channel, thread, message, identity=None):
        if not self._isAllowedToPostInThisChannel(channel):
            return
        self._replies.append({
            'bot': bot,
            'channel': channel,
            'threadId': thread,
            'message': message,
            'identity': identity
        })

    def addCommand(self, bot, channel, command, message, identity=None):
        if not self._isAllowedToPostInThisChannel(channel):
            return
        self._commands.append({
            'bot': bot,
            'channel': channel,
            'command': command,
            'message': message,
            'identity': identity
        })

    def flush(self):
        if self._replacements:
            self._flushReplacement(random.choice(self._replacements))

        replyRequests = self._replies
        random.shuffle(replyRequests)
        for replyRequest in self._replies:
            self._flushReply(replyRequest)

        reactRequests = self._reactions
        random.shuffle(reactRequests)
        sorted(reactRequests,
               key=lambda request: request.get('priority'),
               reverse=True)
        for reactionRequest in reactRequests:
            self._flushReaction(reactionRequest)

        for commandRequest in self._commands:
            self._flushCommand(commandRequest)

        self._replacements = []
        self._replies = []
        self._reactions = []
        self._commands = []

        self._pool.close()
        self._pool.join()

    def _isAllowedToPostInThisChannel(self, channel):
        return channel in allowed_channel_ids()

    def _flushReplacement(self, replacementRequest):
        postData = PostData(replacementRequest.get('channel'),
                            replacementRequest.get('message'),
                            replacementRequest.get('identity'),
                            threadId=replacementRequest.get('threadId'),
                            attachments=replacementRequest.get('attachments'))
        info = postData.get()
        url = 'https://www.slack.com/api/chat.postMessage?{}'.format(
            urllib.parse.urlencode(info))
        res = self._pool.apply_async(requests.get,
                                     args=[url],
                                     callback=poolCallback)
        newTS = res.get(timeout=2).json()['ts']

        for reactionRequest in self._reactions:
            if reactionRequest.get('timestamp') == replacementRequest.get(
                    'id'):
                reactionRequest['timestamp'] = newTS
        for replyRequest in self._replies:
            if replyRequest.get('threadId') == replacementRequest.get('id'):
                replyRequest['timestamp'] = newTS

        self._log.logEvent("{}: {}-bot adds message: {}".format(
            CHANNELS[replacementRequest.get('channel')].get('name'),
            replacementRequest.get('bot'), info['text']))
        self._deleteMessage(replacementRequest)

    def _flushReply(self, replyRequest):
        postData = PostData(replyRequest.get('channel'),
                            replyRequest.get('message'),
                            replyRequest.get('identity'),
                            threadId=replyRequest.get('threadId'))
        info = postData.get()
        url = 'https://www.slack.com/api/chat.postMessage?{}'.format(
            urllib.parse.urlencode(info))
        self._pool.apply_async(requests.get, args=[url], callback=poolCallback)
        self._log.logEvent("{}: {}-bot adds message: {}".format(
            CHANNELS[replyRequest.get('channel')].get('name'),
            replyRequest.get('bot'), info['text']))

    def _flushReaction(self, reactionRequest):
        options = {
            'channel': reactionRequest.get('channel'),
            'name': reactionRequest.get('reaction'),
            'timestamp': reactionRequest.get('timestamp'),
            'as_user': False,
            'token': os.environ.get('DAKA')
        }
        url = 'https://www.slack.com/api/reactions.add?{}'.format(
            urllib.parse.urlencode(options))
        self._pool.apply_async(requests.get, args=[url], callback=poolCallback)
        self._log.logEvent("{}: {}-bot adds reaction: {}".format(
            CHANNELS[reactionRequest.get('channel')].get('name'),
            reactionRequest.get('bot'), reactionRequest.get('reaction')))

    def _flushCommand(self, commandRequest):
        return
        postData = PostData(commandRequest.get('channel'),
                            commandRequest.get('message'),
                            commandRequest.get('identity'),
                            command=commandRequest.get('command'))
        info = postData.get()
        url = 'https://www.slack.com/api/chat.postMessage?{}'.format(
            urllib.parse.urlencode(info))
        self._pool.apply_async(requests.get, args=[url], callback=poolCallback)
        self._log.logEvent("{}: {}-bot uses command: {}".format(
            CHANNELS[reactionRequest.get('channel')].get('name'),
            commandRequest.get('bot'), commandRequest.get('command')))

    def _deleteMessage(self, replacementRequest):
        postData = {
            'channel': replacementRequest.get('channel'),
            'ts': replacementRequest.get('id'),
            'token': os.environ.get('SECRET')
        }
        url = 'https://www.slack.com/api/chat.delete?{}'.format(
            urllib.parse.urlencode(postData))
        self._pool.apply_async(requests.get, args=[url], callback=poolCallback)
        self._log.logEvent("{}: {}-bot deletes message: {}".format(
            CHANNELS[replacementRequest.get('channel')].get('name'),
            replacementRequest.get('bot'), self._originalEvent.text()))