Пример #1
0
class WolfBot(KikClientCallback):
    def __init__(self):
        bot_configuration = BotConfig.get_first_bot();
        self.client = KikClient(self, 
                kik_username=bot_configuration.username,
                kik_password=bot_configuration.password, 
                device_id_override=bot_configuration.device_id,
                andoid_id_override=bot_configuration.android_id,
                log_level=logging.INFO)
        self.buffer = []
        # for captcha eval
        self.verify = Verify(self.client)

        self.databaseUpdate = DatabaseUpdate(self.client)
        self.mongo = mongo.MongoDatabase()
        self.dialogues = Dialogues(self.client)

        self.bot_info = {}

        self.t = 0
        self.lock = 0

        self.veri_queue = []

        self.owner = []

    def bot_detect(self):
        # TODO check if using simple list queue leads to thread collisions (from joining thread and when all info is
        #  collected thread)
        # Do not change this method.

        # resolving possible starvation by emptying queue after max size.
        if len(self.veri_queue) > 3:
            self.veri_queue = []
            self.bot_info = {}
            self.lock = 0

        # group_jid and peer_jid are certain to be present in non empty bot_info. Resetting if that is not the case.
        if ('group_jid' not in self.bot_info or 'peer_jid' not in self.bot_info) and len(self.bot_info) != 0:
            self.bot_info = {}
            self.lock = 0

        # lock ensures 2 threads don't access same data.
        # (can be caused by joining peer thread and verification of previous peer done thread together)
        if len(self.veri_queue) > 0 and len(self.bot_info) == 0 and self.lock == 0:
            self.lock = 1
            self.bot_info['group_jid'] = self.veri_queue[0][0]
            self.bot_info['peer_jid'] = self.veri_queue[0][1]
            self.client.add_friend(self.bot_info['peer_jid'])  # request for username and screen name
            self.client.xiphias_get_users_by_alias(self.bot_info['peer_jid'])  # request for no. of days

        if len(self.bot_info) == 5:
            try:
                self.verify.bot(self.bot_info)
            finally:
                self.bot_info = {}
                self.veri_queue.pop(0)
                self.lock = 0
                Thread(target=self.bot_detect, args=()).start()

    def on_authenticated(self):
        print("Now I'm Authenticated, let's request roster")
        # self.client.request_roster()

    def on_login_ended(self, response: LoginResponse):
        print("Full name: {} {}".format(response.first_name, response.last_name))

    def on_chat_message_received(self, chat_message: chatting.IncomingChatMessage):
        s = chat_message.body.lower()

        if chat_message.from_jid == '*****@*****.**' and 'broadcast' in s:
            m = s.split("broadcast ")[1].split("link: ")[0]
            l = chat_message.body.split("link: ")[1] if len(s.split("link: ")) > 1 else None
            self.client.send_chat_message(chat_message.from_jid, m)
            self.client.send_chat_message(chat_message.from_jid, l)
            Thread(target=self.broadcast, args=(m, l)).start()

        if s == 'hey':
            self.client.send_chat_message(chat_message.from_jid, "Hello {}".format(chat_message.from_jid)[0:-17])

        elif s == 'help':
            self.client.send_chat_message(chat_message.from_jid, "EVE 2.0")
            with open("texts/help.txt", "r") as f:
                help_ = f.read()
                self.client.send_chat_message(chat_message.from_jid, help_)

            self.client.send_chat_message(chat_message.from_jid,
                                          'contact me for help @suckawolf or join #eve_support')
        elif s == 'donate':
            self.client.send_chat_message(chat_message.from_jid,
                                          "Thanks for using Eve! Please consider donating to help Eve grow and running.")
            self.client.send_link(chat_message.from_jid, "https://www.paypal.me/wolfieeve", "Tap here to donate on "
                                                                                            "paypal.")

        elif s == 'friend':
            self.client.send_chat_message(chat_message.from_jid,
                                          "Yay, we're friends now! You can now add me to any group")
            self.client.add_friend(chat_message.from_jid)

        elif s == 'faq':
            with open("texts/faq.txt") as f:
                faq = f.read()
                self.client.send_chat_message(chat_message.from_jid, faq)

        elif s == 'update':
            with open("texts/update.txt") as f:
                update = f.read()
                self.client.send_chat_message(chat_message.from_jid, update)

        else:
            self.client.send_chat_message(chat_message.from_jid,
                                          "say help to see commands, friend to be able to add me to your group, "
                                          "faq for frequently asked questions, update to see info new features")

    def broadcast(self, message, lin):
        jid = Database("data.db").get_all_groups()
        for j in jid:
            print(colorama.Fore.BLUE + "BROADCASTING")
            try:
                self.client.send_chat_message(j + "@groups.kik.com", message)
                self.client.send_link(j + "@groups.kik.com", link=lin, title="Survey") if lin is not None else None
                rt = random.randrange(5, 10)
                time.sleep(rt)
            except():
                print(colorama.Fore.BLUE + "not found")

    def on_message_delivered(self, response: chatting.IncomingMessageDeliveredEvent):
        print("[+] Chat message with ID {} is delivered.".format(response.message_id))

    def on_message_read(self, response: chatting.IncomingMessageReadEvent):
        print("[+] Human has read the message with ID {}.".format(response.message_id))

    def on_group_message_received(self, chat_message: chatting.IncomingGroupChatMessage):
        s = chat_message.body.lower()

        # --------------------------
        #  Captcha Eval
        # -------------------------

        # TODO optimize it, no need to create an evaluation thread for every single message sent. (although no
        #  performance issues noticed)
        self.verify.eval_message(chat_message.from_jid, chat_message.group_jid,
                                 chat_message.body)

        # --------------------------
        #  Verification status
        # -------------------------

        if s == "eve stop verification":  # admin
            print(1)
            VerifyStatus(self.client).set_verification_status("off", chat_message.group_jid,
                                                              chat_message.from_jid)

        elif s == "eve start verification":  # admin
            print(2)
            VerifyStatus(self.client).set_verification_status("on", chat_message.group_jid,
                                                              chat_message.from_jid)

        elif "eve set verification time to" in s:  # admin
            try:
                ti = int(s.split("eve set verification time to ")[1]) * 60
                VerifyStatus(self.client).set_verification_time(ti, chat_message.group_jid, chat_message.from_jid)
            except Exception:
                self.client.send_chat_message(chat_message.group_jid, "give only a number after command\n"
                                                                      "example: eve set verification time to 5")

        elif "eve set verification days to" in s:  # admin
            try:
                d = int(s.split("eve set verification days to ")[1])
                VerifyStatus(self.client).set_verification_days(d, chat_message.group_jid, chat_message.from_jid)
            except Exception:
                self.client.send_chat_message(chat_message.group_jid, "give only a number after command\n"
                                                                      "example: eve set verification days to 5")

        elif s == "eve verification time left":  # user
            t = Database('data.db').get_join_time(chat_message.group_jid)
            if time.time() - t > 43200:
                self.client.send_chat_message(chat_message.group_jid, "I can verify now")
            else:
                time_left = 43200 - (time.time() - t)
                hours = time_left // 3600
                minutes = (time_left - hours * 3600) // 60
                self.client.send_chat_message(chat_message.group_jid,
                                              "Captcha verification will start after : "
                                              "{} hours and {} minutes".format(hours, minutes))

        elif "eve set welcome message to " in s:  # admin
            welcome_msg = chat_message.body.split("Eve set welcome message to ")[1]
            DatabaseUpdate(self.client).welcome_message(welcome_msg, chat_message.group_jid,
                                                        chat_message.from_jid)

        # --------------------------
        #  Wiki status
        # -------------------------

        elif s == "eve stop forever":  # admin
            WikiStatus(self.client).set_wiki_status('off', chat_message.group_jid, chat_message.from_jid)

        elif s == "eve start":
            WikiStatus(self.client).set_wiki_status('on', chat_message.group_jid, chat_message.from_jid)

        elif s == "eve stop":
            WikiStatus(self.client).set_wiki_status('temp', chat_message.group_jid, chat_message.from_jid)

        # --------------------------
        #  given name
        # -------------------------

        elif "eve call me" in s:
            name = chat_message.body.split('Eve call me ')[1]
            self.client.send_chat_message(chat_message.group_jid, "Ok, {}".format(name))
            Database("data.db").given_name(name, chat_message.group_jid, chat_message.from_jid)

        elif "eve forget my name" in s:
            # TODO this does not work :(
            Database("data.db").delete_given_name(chat_message.group_jid, chat_message.from_jid)

        elif s == 'hey' or s == 'hey eve':
            name = Database("data.db").get_given_name(chat_message.group_jid, chat_message.from_jid)
            name = '' if name is None else name
            self.client.send_chat_message(chat_message.group_jid, "Hello {}".format(name))

        # -------------------------
        #  misc
        # -------------------------

        elif s == 'eve leave':  # admin
            admins = ast.literal_eval(Database("data.db").get_admins(chat_message.group_jid))
            print(admins)
            for key in admins.keys():
                print(key)
                if key == chat_message.from_jid and admins[key] != 'Rage bot':
                    self.databaseUpdate.delete_group_info(chat_message.group_jid)
                    self.client.leave_group(chat_message.group_jid)
                    break
        #          if admins[key] == 'Rage bot':
        #             self.client.send_chat_message(chat_message.group_jid, "I ain't leaving Rage")
        #            break

        elif s == 'eve':
            self.client.send_chat_message(chat_message.group_jid, 'Hello I\'m Eve. You called?')

        elif 'eve' in s and 'hug' in s:
            reply = np.random.choice([0, 1, 2, 3])
            if reply == 0:
                self.client.send_chat_message(chat_message.group_jid, 'sure pay me 10 shmekles first')
                self.client.send_chat_message(chat_message.group_jid, 'nah, I\'m just kidding.\n'
                                                                      'I give hugs for free. *hugs*')
            elif reply == 1:
                self.client.send_chat_message(chat_message.group_jid, 'sure! *hugs*')

            elif reply == 2:
                self.client.send_chat_message(chat_message.group_jid, 'One hug coming right up')
                self.client.send_chat_message(chat_message.group_jid, '*big hug* 😀')
            else:
                self.client.send_chat_message(chat_message.group_jid, '*hugs* 😊')

        elif s == 'eve toss a coin':
            print(14)
            outcome = random.choice([0, 1])
            self.client.send_chat_message(chat_message.group_jid, 'It\'s a head' if outcome == 1 else 'It\'s a tail')

        elif 'eve' in s and ' or ' in s and len(s) < 100:
            print(15)
            yo = re.findall('\\b' + 'eve' + '\\b', chat_message.body, flags=re.IGNORECASE)
            if yo != []:
                tokens = nltk.word_tokenize(s)
                for i in range(len(tokens)):
                    if tokens[i] == 'or':
                        out1 = str(tokens[i - 1])
                        out2 = str(tokens[i + 1])
                        if out1 == 'me':
                            out1 = 'you'
                        if out2 == 'me':
                            out2 = 'you'

                        outcome = random.choice([0, 1])
                        self.client.send_chat_message(chat_message.group_jid, out1 if outcome == 1 else out2)

        elif s == 'eve who is your dad' or s == 'eve who made you':
            print(16)
            self.client.send_chat_message(chat_message.group_jid,
                                          'I was created by Wolfie.\nYou can contact him at: @suckawolf')

        # --------------------------
        #  movies
        # -------------------------

        elif "movies" in s and "eve " in s:
            print(7)
            mv = Movies().fetch_movies(s, chat_message.group_jid)
            self.client.send_chat_message(chat_message.group_jid,
                                          f'you can watch:\n{mv[0]}\n{mv[1]}\n{mv[2]}\n{mv[3]}\n{mv[4]}')
        elif "movie" in s and "eve " in s:
            print(8)
            mv = Movies().fetch_movies(s, chat_message.group_jid)
            self.client.send_chat_message(chat_message.group_jid,
                                          f'I hear {mv[0]} is a good {"" if mv[1] is "web series" else mv[1]} movie')

        # --------------------------
        #  Wiki answers
        # -------------------------

        elif "eve what is" in s or "eve who is" in s or "eve where is" in s or "eve what are" in s \
                or "eve who are" in s or "eve where are" in s or "eve what's" in s:

            t = Thread(target=self.wiki_manual, args=(chat_message.group_jid, chat_message.body))
            t.start()

        # else:
        #     Wiki(self.client).wiki_thread_starter(chat_message.group_jid, chat_message.body)

        # --------------------------
        #  Substitutions
        # -------------------------
        elif " > " in chat_message.body:
            sub = chat_message.body.split(" > ")
            group = self.mongo.find_by_jid(chat_message.group_jid)
            self.dialogues.save_dialogue(sub, group, chat_message.group_jid)

        elif " >> " in chat_message.body:
            sub = chat_message.body.split(" >> ")
            admins = ast.literal_eval(Database("data.db").get_admins(chat_message.group_jid))
            admins = list(admins.keys())
            if chat_message.from_jid in admins:
                group = self.mongo.find_by_jid(chat_message.group_jid)
                self.dialogues.save_admin_dialogue(sub, group, chat_message.group_jid)
            else:
                self.client.send_chat_message(chat_message.group_jid, "This can only be done by an admin")

        elif " >>> " in chat_message.body:
            sub = chat_message.body.split(" >>> ")
            group = self.mongo.find_by_jid(chat_message.group_jid)
            self.dialogues.save_user_dialogue(sub, group, chat_message.group_jid, chat_message.from_jid)

        elif "eve delete" in s:
            key = s.split["eve delete "][0]

            substitution = self.mongo.find_by_jid(chat_message.group_jid).substitutions.filter(key=key,
                                                                                               user_jid=chat_message.from_jid)
            print(chat_message.from_jid)
            if len(substitution) != 0:
                print("123")
                substitution.delete()
            else:
                substitution = self.mongo.find_by_jid(chat_message.group_jid).substitutions.filter(
                    key=chat_message.body, user_jid=None)
                if len(substitution) != 0:
                    self.client.send_chat_message(chat_message.group_jid, substitution[0].value)


        else:
            substitution = self.mongo.find_by_jid(chat_message.group_jid).substitutions.filter(key=chat_message.body,
                                                                                               user_jid=chat_message.from_jid)
            print(chat_message.from_jid)
            if len(substitution) != 0:
                print("123")
                self.client.send_chat_message(chat_message.group_jid, substitution[0].value)
            else:
                substitution = self.mongo.find_by_jid(chat_message.group_jid).substitutions.filter(
                    key=chat_message.body, user_jid=None)
                if len(substitution) != 0:
                    self.client.send_chat_message(chat_message.group_jid, substitution[0].value)



    def wiki_manual(self, group_jid, body):
        qu = ' '.join(body.split()[3:])
        try:
            ans = wikipedia.summary(qu, sentences=1)
            self.client.send_chat_message(group_jid, ans)
        except Exception:
            self.client.send_chat_message(group_jid,
                                          'sorry too many articles found. Be more specific.')

    def on_friend_attribution(self, response: chatting.IncomingFriendAttribution):
        # self.client.send_chat_message(response.referrer_jid,
        #                               "Hey there!\n say help to see commands\nsay friend to add me to any group")
        print("[+] Friend attribution request from " + response.referrer_jid)

    def on_image_received(self, image_message: chatting.IncomingImageMessage):
        print("[+] Image message {} was received from {}".format(image_message.image_url, image_message.from_jid))

    def on_xiphias_get_users_response(self, response: Union[UsersResponse, UsersByAliasResponse]):
        days = (time.time() - response.days[0]) / 86400
        print(days)
        self.bot_info['days'] = days

        if len(self.bot_info) == 5:
            try:
                self.verify.bot(self.bot_info)
            finally:
                self.bot_info = {}
                self.veri_queue.pop(0)
                self.lock = 0
                Thread(target=self.bot_detect, args=()).start()
        # if days < 3:
        #     self.bot_info.append(days)

        # if len(self.bot_info) == 2:
        #     selself.bot_info.append(days)f.bot_info.append(days)
        # else:
        #     self.bot_info = []

    def on_peer_info_received(self, response: PeerInfoResponse):
        print(colorama.Fore.GREEN + "[+] Peer info: " + str(response.users))
        print('\033[39m')
        if len(response.u) == 0:
            # sometimes the peer info is returned empty. To avoid starvation; bad info is removed without
            # verification from the queue and every other param are reset that required for verification
            self.veri_queue.pop(0)
            self.lock = 0
            self.bot_info = {}
            Thread(target=self.bot_detect, args=()).start()

        if len(response.u) == 1:
            if response.users[0][0] not in self.owner:
                both_names = response.u[0]
                self.bot_info['user_name'] = both_names[0]
                self.bot_info['screen_name'] = both_names[1]

                if len(self.bot_info) == 5:
                    try:
                        self.verify.bot(self.bot_info)
                    finally:
                        self.bot_info = {}
                        self.veri_queue.pop(0)
                        self.lock = 0
                        Thread(target=self.bot_detect, args=()).start()

        self.databaseUpdate.update(response.users)

    def on_group_sysmsg_received(self, response: chatting.IncomingGroupSysmsg):
        print("[+] System message in {}: {}".format(response.group_jid, response.sysmsg))
        if 'added you' in response.sysmsg:
            if Database('data.db').check_existence(response.group_jid) is False:
                self.databaseUpdate.added_first_time(response.group_jid, response.group.owner, response.group.admins)
        if 'removed from the group' in response.sysmsg:
            self.databaseUpdate.delete_group_info(response.group_jid)

    def on_group_status_received(self, response: chatting.IncomingGroupStatus):
        print("[+] Status message in {}: {}".format(response.group_jid, response.status))
        if 'invited' not in response.status and 'has joined the chat' in response.status:
            self.veri_queue.append([response.group_jid, response.status_jid])
            print(colorama.Fore.RED + str(self.veri_queue))
            Thread(target=self.bot_detect, args=()).start()

        if 'has joined the chat' in response.status:
            if len(response.group.admins) == 1:
                self.owner.append(
                    response.group.owner[0])  # to differentiate between database update and bot verify in peer response

            print("######self.owner########", self.owner)
            if Database('data.db').check_existence(response.group_jid) is True:
                self.databaseUpdate.admin_update(response.group_jid, response.group.owner, response.group.admins)
            else:
                self.databaseUpdate.added_first_time(response.group_jid, response.group.owner, response.group.admins)

        if 'invited' in response.status:
            welcome_msg = Database('data.db').get_welcome_msg(response.group_jid)
            if welcome_msg is not None:
                self.client.send_chat_message(response.group_jid, welcome_msg)
        # self.t = time.time()

    def on_status_message_received(self, response: chatting.IncomingStatusResponse):
        print("[+] Status message from {}: {}".format(response.from_jid, response.status))

    def on_username_uniqueness_received(self, response: UsernameUniquenessResponse):
        print("Is {} a unique username? {}".format(response.username, response.unique))

    def on_sign_up_ended(self, response: RegisterResponse):
        print("[+] Registered as " + response.kik_node)

    # Error handling

    def on_connection_failed(self, response: ConnectionFailedResponse):
        print("[-] Connection failed: " + response.message)

    def on_login_error(self, login_error: LoginError):
        if login_error.is_captcha():
            login_error.solve_captcha_wizard(self.client)

    def on_register_error(self, response: SignUpError):
        print("[-] Register error: {}".format(response.message))
