Exemplo n.º 1
0
 def __init__(self, token):
     self.token = token
     self.slack = SlackClient(token=self.token)
     self.cleverbot = Cleverbot()
     self.botname = settings.BOT_NAME
     self.facebook = Facebook()
     self.twitter = Twitter()
     self.network = SocialNetwork()
Exemplo n.º 2
0
 def __init__(self):
     logger.debug('Instantiating SocialBot')
     self.token = settings.SECRET_KEY
     self.slack = Slacker(self.token)
     self.facebook = Facebook()
     self.twitter = Twitter()
     self.cleverbot = Cleverbot()
     self.history = {}
Exemplo n.º 3
0
 def __init__(self):
     logger.debug("Instantiating SocialBot")
     self.token = settings.SECRET_KEY
     self.slack = Slacker(self.token)
     self.facebook = Facebook()
     self.twitter = Twitter()
     self.cleverbot = Cleverbot()
     self.history = {}
Exemplo n.º 4
0
 def __init__(self, token):
     self.token = token
     self.slack = SlackClient(token=self.token)
     self.cleverbot = Cleverbot()
     self.botname = settings.BOT_NAME
     self.facebook = Facebook()
     self.twitter = Twitter()
     self.network = SocialNetwork()
Exemplo n.º 5
0
class SocialBot:
    def __init__(self):
        logger.debug("Instantiating SocialBot")
        self.token = settings.SECRET_KEY
        self.slack = Slacker(self.token)
        self.facebook = Facebook()
        self.twitter = Twitter()
        self.cleverbot = Cleverbot()
        self.history = {}

    def channels(self):
        logger.debug("Getting all channels")
        channels = []
        for channel in self.slack.channels.list().body["channels"]:
            channels.append(channel)

        return channels

    def discover_userid(self, username):
        logger.debug("Getting user id")
        users = self.slack.users.list().body["members"]
        for user in users:
            if user["name"] == username:
                return user["id"]

    def discover_username(self, userid):
        logger.debug("Getting username")
        users = self.slack.users.list().body["members"]
        for user in users:
            if user["id"] == userid:
                return user["name"]

    def listen(self, channel):
        logger.debug("Listening...")
        self.messages = self.slack.channels.history(channel, count=3).body["messages"]
        bot_id = self.discover_userid(settings.BOT_NAME)
        bot_mention = "<@" + bot_id + ">"
        if str(channel) in self.history:
            if self.history[str(channel)] != self.messages:
                for message in self.messages:
                    logger.debug("Getting new messages")
                    if dict(message) not in self.history[str(channel)]:
                        text = ""
                        try:
                            text = message["text"]
                            logger.debug("New message: %s" % text)
                        except:
                            logger.error("Invalid message: %s" % str(message["text"]))
                        if bot_mention in text:
                            logger.debug("Oh! Someone is talking to me :D")
                            self.talk(channel, message)
                        if settings.SHARE_TRIGGER in text:
                            logger.debug("Someone is calling me to share!")
                            self.share(channel, text)
                self.history[str(channel)] = self.messages
        else:
            self.history[str(channel)] = []
            self.listen(channel)

    def talk(self, channel, question):
        try:
            logger.debug("Talking to the moooon... ops, to the bot =P")
            answer = "@" + self.discover_username(question["user"]) + ": " + self.cleverbot.ask(question["text"])
            self.slack.chat.post_message(channel=channel, text=answer, as_user=settings.BOT_NAME)
        except Exception as ex:
            logger.error("Something wrong. Error: %s" % str(ex))

    def share(self, channel, message):
        try:
            logger.debug("Sharing...")
            message = message.replace(settings.SHARE_TRIGGER, "").strip().replace("<", "").replace(">", "")
            self.facebook.post(message)
            self.twitter.post(message)
        except Exception as ex:
            logger.error("Something wrong. Error: %s" % str(ex))
Exemplo n.º 6
0
class Robotson():
    def __init__(self, token):
        self.token = token
        self.slack = SlackClient(token=self.token)
        self.cleverbot = Cleverbot()
        self.botname = settings.BOT_NAME
        self.facebook = Facebook()
        self.twitter = Twitter()
        self.network = SocialNetwork()

    def run(self, interval):
        if self.slack.rtm_connect():
            while True:
                full_message = self.slack.rtm_read()
                if full_message:
                    content = full_message[0]
                    if content.get("type") == 'message':
                        sender = self.username_as_str(content.get("user"))
                        channel = content.get("channel")
                        message = content.get("text")

                        try:
                            match = re.search(r'<@[A-Z0-9]+>', message)
                            bot_mention = match.group() if match else ""

                            if bot_mention:
                                # TODO: Remove hardcoding
                                if settings.BOT_UID in bot_mention:
                                    self.talk(channel, sender, message)
                            elif settings.SHARE_TRIGGER in message.lower():
                                self.share(message)
                        except:
                            pass
                time.sleep(interval)
        else:
            raise SlackNotConnected

    def share(self, message):
        try:
            match_share_trigger = re.search(
                r'%s[\:]?' % settings.SHARE_TRIGGER, message)
            message = message.replace(match_share_trigger.group(), "")

            match_lt_mt = re.search(r'[<]+(.*)[>]+', message)
            message = message.replace(match_lt_mt.group(0),
                                      match_lt_mt.group(1))

            message = message.strip()

            url = re.findall(
                r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+',
                message)
            if len(url) > 0:
                if not self.network.already_posted(url[0]):
                    self.facebook.post(message)
                    # self.twitter.post(message)
                    self.network.save_message(message)
        except Exception:
            pass

    def talk(self, channel, user, message):
        try:
            answer = '@%s: %s' % (user, self.cleverbot.ask(message))
            self.slack.rtm_send_message(channel=channel, message=answer)
        except Exception:
            pass

    def username_as_str(self, userid):
        try:
            response = json.loads(
                self.slack.api_call('users.info', user=userid))
            return response.get("user").get("name")
        except:
            return ""
