Example #1
0
    def startBot(self):
        try:
            print("startBot() id: " + self.id)
            # need groups.list api call for the dict of private group info dict by id key
            # make it once at startup, save it for later
            users = (self.sc.api_call("users.list", token=self.token))["members"]
            groups = (self.sc.api_call("groups.list", token=self.token))["groups"]
            ims = (self.sc.api_call("im.list", token=self.token))["ims"]
            channels = (self.sc.api_call("channels.list", token=self.token))["channels"]
            for user in users:
                self.userDict[user["id"]] = user["name"]
                self.idDict[user["name"]] = user["id"]

            # setup the chanDict used for private group/im and public channel info and id reference
            # contains all meta data about those channels and can be used later
            # get it once, so every delete call doesn't repeat them
            # TODO -- seems like joining a channel after starting the bots
            #   allows for deletion even though bot joined after the dictionary was created
            for group in groups:
                self.chanDict[group['id']] = group
            for im in ims:
                self.chanDict[im['id']] = im
            for chan in channels:
                self.chanDict[chan['id']] = chan
            if self.sc.rtm_connect(): # connected to slack real-time messaging api
                print("connected")

                while True:
                    msgs = self.sc.rtm_read()
                    for msg in msgs:
                        # debug messages
                        ##if ("subtype" not in msg):
                        ######print(msg)

                        # this uses the 'EN_dict.txt' file
                        #images.distractionChan(self)

                        catFacts.subbedToCatFacts(self)

                        #### kick a user when they join a channel #####################################
                        #      (need user api key, not bot key)
                        #
                        #
                        # if("subtype" in msg and msg["subtype"] == "group_join"):
                        #     print("remove")
                        #     print(self.sc.api_call("groups.kick",channel=msg["channel"], user="******"))##bots can't kick, use your user api key not bot key to have bot kick users
                        #
                        #
                        ##### send message every time a user becomes active ###########################
                        #
                        #elif("type" in msg and msg["type"] == "presence_change" and
                        #                                msg["presence"] == "active" and msg["user"]):
                        #    # if(msg["user"] not in self.bots):
                        #        # not b0t, Luna, gotoo
                        #        # post to interns-education as "user is active"
                        #        # message = self.userDict[msg["user"]] + " is active"
                        #        # sendMessage("G09LLA9EW",message)
                        #        # print("[I] sent: "+message)
                        ###############################################################################

                        if("type" in msg and msg["type"] == "error"):
                            print("\n\n[!!] error: \n" + msg + "\n\n")
                            # user_is_bot errors because bot cannot use that api function
                            error = "message error - probably no quotes found"
                            self.sendMessage(self.last_channel, error) # error messages don"t have a channel
                            self.sendError()
                        elif("type" in msg and msg["type"] == "message"and "text" in msg and
                                            all(c in self.legalChars for c in msg["text"].replace("'",""))):
                            self.inWhitelist(msg)

                            if(msg["channel"] in self.whitelist):
                                m = msg["text"]
                                #  cuts text contained between <> ex: <test>
                                # TODO -- more detailed usage info for specific commands
                                # to allow for future ~help,<~function> to only display the help message
                                m = re.sub(r'&lt;(.*?)&gt;', '', m)
                                msg["santized"] = m
                                for r in router:
                                    for t in r["text"]:
                                        if(t.lower() in m.lower()):
                                            r["callback"](self, msg)
                    time.sleep(1)
            else:
                print("[!!] Connection Failed, invalid token?")

        except AttributeError:
            print("[!!] attribute error - probably in the send")
            traceback.print_exc(file=sys.stdout)
            print("[!!] restarting the bot")
            self.sc = SlackClient(self.token)
            time.sleep(5)
            self.start()
        except Exception:
            print("[!!] uncaught error")
            traceback.print_exc(file=sys.stdout)
            print("[!!] restarting the bot")
            time.sleep(5)
            self.sc = SlackClient(self.token)
            self.start()