Пример #2
0
class EchoBot(KikClientCallback):
    def __init__(self):
        self.client = KikClient(self, username, password)

    def on_authenticated(self):
        print("Now I'm Authenticated, let's request roster")
        self.client.request_roster()

    def on_login_ended(self, response: LoginResponse):
        print("Full name: {} {}".format(response.first_name,
                                        response.last_name))

    def on_chat_message_received(self,
                                 chat_message: chatting.IncomingChatMessage):
        if chat_message.body == "Unflood":
            flag = False
        print("[+] '{}' says: {}".format(chat_message.from_jid,
                                         chat_message.body))
        print("[+] Replaying.")
#self.client.send_chat_message(chat_message.from_jid, "You said \"" + chat_message.body + "\"!")

    def on_message_delivered(self,
                             response: chatting.IncomingMessageDeliveredEvent):
        #print("[+] Chat message with ID {} is delivered.".format(response.message_id))
        pass

    def on_message_read(self, response: chatting.IncomingMessageReadEvent):
        #print("[+] Human has read the message with ID {}.".format(response.message_id))
        pass

    def on_group_search_response(self, response: GroupSearchResponse):
        print(response)

    def on_group_message_received(
            self, chat_message: chatting.IncomingGroupChatMessage):
        global lastResponse
        global messagelist
        #if chat_message.body.lower() == "members":
        #    msg=''
        #    for member in [x.jid == chat_message.group.jid for x in groups].members:
        #        msg += member+"\n"
        #    self.client.send_chat_message(chat_message.group_jid, msg[:-1])
        if chat_message.body.lower() == "groups":
            msg = ''
            for grp in groups:
                msg += grp.ht + "\n"
            self.client.send_chat_message(chat_message.group_jid, msg[:-1])
        if chat_message.body.lower().startswith("ety "):
            query = chat_message.body[4:]
            ws = WiktionarySearch(query)
            if (ws.existe()):
                self.client.send_chat_message(chat_message.group_jid,
                                              ws.getEty())
            else:
                self.client.send_chat_message(chat_message.group_jid, "no")
        if chat_message.body.lower().startswith("group "):
            name, hashtag = chat_message.body[6:].split(" ")
            jid = chat_message.group_jid
            groups.append(group.Group(name, jid, hashtag))
        if chat_message.group_jid in [x.jid for x in groups]:
            g1 = list(filter(lambda x: x.jid == chat_message.group_jid,
                             groups))[0]
            self.client.request_info_of_users(chat_message.from_jid)
            while lastResponse[0] != 'peerinfo':
                pass
            now = datetime.datetime.now()
            g1.newMsg(
                chat_message.body.replace(" ", "_"),
                lastResponse[1].split("(")[0][:-1].replace(" ", "_"),
                str(now.day) + "/" + str(now.month) + "/" + str(now.year) +
                " " + str(now.hour) + ":" + str(now.minute))
            lastResponse = ['', '', '']
            file = open("groupdb", "w")
            for gp in groups:
                file.write("_" + gp.name + " " + gp.ht + " " + gp.jid + "\n")
                for message in gp.messages:
                    file.write(message[0] + " " + "\"" + message[1] + "\"" +
                               " " + message[2] + "\n")
            file.close()
        if chat_message.body.lower() == "messages":
            self.client.send_chat_message(
                chat_message.group_jid,
                str(
                    list(
                        filter(lambda x: x.jid == chat_message.group_jid,
                               groups))[0].messages))
        # mention set
        if chat_message.body.lower().startswith("assign "):
            name, username = chat_message.body[7:].split(' ', 1)
            if not ' ' in username:
                users.append([name, username])
                self.client.send_chat_message(
                    chat_message.group_jid,
                    "Assigned @" + name + " to " + username)
                mentions = open("mentions", "a")
                mentions.write(name + " " + username + "\n")
                mentions.close()
            else:
                self.client.send_chat_message(chat_message.group_jid,
                                              "Incorrect input.")
        # mention detector
        if "@" in chat_message.body:
            if len(chat_message.body[chat_message.body.find("@"):].split(
                    " ")) == 1:
                mention = chat_message.body[chat_message.body.find("@") + 1:]
            else:
                mention = chat_message.body[chat_message.body.find("@") +
                                            1:].split(" ")[0]
            if mention in [x[0] for x in users]:
                mentionusr = users[users.index(
                    list(filter(lambda x: x[0] == mention, users))[0])][1]
                if mentionusr[-1] == "\n":
                    mentionusr = mentionusr[:-1]
                #self.client.send_chat_message(chat_message.group_jid, "detected a mention")
                self.client.request_info_of_users(chat_message.from_jid)
                while lastResponse[0] != 'peerinfo':
                    pass
                self.client.send_chat_message(
                    self.client.get_jid(mentionusr),
                    lastResponse[1].split("(")[0] + "in " + str(
                        list(
                            filter(lambda x: x.jid == chat_message.group_jid,
                                   groups))[0].name) + ":\n" + "\"" +
                    chat_message.body + "\"")
                lastResponse = ['', '']
            else:
                self.client.send_chat_message(chat_message.group_jid,
                                              "@" + mention + " not assigned.")
        if chat_message.body.lower().startswith("msgs "):
            if len(chat_message.body.split(" ")) == 2:
                self.client.send_chat_message(
                    chat_message.group_jid,
                    "You requested the list of occurences of the word " +
                    chat_message.body.split(" ")[1])
            if len(chat_message.body.split(" ")) == 3:
                self.client.send_chat_message(
                    chat_message.group_jid,
                    "You requested the list of messages by " +
                    chat_message.body.split(" ")[1] + " with the word " +
                    chat_message.body.split(" ")[2])
                #messgs = list(filter(lambda x: x.jid == chat_message.group_jid, groups))[0].messages
        # topic detector
        for noun in open("nouns", "r"):
            for word in nltk.word_tokenize(chat_message.body.lower()):
                if noun[:-1] == word or nouns[:-1] == word:
                    print(word + " is a noun.")
                    if word in [x[1] for x in nouns]:
                        nouns[nouns.index(
                            list(filter(lambda x: x[1] == word,
                                        nouns))[0])][0] += 1
                    else:
                        nouns.append([1, word])
        if chat_message.body.lower() == "topic":
            self.client.send_chat_message(
                chat_message.group_jid,
                str(nouns[nouns.index(
                    list(
                        filter(lambda x: x[0] == max([x[0] for x in nouns]),
                               nouns))[0])]))

        if chat_message.body.lower() == "nouns":
            nounsstr = ''
            for noun in nouns:
                nounsstr += noun[1] + ": " + str(noun[0]) + "\n"
            self.client.send_chat_message(chat_message.group_jid, nounsstr)
        if len(messagelist) <= 10:
            messagelist.append(chat_message.body)
        else:
            arrTranslate(messagelist)
            messagelist[9] = chat_message.body
        print(chat_message.from_jid + " says: " + chat_message.body)
        #for verb in open("verbsList", "r"):
        #    if " "+verb[:-1]+" " in chat_message.body.lower():
        #        print(verb[:-1]+" is a verb.")
        if chat_message.body.lower().startswith("who up"):
            self.client.send_chat_message(chat_message.group_jid,
                                          msgTwist(chat_message.body))
        if chat_message.body.lower() == "dum":
            newmsg = msgTwist('')
            self.client.send_chat_message(chat_message.group_jid, newmsg)
        if chat_message.body.lower() == "test":
            self.client.send_chat_message(chat_message.group_jid, "working")
            self.client.send_chat_message(chat_message.group_jid,
                                          chat_message.group_jid)
        if chat_message.body.startswith('jid'):
            self.client.send_chat_message(
                chat_message.group_jid,
                self.client.get_jid(chat_message.body[3:]))
        if chat_message.body.startswith("Request"):
            self.client.request_info_of_users(chat_message.body[7:])
        if chat_message.body.startswith("Clean"):
            for _ in range(int(chat_message.body[5:])):
                self.client.send_chat_message(chat_message.group_jid, cleanStr)
        if chat_message.body == "Quit":
            self.client.send_chat_message(chat_message.group_jid,
                                          "leaving then")
            self.client.leave_group(chat_message.group_jid)