Exemplo n.º 7
0
class Robotson():
    def __init__(self, token):
        self.token = token
        self.slack = SlackClient(token=self.token)
        self.cleverbot = Cleverbot()
        self.botname = settings.BOT_NAME
        self.facebook = Facebook()
        self.twitter = Twitter()
        self.network = SocialNetwork()

    def run(self, interval):
        if self.slack.rtm_connect():
            while True:
                full_message = self.slack.rtm_read()
                if full_message:
                    content = full_message[0]
                    if content.get("type") == 'message':
                        sender = self.username_as_str(content.get("user"))
                        channel = content.get("channel")
                        message = content.get("text")

                        try:
                            match = re.search(r'<@[A-Z0-9]+>', message)
                            bot_mention = match.group() if match else ""

                            if bot_mention:
                                # TODO: Remove hardcoding
                                if settings.BOT_UID in bot_mention:
                                    self.talk(channel, sender, message)
                            elif settings.SHARE_TRIGGER in message.lower():
                                self.share(message)
                        except:
                            pass
                time.sleep(interval)
        else:
            raise SlackNotConnected

    def share(self, message):
        try:
            match_share_trigger = re.search(r'%s[\:]?' % settings.SHARE_TRIGGER, message)
            message = message.replace(match_share_trigger.group(), "")

            match_lt_mt = re.search(r'[<]+(.*)[>]+', message)
            message = message.replace(match_lt_mt.group(0), match_lt_mt.group(1))

            message = message.strip()

            url = re.findall(r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', message)
            if len(url) > 0:
                if not self.network.already_posted(url[0]):
                    self.facebook.post(message)
                    # self.twitter.post(message)
                    self.network.save_message(message)
        except Exception:
            pass

    def talk(self, channel, user, message):
        try:
            answer = '@%s: %s' % (user, self.cleverbot.ask(message))
            self.slack.rtm_send_message(channel=channel, message=answer)
        except Exception:
            pass

    def username_as_str(self, userid):
        try:
            response = json.loads(self.slack.api_call('users.info', user=userid))
            return response.get("user").get("name")
        except:
            return ""
Exemplo n.º 8
0
class SocialBot():
    def __init__(self):
        logger.debug('Instantiating SocialBot')
        self.token = settings.SECRET_KEY
        self.slack = Slacker(self.token)
        self.facebook = Facebook()
        self.twitter = Twitter()
        self.cleverbot = Cleverbot()
        self.history = {}

    def channels(self):
        logger.debug('Getting all channels')
        channels = []
        for channel in self.slack.channels.list().body['channels']:
            channels.append(channel)

        return channels

    def discover_userid(self, username):
        logger.debug('Getting user id')
        users = self.slack.users.list().body['members']
        for user in users:
            if user['name'] == username:
                return user['id']

    def discover_username(self, userid):
        logger.debug('Getting username')
        users = self.slack.users.list().body['members']
        for user in users:
            if user['id'] == userid:
                return user['name']

    def listen(self, channel):
        logger.debug('Listening...')
        self.messages = self.slack.channels.history(channel, count=3).body['messages']
        bot_id = self.discover_userid(settings.BOT_NAME)
        bot_mention = "<@" + bot_id + ">"
        if str(channel) in self.history:
            if self.history[str(channel)] != self.messages:
                for message in self.messages:
                    logger.debug('Getting new messages')
                    if dict(message) not in self.history[str(channel)]:
                        text = ''
                        try:
                            text = message['text']
                            logger.debug('New message: %s' % text)
                        except:
                            logger.error('Invalid message: %s' % str(message['text']))
                        if bot_mention in text:
                            logger.debug('Oh! Someone is talking to me :D')
                            self.talk(channel, message)
                        if settings.SHARE_TRIGGER in text:
                            logger.debug('Someone is calling me to share!')
                            self.share(channel, text)
                self.history[str(channel)] = self.messages
        else:
            self.history[str(channel)] = []
            self.listen(channel)

    def talk(self, channel, question):
        try:
            logger.debug('Talking to the moooon... ops, to the bot =P')
            answer = '@' + self.discover_username(question['user']) + ': ' + self.cleverbot.ask(question['text'])
            self.slack.chat.post_message(channel=channel, text=answer, as_user=settings.BOT_NAME)
        except Exception as ex:
            logger.error('Something wrong. Error: %s' % str(ex))

    def share(self, channel, message):
        try:
            logger.debug('Sharing...')
            message = message.replace(settings.SHARE_TRIGGER, '').strip().replace('<', '').replace('>', '')
            self.facebook.post(message)
            self.twitter.post(message)
        except Exception as ex:
            logger.error('Something wrong. Error: %s' % str(ex))