Example #2
0
    def startBot(self):
        try:
            print('startBot')
            usrResponse = self.sc.api_call('users.list', token=self.token)
            usrJson = json.loads(usrResponse.decode('utf-8'))
            users = usrJson['members']
            ##############################
            ### slacker implementation ###
            # slack = Slacker(self.token)
            # response = slack.users.list()
            # users = response.body['members']
            for user in users:
                self.userDict[user['id']] = user['name']
                self.idDict[user['name']] = user['id']
            print(datetime.datetime.now())
            print(self.userDict)
            if self.sc.rtm_connect():
                print('connected')
                while True:
                    now = time.strftime('%H:%M:%S')
                    if (now == '16:20:00' or now == '16:20:30'):
                        images.blaze(self)

                    msgs = self.sc.rtm_read()
                    for msg in msgs:
                        #print(msg)
                        images.distractionChan(self)
                        catFacts.subbedToCatFacts(self)

                        if("subtype" in msg and msg["subtype"] == 'group_join'):
                            print("remove")
                            print(self.sc.api_call("groups.kick",channel=msg["channel"], user="******"))
                        elif("type" in msg and msg["type"] == "presence_change" and 
                                                        msg["presence"] == "active" and msg["user"]):
                            if(msg["user"] not in self.bots):
                                #not b0t, Luna, gotoo
                                #post to interns-education as "user is active"
                                message = self.userDict[msg["user"]] + " is active"
                                #sendMessage("G09LLA9EW",message)
                                #print("[I] sent: "+message)
                        elif("type" in msg and msg["type"] == "error"):
                            print("\n[!!] error: \n" + msg)
                            # user_is_bot errors because bot cannot use that api function
                            error = "message error - probably no quotes found"
                            self.sendMessage(self.last_channel, error) # error messages don't have a channel
                            self.sendError()
                        elif("type" in msg and msg["type"] == "message"and "text" in msg and 
                                                        all(c in self.legalChars for c in msg["text"].replace("'",""))):
                            #print(msg)
                            self.inWhitelist(msg)
                            if("user" in msg and msg["user"] == self.idDict["steveng"]):
                                print("corn")
                                channel = msg["channel"]
                                timestamp = msg["ts"]
                                self.addReaction(channel,timestamp,"corn")
                            elif("user" in msg and msg["user"] == self.idDict["jono"]):
                                print("hancock")
                                channel = msg["channel"]
                                timestamp = msg["ts"]
                                self.addReaction(channel,timestamp,"hancock")
                            elif("user" in msg and msg["user"] == self.idDict["osardar"]):
                                    print("hancock")
                                    channel = msg["channel"]
                                    timestamp = msg["ts"]
                                    self.addReaction(channel,timestamp,"partyparrot")
                            elif("user" in msg and msg["user"] == self.idDict["derek"]):
                                print("derek")
                                channel = msg["channel"]
                                timestamp = msg["ts"]
                                self.addReaction(channel,timestamp,"derek")
                            if(msg["channel"] in self.whitelist):
                                for r in router:
                                    for t in r['text']:
                                        if(t.lower() in msg['text'].lower()):
                                            r['callback'](self, msg)
                        elif('ok' in msg and msg['ok'] == True):
                            self.timestamp.put({'ts':msg['ts'],'channel':self.last_channel})
                    time.sleep(2)
            else:
                print('[!!] Connection Failed, invalid token?')
        except AttributeError:
            print('[!!] error - probably in the send')
            traceback.print_exc(file=sys.stdout)
            print('[!!] restarting the bot')
            self.sc = SlackClient(self.token)
            self.start()
        except Exception:
            print('[!!] uncaught error')
            traceback.print_exc(file=sys.stdout)
            print('[!!] restarting the bot')
            time.sleep(5)
            self.sc = SlackClient(self.token)
            self.start()