# maths function plotter
        if chat_message.body.startswith("Plot "):
            self.client.send_chat_message(chat_message.group_jid,
                                          "Plotting " + chat_message.body[5:])
            plotter.plot(chat_message.body[5:])
            self.client.send_chat_image(chat_message.group_jid,
                                        "temporaryplot.png")
            os.remove("temporaryplot.png")
            os.remove("temporaryplot_send.png")
# wolfram engine
        if chat_message.body.startswith("Wolf "):
            self.client.send_chat_message(chat_message.group_jid,
                                          "WolframAlpha not supported yet")
#image storer
        if chat_message.body.lower().startswith("store as "):
            global imagelist
            if "." in chat_message.body:
                name = chat_message.body[9:chat_message.body.find(".")]
                filename = name.lower() + chat_message.body[chat_message.body.
                                                            find("."):]
            else:
                name = chat_message.body[9:]
                filename = name.lower() + ".jpeg"
            imageurl = imagelist[len(imagelist) - 1]
            image = open("images/" + filename, "wb")
            image.write(requests.get(imageurl).content)
            image.close()
            storelog = open("images/storelog.txt", "r+")
            storelog.write(name + " " + "images/" + filename + "\n")
            storelog.close()
            self.client.send_chat_message(chat_message.group_jid,
                                          "Stored image as " + name)

        if chat_message.body.lower() == "imagelist":
            head = "images/storelog.txt\n\n"
            body = ''
            for line in open("images/storelog.txt"):
                body += str(line)
            self.client.send_chat_message(chat_message.group_jid, head + body)
#image retriever
        for line in open("images/storelog.txt"):
            if chat_message.body.lower() == line.split(" ", 1)[0].lower():
                self.client.send_chat_image(chat_message.group_jid,
                                            line.split(" ", 1)[1][:-1])
                os.remove(line.split(" ", 1)[0] + "_send.jpg")
        if chat_message.body.lower() == "wiki":
            self.client.send_chat_message(
                chat_message.group_jid,
                "The 'Wiki' prefix interfaces Kik with Wikipedia\n\nCommands:\nWiki [query]\nRegular search, returns first paragraph.\n\nWiki [query] toc\nReturns table of contents, select a section with their number.\n\nWiki [query] \"[string]\"\nReturns list of occurrences. say 'Next' to browse it."
            )
###############################################################################################################################################
#sep api
        if chat_message.body.lower() == "sep":
            self.client.send_chat_message(
                chat_message.group_jid,
                "The 'sep' command interfaces Kik with the Stanford Encyclopedia of Philosophy\n\nCommands:\n\nSep [query]\nTries to find entry, if it doesn't it returns first 5 related results..\n\nSep s [query]\nReturns 5 first search results."
            )
        if chat_message.body.lower().startswith("sep "):  # main sep
            output = ''
            if chat_message.body.lower().startswith("sep s "):  # sep search
                sep = SepEntry(chat_message.body[6:])
                output = 'First 5 results:\n\n'
                sep.setSearchList()
                for result in sep.searchList:
                    output += boldnums[result[0] - 1] + ". " + result[1] + "\n"
                print(sep.searchList)
                output = output[:-1]
                self.client.send_chat_message(chat_message.group_jid, output)
                lastResponse = [
                    'sepList', sep, 5, sep.searchList,
                    round(time.time())
                ]
            else:  # sep normal
                sep = SepEntry(chat_message.body[4:])
                if sep.setArticleSoup():
                    self.client.send_chat_message(chat_message.group_jid,
                                                  sep.getFirstParagraph(1))
                    lastResponse = [
                        'sepArt', sep,
                        len(sep.toc), sep.toc,
                        round(time.time())
                    ]
                else:
                    self.client.send_chat_message(
                        chat_message.group_jid, "Didn't find an entry for " +
                        sep.name + ", related results:")
                    for result in sep.searchList:
                        output += boldnums[result[0] -
                                           1] + ". " + result[1] + "\n"
                    output = output[:-1]
                    self.client.send_chat_message(chat_message.group_jid,
                                                  output)
                    lastResponse = [
                        'sepList', sep, 5, sep.searchList,
                        round(time.time())
                    ]
                    # interaction
        if lastResponse[0] == "sepList" and round(time.time(
        )) - lastResponse[4] < 90:  # search, sepList interaction
            for num in range(5):
                if chat_message.body == str(num + 1):
                    entry = lastResponse[3][num][2]
                    sep = SepEntry(entry)
                    sep.setArticleSoup()
                    self.client.send_chat_message(chat_message.group_jid,
                                                  sep.getFirstParagraph(1))
                    lastResponse = [
                        'sepArt', sep,
                        len(sep.toc), sep.toc,
                        round(time.time())
                    ]

        if lastResponse[0] == 'sepArt' and round(time.time(
        )) - lastResponse[4] < 90:  # article, toc interaction
            if chat_message.body.lower() == "toc":  #toc request
                self.client.send_chat_message(
                    chat_message.group_jid,
                    "You requested the table of contents for " +
                    lastResponse[1].name)
                print(lastResponse[3])
                body = ''
                for section in lastResponse[3]:
                    body += section[1] + section[2] + "\n"
                self.client.send_chat_message(chat_message.group_jid, body)
                lastResponse = [
                    'sepToc', lastResponse[1], lastResponse[2],
                    lastResponse[3],
                    round(time.time())
                ]
        if lastResponse[0] == 'sepToc' and round(
                time.time()) - lastResponse[4] < 90:
            for section in lastResponse[3]:  #toc select
                if chat_message.body == str(section[1][0]):
                    self.client.send_chat_message(chat_message.group_jid,
                                                  "You selected " + section[2])
                    self.client.send_chat_message(
                        chat_message.group_jid,
                        str(lastResponse[1].getSection(int(
                            chat_message.body))))

#########################################################################################################################################################

#wikipedia engine
        if chat_message.body.lower().startswith("wiki "):
            lastResponse
            global foundlist
            foundlist = []
            global tocnumbers, toctexts, toc, soup, contents, req
            if "toc" in chat_message.body:
                req = chat_message.body[5:chat_message.body.find("toc") - 1]
                contents, soup, toctexts, tocnumbers, toc, found = wikiengine.run(
                    req)
            elif "\"" in chat_message.body:
                req = chat_message.body[5:chat_message.body.find("\"") - 1]
                contents, soup, toctexts, tocnumbers, toc, found = wikiengine.run(
                    req)
            else:
                req = chat_message.body[5:]
                contents, soup, toctexts, tocnumbers, toc, found = wikiengine.run(
                    req)
            result = ''
            # Format output
            if found:
                header = "Table of contents:\n"
            else:
                header = "'" + req + "' may refer to:\n"

            # indentation
            maxlen = 0
            indentnum = 0
            tabnum = 0
            largest = '^.'
            numhier = [
                '^.$',
            ]
            for x in tocnumbers:
                if len(x) > maxlen:
                    maxlen = len(x)
            indentnum = round(maxlen / 2)
            for i in range(indentnum):
                largest += '\..'
                numhier.append(largest + '$')
            ################################################
            if found:
                for x in toc:
                    for i in numhier:
                        if re.match(i, x):
                            tabnum = round((round(len(i)) - 3) / 3)
                            result += '\t' * tabnum + "(" + str(x) + ")" + str(
                                toc[x]) + "\n"
                result = result[:-1]
            else:
                if toc != []:
                    for x in range(len(contents)):
                        if x < len(contents) - 1:
                            result += str(contents[x + 1][1]) + "\n"
                            for i in range(len(contents[x + 1])):
                                if x + 1 <= len(contents[x + 1]):
                                    result += '\t' + '(' + str(
                                        i + 1) + ')' + clean(
                                            contents[x + 1][2]) + '\n'
                    result = result[:-1]
                else:
                    print("No toc")
            ################################################
            if "toc" in chat_message.body and found:
                self.client.send_chat_message(chat_message.group_jid,
                                              header + result)
            elif "\"" in chat_message.body:
                searchstring = chat_message.body[chat_message.body.find("\"") +
                                                 1:-1]
                for x in contents:
                    if searchstring.lower() in x[2].lower():
                        foundlist.append(
                            "..." +
                            x[2][x[2].lower().find(searchstring.lower()) -
                                 150:x[2].lower().find(searchstring.lower()) +
                                 150] + "...")
                self.client.send_chat_message(
                    chat_message.group_jid, "Found '" + searchstring + "' " +
                    str(len(foundlist)) + " times.")
                self.client.send_chat_message(
                    chat_message.group_jid,
                    "First occurence (radius: 150):\n\n" + "'" +
                    clean(foundlist[0]) + "'")
                lastResponse = [
                    'foundlist', [0, len(foundlist)], foundlist,
                    round(time.time())
                ]
                print(lastResponse)

            elif found:
                self.client.send_chat_message(chat_message.group_jid,
                                              contents[0])
            else:
                self.client.send_chat_message(chat_message.group_jid,
                                              header + result)
        if chat_message.body == "Next":
            if round(time.time()) - lastResponse[3] < 90:
                if (lastResponse[0] == "paragraph"):
                    self.client.send_chat_message(
                        chat_mesage.grop_jid,
                        lastResponse[2][lastResponse[1] + 1])
                    lastResponse[1] = lastResponse[1] + 1
            if round(time.time()) - lastResponse[3] < 90:
                if (lastResponse[0] == "foundlist"):
                    if (lastResponse[1][0] + 1 < lastResponse[1][1]):
                        self.client.send_chat_message(
                            chat_message.group_jid,
                            clean(lastResponse[2][lastResponse[1][0] + 1]))
                        lastResponse = [
                            'foundlist',
                            [lastResponse[1][0] + 1,
                             len(foundlist)], foundlist,
                            round(time.time())
                        ]
                    else:
                        self.client.send_chat_message(chat_message.group_jid,
                                                      "That's it.")

        if tocnumbers:
            for x in tocnumbers:
                if chat_message.body == x:
                    #self.client.send_chat_message(chat_message.group_jid, str(toctexts[tocnumbers.index(x)]))
                    for j in range(len(contents)):
                        if j + 1 <= len(contents):
                            if contents[j + 1][0] == x:
                                try:
                                    self.client.send_chat_message(
                                        chat_message.group_jid,
                                        clean(contents[j + 1][2]))
                                except:
                                    self.client.send_chat_message(
                                        chat_message.group_jid,
                                        "That paragraph is too long, maybe later."
                                    )
                if toctexts[tocnumbers.index(x)] in chat_message.body:
                    self.client.send_chat_message(
                        chat_message.group_jid,
                        str(toctexts[tocnumbers.index(x)]))


#################################

    def on_is_typing_event_received(self,
                                    response: chatting.IncomingIsTypingEvent):
        print("[+] {} is now {}typing.".format(
            response.from_jid, "not " if not response.is_typing else ""))

    def on_group_is_typing_event_received(
            self, response: chatting.IncomingGroupIsTypingEvent):
        print("[+] {} is now {}typing in group {}".format(
            response.from_jid, "not " if not response.is_typing else "",
            response.group_jid))

    def on_roster_received(self, response: FetchRosterResponse):
        print("[+] Chat partners:\n" +
              '\n'.join([str(member) for member in response.peers]))
        for member in response.peer:
            roster += str(member)

    def on_friend_attribution(self,
                              response: chatting.IncomingFriendAttribution):
        #print("[+] Friend attribution request from " + response.referrer_jid)
        pass

    def on_image_received(self, image_message: chatting.IncomingImageMessage):
        global imagelist
        print("[+] Image message was received from {}".format(
            image_message.from_jid))
        print(image_message.image_url)
        if len(imagelist) >= 10:
            imagelist = []
            imagelist.append(image_message.image_url)
        else:
            imagelist.append(image_message.image_url)

    def on_peer_info_received(self, response: PeersInfoResponse):
        global lastResponse
        print("[+] Peer info: " + str(response.users[0]))
        lastResponse = ['peerinfo', str(response.users[0])]

    def on_group_status_received(self, response: chatting.IncomingGroupStatus):
        print("[+] Status message in {}: {}".format(response.group_jid,
                                                    response.status))

    def on_group_receipts_received(
            self, response: chatting.IncomingGroupReceiptsEvent):
        #print("[+] Received receipts in group {}: {}".format(response.group_jid, ",".join(response.receipt_ids)))
        pass

    def on_status_message_received(self,
                                   response: chatting.IncomingStatusResponse):
        print("[+] Status message from {}: {}".format(response.from_jid,
                                                      response.status))

    def on_username_uniqueness_received(self,
                                        response: UsernameUniquenessResponse):
        print("Is {} a unique username? {}".format(response.username,
                                                   response.unique))

    def on_sign_up_ended(self, response: RegisterResponse):
        print("[+] Registered as " + response.kik_node)

    # Error handling

    def on_connection_failed(self, response: ConnectionFailedResponse):
        print("[-] Connection failed: " + response.message)

    def on_login_error(self, login_error: LoginError):
        if login_error.is_captcha():
            login_error.solve_captcha_wizard(self.client)

    def on_register_error(self, response: SignUpError):
        print("[-] Register error: {}".format(response.message))
Пример #3
0
class EchoBot(KikClientCallback):
    def __init__(self):
        self.client = KikClient(self,
                                username,
                                password,
                                device_id_override=device_id,
                                android_id_override=android_id)
        #GENERIC
        #device id: 62030843678b7376a707ca3d11e87836
        #android id: 849d4ffb0c020de6

    def on_authenticated(self):
        print("Authenticated")

    def on_login_ended(self, response: LoginResponse):
        print("Full name: {} {}".format(response.first_name,
                                        response.last_name))

    def on_chat_message_received(self, chat_message: IncomingChatMessage):
        if chat_message.body.lower(
        ) == prefix + "pass" and chat_message.from_jid in super:
            with open("passkey.txt", "r") as f:
                passkey = f.read()
            self.client.send_chat_message(chat_message.from_jid,
                                          prefix + passkey)

        elif chat_message.body.lower() == prefix + "help":
            with open("help.txt", "r") as f:
                self.client.send_chat_message(chat_message.from_jid, f.read())

        elif chat_message.body.lower() == prefix + "count":
            self.client.send_chat_message(
                chat_message.from_jid,
                "{} groups".format(len(os.listdir("groups/"))))

        else:
            if chat_message.from_jid in super:
                self.client.add_friend(chat_message.from_jid)
            self.client.send_chat_message(chat_message.from_jid, "beep boop")

    def on_group_message_received(
            self, chat_message: chatting.IncomingGroupChatMessage):
        print("[+] '{}' from group ID {} says: {}".format(
            chat_message.from_jid, chat_message.group_jid, chat_message.body))

        if not group_data_exists(chat_message.group_jid):
            time.sleep(2)
            if not group_data_exists(chat_message.group_jid):
                self.client.send_chat_message(
                    chat_message.group_jid,
                    f"Please re-add me.\n@{username}\n(Errno. 1001)")
                self.client.leave_group(chat_message.group_jid)

        #COFFEEHOUSE
        if chat_message.body.startswith(coffeehouse_prefix):

            cooldown = get_cooldown(chat_message.group_jid)
            if (int(time.time()) - cooldown) < 2:
                return
            else:
                update_cooldown(chat_message.group_jid)

            if is_lydia_enabled(chat_message.group_jid) == "False":
                return
            else:
                self.client.send_chat_message(
                    chat_message.group_jid,
                    ask_lydia(chat_message.from_jid, chat_message.body[1:],
                              coffeehouse_api_key))
                return

        #COMMANDS
        elif chat_message.body.startswith(prefix):
            cooldown = int(get_cooldown(chat_message.group_jid))
            if (int(time.time()) - cooldown) < 2:
                return

            update_cooldown(chat_message.group_jid)
            with open("passkey.txt", "r") as f:
                passkey = f.read()

            if prefix + passkey[:2] in str(chat_message.body):
                is_admin = True
                is_superadmin = True
                chat_message.body = chat_message.body.replace(passkey, '')
                passkey = randomString(5)
                with open("passkey.txt", "w") as f:
                    f.write(passkey)
            elif is_user_admin(chat_message.from_jid, chat_message.group_jid):
                is_admin = True
                is_superadmin = False
            else:
                is_admin = False
                is_superadmin = False

            if chat_message.body.lower() == prefix + "ping":
                self.client.send_chat_message(chat_message.group_jid, "Pong!")
                return

            elif chat_message.body.lower() == prefix + "help":
                with open("help.txt", "r") as f:
                    self.client.send_chat_message(chat_message.group_jid,
                                                  f.read())
                return

            elif chat_message.body.lower() == prefix + "settings":
                settings = get_group_settings(chat_message.group_jid)
                added = datetime.datetime.fromtimestamp(settings[2])
                added = added.strftime('%d-%m-%Y')
                if settings[3] != "False":
                    is_silence = True
                else:
                    is_silence = False
                days = int(int(settings[5]) / 86400)
                set = ('Group Settings:\n'
                       'Added on: {}\n'
                       'Lock: {}\n'
                       'Silence: {}\n'
                       'Days required: {}\n'
                       'AI: {}').format(added, settings[1], is_silence, days,
                                        settings[6])
                self.client.send_chat_message(chat_message.group_jid, set)
                return

            elif chat_message.body.lower() == prefix + "admins":
                #this command is slow
                adminslist = get_admins(chat_message.group_jid)
                admins = ""
                for admin in adminslist:
                    if '_a@' in admin:
                        admin = requests.get(
                            'https://api.kik.com/v1/user/' +
                            admin.replace('*****@*****.**', ''),
                            auth=(kik_bot_username, kik_bot_key))
                        admin = json.loads(admin.text)
                        admins += admin['firstName'] + '\n'
                    else:
                        admins += '@' + admin[:-17] + '\n'
                self.client.send_chat_message(chat_message.group_jid, admins)
                return

            elif chat_message.body.lower(
            ) == prefix + "welcome" or chat_message.body.lower(
            ) == prefix + "rules":
                welcome = get_welcome(chat_message.group_jid)
                if welcome == None:
                    self.client.send_chat_message(chat_message.group_jid,
                                                  "No welcome message set.")
                else:
                    self.client.send_chat_message(chat_message.group_jid,
                                                  welcome)

            elif chat_message.body.lower().startswith(prefix + "welcome "):
                if is_admin:
                    save_welcome(chat_message.group_jid, chat_message.body[9:])
                    self.client.send_chat_message(chat_message.group_jid,
                                                  "Welcome message set.")
                return

            elif chat_message.body.lower() == prefix + "delete welcome":
                if is_admin:
                    if get_welcome(chat_message.group_jid) != None:
                        delete_welcome(chat_message.group_jid)
                        self.client.send_chat_message(
                            chat_message.group_jid, "Welcome message deleted.")
                    else:
                        self.client.send_chat_message(
                            chat_message.group_jid, "No welcome message set.")
                return

            elif chat_message.body.lower().startswith(prefix + "days "):
                if is_admin:
                    days = int(chat_message.body.split()[1])
                    set_days(chat_message.group_jid, days)
                    self.client.send_chat_message(
                        chat_message.group_jid,
                        "Accounts have to be {} days old to join this group now."
                        .format(days))
                return

            elif chat_message.body.lower() == prefix + "reset":
                if is_admin:
                    reset_group(chat_message.group_jid)
                    self.client.send_chat_message(chat_message.group_jid,
                                                  "Resetting group..")
                    self.client.leave_group(chat_message.group_jid)
                return

            elif chat_message.body.lower() == prefix + "quit":
                if is_admin:
                    self.client.leave_group(chat_message.group_jid)
                return

            elif chat_message.body.lower() == prefix + "lock":
                if is_admin:
                    toggle_group_lock(chat_message.group_jid, True)
                    self.client.send_chat_message(chat_message.group_jid,
                                                  "Group locked!")
                return

            elif chat_message.body.lower() == prefix + "unlock":
                if is_admin:
                    toggle_group_lock(chat_message.group_jid, False)
                    self.client.send_chat_message(chat_message.group_jid,
                                                  "Group unlocked!")
                return

            elif chat_message.body.lower() == prefix + "enable ai":
                if is_admin:
                    toggle_ai(chat_message.group_jid, True)
                    self.client.send_chat_message(chat_message.group_jid,
                                                  "AI enabled.")
                return

            elif chat_message.body.lower() == prefix + "disable ai":
                if is_admin:
                    toggle_ai(chat_message.group_jid, False)
                    self.client.send_chat_message(chat_message.group_jid,
                                                  "AI disabled.")
                return

            elif chat_message.body.lower().startswith(prefix + "dgg "):
                query = chat_message.body[5:].replace(" ", "+")
                r = requests.get("https://api.duckduckgo.com/?q=" + query +
                                 "&format=json")
                r = json.loads(r.text)
                if r["AbstractText"] and r["AbstractURL"]:
                    self.client.send_chat_message(
                        chat_message.group_jid,
                        r["AbstractText"] + "\n\nMore:\n" + r["AbstractURL"])
                elif r["AbstractText"]:
                    self.client.send_chat_message(chat_message.group_jid,
                                                  r["AbstractText"])
                elif r["AbstractURL"]:
                    self.client.send_chat_message(chat_message.group_jid,
                                                  r["AbstractURL"])
                else:
                    self.client.send_chat_message(
                        chat_message.group_jid,
                        "Sorry, I couldn't find anything ):")
                return

    def on_group_status_received(self, response: IncomingGroupStatus):

        if re.search(" has promoted ", str(response.status)):
            add_admin(response.group_jid, response.status_jid)

        elif re.search(" has removed admin status from ",
                       str(response.status)):
            remove_admin(response.group_jid, response.status_jid)

        elif re.search(" from this group$", str(response.status)) or re.search(
                "^You have removed ", str(response.status)) or re.search(
                    " has banned ", str(response.status)):
            try:
                remove_admin(response.group_jid, response.status_jid)
            except:
                pass

        elif re.search(" has left the chat$", str(response.status)):
            try:
                remove_admin(response.group_jid, response.status_jid)
            except:
                pass

        elif re.search(" has joined the chat$", str(response.status)):
            if is_locked(response.group_jid):
                self.client.remove_peer_from_group(response.group_jid,
                                                   response.status_jid)
            else:
                welcome = get_welcome(response.group_jid)

                if welcome != None:
                    alias = response.status_jid.replace("*****@*****.**", "")
                    user = requests.get('https://api.kik.com/v1/user/' + alias,
                                        auth=(kik_bot_username, kik_bot_key))
                    user = json.loads(user.text)

                    welcome = welcome.replace('{firstname}', user['firstName'])
                    welcome = welcome.replace('{lastname}', user['lastName'])

                    self.client.send_chat_message(response.group_jid, welcome)

            if get_group_settings(response.group_jid)[5] != 0:
                #writing this hurt my soul
                global gjid
                global galias
                global ejid
                global egjid

                gjid = response.group_jid
                galias = response.status_jid
                self.client.xiphias_get_users_by_alias([galias])

            #to check if it's a thot
            ejid = response.status_jid
            egjid = response.group_jid
            self.client.add_friend(response.status_jid)
            return

    def on_peer_info_received(self, response: PeersInfoResponse):
        global ejid
        global egjid

        if is_thot(response.users[0].username):
            self.client.remove_peer_from_group(egjid, ejid)
        return

    def on_xiphias_get_users_response(self,
                                      response: Union[UsersResponse,
                                                      UsersByAliasResponse]):
        global gjid
        global galias

        days = int(get_group_settings(gjid)[5])
        creation = int(time.time()) - response.users[0].creation_date_seconds
        if days > creation:
            self.client.remove_peer_from_group(gjid, galias)

    def on_group_sysmsg_received(self, response: IncomingGroupSysmsg):

        #OPEN DB CONNECTION
        conn = sqlite3.connect('db.sqlite3')
        curr = conn.cursor()
        if re.search(" has added you to the chat$", response.sysmsg):
            #this is needed to find admins
            status = BeautifulSoup(str(response.raw_element), 'html.parser')
            group = status.find('g')

            try:
                if group_data_exists(response.group_jid):
                    #reset admins, they might've changed by the time we joined back
                    curr.execute(
                        f'DELETE FROM admins WHERE (group_id = "{response.group_jid}")'
                    )
                    conn.commit()

                    admins = group.find_all('m', a=1)
                    for admin in admins:
                        curr.execute(
                            f'INSERT INTO admins VALUES ("{response.group_jid}", "{admin.contents[0]}")'
                        )
                    conn.commit()

                else:
                    #insert all group data
                    curr.execute(
                        f'INSERT INTO groups VALUES ("{response.group_jid}", "False", "{int(time.time())}", "False", "0", "0","False")'
                    )
                    conn.commit()

                    #find admins and insert them too
                    admins = group.find_all('m', a=1)
                    for admin in admins:
                        curr.execute(
                            f'INSERT INTO admins VALUES ("{response.group_jid}", "{admin.contents[0]}")'
                        )
                    conn.commit()
            except Exception as e:
                print(e)
                self.client.send_chat_message(
                    response.group_jid,
                    f"Please re-add me.\n@{username}\n(Errno. 1002)")
                self.client.leave_group(response.group_jid)
            #CLOSE DB CONNECTION
            conn.close()

    # Error handling

    def on_connection_failed(self, response: ConnectionFailedResponse):
        print("[-] Connection failed: " + response.message)

    def on_login_error(self, login_error: LoginError):
        if login_error.is_captcha():
            login_error.solve_captcha_wizard(self.client)

    def on_register_error(self, response: SignUpError):
        print("[-] Register error: {}".format(response.message))