Example #1
0
  def login(self, mail=None, passwd=None, cert=None, token=None, qr=False, callback=None):
    if callback is None:
      callback = def_callback
    resp = self.__validate(mail,passwd,cert,token,qr)
    if resp == 1:
      self.Talk.login(mail, passwd, callback=callback)
    elif resp == 2:
      self.Talk.login(mail,passwd,cert, callback=callback)
    elif resp == 3:
      self.Talk.TokenLogin(token)
    elif resp == 4:
      self.Talk.qrLogin(callback)
    else:
      raise Exception("invalid arguments")

    self.authToken = self.Talk.authToken
    self.cert = self.Talk.cert

    self.Poll = Poll(self.authToken)
    self.channel = channel.Channel(self.authToken)
    self.channel.login()

    self.mid = self.channel.mid
    self.channel_access_token = self.channel.channel_access_token
    self.token = self.channel.token
    self.obs_token = self.channel.obs_token
    self.refresh_token = self.channel.refresh_token
    self._headers = {
                        'X-Line-Application': 'IOSIPAD\t7.14.0\tiPhone OS\t10.12.0',
                        'X-Line-Access': self.authToken,
                        'User-Agent': 'Line/6.0.0 iPad4,1 9.0.2'
                         }
Example #2
0
  def login(self, mail=None, passwd=None, cert=None, token=None, qr=False, callback=None):
    if callback is None:
      callback = def_callback
    resp = self.__validate(mail,passwd,cert,token,qr)
    if resp == 1:
      self.Talk.login(mail, passwd, callback=callback)
    elif resp == 2:
      self.Talk.login(mail,passwd,cert, callback=callback)
    elif resp == 3:
      self.Talk.TokenLogin(token)
    elif resp == 4:
      self.Talk.qrLogin(callback)
    else:
      raise Exception("invalid arguments")

    self.authToken = self.Talk.authToken
    self.cert = self.Talk.cert
    self._headers = {
              'X-Line-Application': 'DESKTOPMAC 10.10.2-YOSEMITE-64    MAC 4.5.0', 
              'X-Line-Access': self.authToken, 
              'User-Agent': 'Line/6.0.0 iPad4,1 9.0.2'#'Line/7.18.0 AppleWebKit/534.30'#'Line/6.0.0 iPad4,1 9.0.2'#'Line/7.18.0 iPad4,1 9.0.2'
   }
    self.Poll = Poll(self.authToken)
    self.channel = channel.Channel(self.authToken)
    self.channel.login()
    self.mid = self.channel.mid
    self.channel_access_token = self.channel.channel_access_token
    self.token = self.channel.token
    self.obs_token = self.channel.obs_token
    self.refresh_token = self.channel.refresh_token
Example #3
0
  def login(self, mail=None, passwd=None, cert=None, token=None, qr=False, callback=None):
    if callback is None:
      callback = def_callback
    resp = self.__validate(mail,passwd,cert,token,qr)
    if resp == 1:
      self.Talk.login(mail, passwd, callback=callback)
    elif resp == 2:
      self.Talk.login(mail,passwd,cert, callback=callback)
    elif resp == 3:
      self.Talk.TokenLogin(token)
    elif resp == 4:
      self.Talk.qrLogin(callback)
    else:
      raise Exception("invalid arguments")

    self.authToken = self.Talk.authToken
    self.cert = self.Talk.cert
    self._headers = {
              'X-Line-Application': 'CHROMEOS\t1.4.17\tChrome_OS\t1',
              'X-Line-Access': self.authToken,
              'User-Agent': 'Line/1.4.17'
   }

    self.Poll = Poll(self.authToken)
    """self.channel = channel.Channel(self.authToken)
Example #4
0
  def login(self, mail=None, passwd=None, cert=None, token=None, qr=False, callback=None):
    if callback is None:
      callback = def_callback
    resp = self.__validate(mail,passwd,cert,token,qr)
    if resp == 1:
      self.Talk.login(mail, passwd, callback=callback)
    elif resp == 2:
      self.Talk.login(mail,passwd,cert, callback=callback)
    elif resp == 3:
      self.Talk.TokenLogin(token)
    elif resp == 4:
      self.Talk.qrLogin(callback)
    else:
      raise Exception("invalid arguments")

    self.authToken = self.Talk.authToken
    self.cert = self.Talk.cert
    self._headers = {
              'X-Line-Application': 'DESKTOPMAC	7.18.1	HELLO-WORLD	11.2.5',
              'X-Line-Access': self.authToken, 
              'User-Agent': 'Line/8.0.1'
   }
    self.Poll = Poll(self.authToken)
    self.channel = channel.Channel(self.authToken)
    self.channel.login()	
    self.mid = self.channel.mid
    self.channel_access_token = self.channel.channel_access_token
    self.token = self.channel.token
    self.obs_token = self.channel.obs_token
    self.refresh_token = self.channel.refresh_token
Example #5
0
  def login(self, mail=None, passwd=None, cert=None, token=None, qr=False, callback=None):
    if callback is None:
      callback = def_callback
    resp = self.__validate(mail,passwd,cert,token,qr)
    if resp == 1:
      self.Talk.login(mail, passwd, callback=callback)
    elif resp == 2:
      self.Talk.login(mail,passwd,cert, callback=callback)
    elif resp == 3:
      self.Talk.TokenLogin(token)
    elif resp == 4:
      self.Talk.qrLogin(callback)
    else:
      raise Exception("invalid arguments")

    self.authToken = self.Talk.authToken
    self.cert = self.Talk.cert

    self.Poll = Poll(self.authToken)
    self.channel = channel.Channel(self.authToken)
    self.channel.login()

    self.mid = self.channel.mid
    self.channel_access_token = self.channel.channel_access_token
    self.token = self.channel.token
    self.obs_token = self.channel.obs_token
    self.refresh_token = self.channel.refresh_token
Example #6
0
  def login(self, mail=None, passwd=None, cert=None, token=None, qr=False, callback=None):
    if callback is None:
      callback = def_callback
    resp = self.__validate(mail,passwd,cert,token,qr)
    if resp == 1:
      self.Talk.login(mail, passwd, callback=callback)
    elif resp == 2:
      self.Talk.login(mail,passwd,cert, callback=callback)
    elif resp == 3:
      self.Talk.TokenLogin(token)
    elif resp == 4:
      self.Talk.qrLogin(callback)
    else:
      raise Exception("invalid arguments")

    self.authToken = self.Talk.authToken
    self.cert = self.Talk.cert
    self._headers = {
              'X-Line-Application': 'DESKTOPMAC 8.0.0-YOSEMITE-x64    MAC 4.5.0', 
              'X-Line-Access': self.authToken, 
              'User-Agent': 'Line/1.4.17'
   }
    self.Poll = Poll(self.authToken)
Example #7
0
class LINE:

    mid = None
    authToken = None
    cert = None
    channel_access_token = None
    token = None
    obs_token = None
    refresh_token = None

    def __init__(self):
        self.Talk = Talk()
        self._session = requests.session()

    def login(self,
              mail=None,
              passwd=None,
              cert=None,
              token=None,
              qr=False,
              callback=None):
        if callback is None:
            callback = def_callback
        resp = self.__validate(mail, passwd, cert, token, qr)
        if resp == 1:
            self.Talk.login(mail, passwd, callback=callback)
        elif resp == 2:
            self.Talk.login(mail, passwd, cert, callback=callback)
        elif resp == 3:
            self.Talk.TokenLogin(token)
        elif resp == 4:
            self.Talk.qrLogin(callback)
        else:
            raise Exception("invalid arguments")

        self.authToken = self.Talk.authToken
        self.cert = self.Talk.cert
        self._headers = {
            'X-Line-Application': 'CHROMEOS\t1.7.14\tChrome_OS\t1',
            'X-Line-Access': self.authToken,
            'User-Agent': 'Trevpad/6.0'
        }

        self.Poll = Poll(self.authToken)
        #self.channel = channel.Channel(self.authToken)
        #self.channel.login()

        #self.mid = self.channel.mid

    # self.channel_access_token = self.channel.channel_access_token
    ##self.token = self.channel.token
    #self.obs_token = self.channel.obs_token
    #self.refresh_token = self.channel.refresh_token
    #self._headers = {
    #'X-Line-Application': 'DESKTOPMAC 10.10.2-YOSEMITE-x64 MAC 4.5.0',
    #'X-Line-Access': self.authToken,
    #'User-Agent': 'Line/6.0.0 iPad4,1 9.0.2'
    #}
    """User"""

    def getProfile(self):
        return self.Talk.client.getProfile()

    def getSettings(self):
        return self.Talk.client.getSettings()

    def getUserTicket(self):
        return self.Talk.client.getUserTicket()

    def updateProfile(self, profileObject):
        return self.Talk.client.updateProfile(0, profileObject)

    def updateSettings(self, settingObject):
        return self.Talk.client.updateSettings(0, settingObject)

    def CloneContactProfile(self, mid):
        contact = self.getContact(mid)
        profile = self.getProfile()
        profile.displayName = contact.displayName
        profile.statusMessage = contact.statusMessage
        profile.pictureStatus = contact.pictureStatus
        self.updateDisplayPicture(profile.pictureStatus)
        return self.updateProfile(profile)

    def updateDisplayPicture(self, hash_id):
        return self.Talk.client.updateProfileAttribute(0, 8, hash_id)

    """Operation"""

    def fetchOperation(self, revision, count):
        return self.Poll.client.fetchOperations(revision, count)

    def fetchOps(self, rev, count):
        return self.Poll.client.fetchOps(rev, count, 0, 0)

    def getLastOpRevision(self):
        return self.Talk.client.getLastOpRevision()

    def stream(self):
        return self.Poll.stream()

    """Message"""

    def kedapkedip(self, tomid, text):
        M = Message()
        M.to = tomid
        t1 = "\xf4\x80\xb0\x82\xf4\x80\xb0\x82\xf4\x80\xb0\x82\xf4\x80\xb0\x82"
        t2 = "\xf4\x80\x82\xb3\xf4\x8f\xbf\xbf"
        rst = t1 + text + t2
        M.text = rst.replace("\n", " ")
        return self.Talk.client.sendMessage(0, M)

    def sendMessage(self, messageObject):
        return self.Talk.client.sendMessage(0, messageObject)

    def sendText(self, Tomid, text):
        msg = Message()
        msg.to = Tomid
        msg.text = text

        return self.Talk.client.sendMessage(0, msg)

    def post_content(self, url, data=None, files=None):
        return self._session.post(url,
                                  headers=self._headers,
                                  data=data,
                                  files=files)

    def like(self, mid, postid, likeType=1001):

        header = {
            "Content-Type": "application/json",
            "X-Line-Mid": self.mid,
            "x-lct": self.channel_access_token,
        }

        payload = {
            "likeType": likeType,
            "activityExternalId": postid,
            "actorId": mid
        }

        r = requests.post("http://" + self.host +
                          "/mh/api/v23/like/create.json?homeId=" + mid,
                          headers=header,
                          data=json.dumps(payload))

        return r.json()

    def comment(self, mid, postid, text):
        header = {
            "Content-Type": "application/json",
            "X-Line-Mid": self.mid,
            "x-lct": self.channel_access_token,
        }

        payload = {
            "commentText": text,
            "activityExternalId": postid,
            "actorId": mid
        }

        r = requests.post("http://" + self.host +
                          "/mh/api/v23/comment/create.json?homeId=" + mid,
                          headers=header,
                          data=json.dumps(payload))

        return r.json()

    def sendImage(self, to_, path):
        M = Message(to=to_, text=None, contentType=1)
        M.contentMetadata = None
        M.contentPreview = None
        M_id = self.Talk.client.sendMessage(0, M).id
        files = {
            'file': open(path, 'rb'),
        }
        params = {
            'name': 'media',
            'oid': M_id,
            'size': len(open(path, 'rb').read()),
            'type': 'image',
            'ver': '1.0',
        }
        data = {'params': json.dumps(params)}
        r = self.post_content('https://os.line.naver.jp/talk/m/upload.nhn',
                              data=data,
                              files=files)
        print r
        if r.status_code != 201:
            raise Exception('Upload image failure.')
        return True

    def stalk_instagram():
        """ Function to stalk instagram account and return user profile and top 5 pic """

        try:

            def get_instagram_page_keyword():
                """ Function to return full instagram page link """

                # Find the index of apostrophe
                index_start = text.find("'") + 1
                index_stop = text.rfind("'")

                # Determine whether 2 apostrophe are exist and the text exist
                text_available = (index_stop - index_start) >= 1

                # If user (keyword) exist, crop it
                if text_available:
                    keyword = text[index_start:index_stop]
                    return keyword

                else:
                    return "keyword not found"

            def get_insta_raw_data(page_url):
                """ Function to crawl instagram page to get various data about someone """

                # Try to open instagram page
                try:
                    req = urllib.request.Request(
                        page_url, headers={'User-Agent': "Magic Browser"})
                    con = urllib.request.urlopen(req)
                    page_source_code_text = con.read()
                    mod_page = BeautifulSoup(page_source_code_text,
                                             "html.parser")

                except:
                    report = Lines.general_lines(
                        "failed to open page") % page_url
                    line_bot_api.push_message(address,
                                              TextSendMessage(text=report))
                    raise

                # Parse the raw data, get the script part , select the longest one
                try:
                    rawdatas = mod_page.find_all("script")
                    temp = []
                    for x in rawdatas:
                        temp.append(str(x))
                    rawdatas = max(temp, key=len)

                    # Crop the pre-json part
                    json_raw_text = str(rawdatas)
                    index_start = json_raw_text.find("{")
                    index_stop = json_raw_text.rfind("}") + 1
                    rawdatas = str(json_raw_text[index_start:index_stop])

                except:
                    report = Lines.general_lines(
                        "formatting error") % "instagram's page"
                    line_bot_api.push_message(address,
                                              TextSendMessage(text=report))
                    raise

                # Convert to JSON data
                json_rawdata = json.loads(rawdatas)

                return json_rawdata

            def get_insta_user_data(json_rawdata):
                """ Function to get insta user data """

                # Get user fullname
                try:
                    insta_fullname = json_rawdata["entry_data"]["ProfilePage"][
                        0]["user"]["full_name"]
                except:
                    insta_fullname = "no data"

                # Get user username
                try:
                    insta_username = json_rawdata["entry_data"]["ProfilePage"][
                        0]["user"]["username"]
                except:
                    insta_username = "******"

                # Get user biography
                try:
                    insta_biography = json_rawdata["entry_data"][
                        "ProfilePage"][0]["user"]["biography"]
                except:
                    insta_biography = "no data"

                # Get user follower count
                try:
                    insta_follower = json_rawdata["entry_data"]["ProfilePage"][
                        0]["user"]["followed_by"]["count"]
                except:
                    insta_follower = "no data"

                # Get user following count
                try:
                    insta_following = json_rawdata["entry_data"][
                        "ProfilePage"][0]["user"]["follows"]["count"]
                except:
                    insta_following = "no data"

                # Get user privacy status
                try:
                    insta_private = json_rawdata["entry_data"]["ProfilePage"][
                        0]["user"]["is_private"]
                except:
                    insta_private = "no data"

                # Return all the data found
                return insta_fullname, insta_username, insta_biography, insta_follower, insta_following, insta_private

            def get_insta_media_data(json_rawdata):
                """ Function to get insta media data """

                # Try to get the medias data
                try:
                    insta_media = json_rawdata["entry_data"]["ProfilePage"][0][
                        "user"]["media"]["nodes"]
                except:
                    report = Lines.general_lines(
                        "formatting error") % "posted-media's"
                    line_bot_api.push_message(address,
                                              TextSendMessage(text=report))
                    raise

                # Set default value
                insta_image_link_list = []
                insta_image_caption_list = []
                insta_image_like_list = []

                # Get top 5 image / video data
                for item in insta_media:
                    if len(insta_image_link_list) < 5:

                        # Get the media link
                        try:
                            insta_image = item["thumbnail_src"]
                            insta_image_link_list.append(insta_image)
                        except:
                            break

                        # Get the media caption
                        try:
                            insta_image_caption = str(item["caption"]).strip()
                            insta_image_caption_list.append(
                                insta_image_caption)
                        except:
                            insta_image_caption_list.append("-")

                        # Get the media like count
                        try:
                            insta_image_like = item["likes"]["count"]
                            insta_image_like_list.append(insta_image_like)
                        except:
                            insta_image_like_list.append("0")

                    # If there's more than 5 item in image_link_list, stop it
                    else:
                        break

                return insta_image_link_list, insta_image_caption_list, insta_image_like_list

            def send_header():
                """ Function to send header , confirmation that stalking on the way """

                report = (Lines.stalk_instagram("header")).format(keyword)
                line_bot_api.push_message(address,
                                          TextSendMessage(text=report))

            def send_insta_user_info(insta_fullname, insta_username,
                                     insta_biography, insta_follower,
                                     insta_following):
                """ Function to send instagram page user information """

                # Generate report about user information
                report = [Lines.stalk_instagram("user information header")]
                try:
                    report.append(" ")
                    report.append("Fullname : " + str(insta_fullname))
                    report.append("Instagram username: "******" ")
                    report.append("Biography : " + str(insta_biography))
                    report.append(" ")
                    report.append("Follower : " + str(insta_follower))
                    report.append("Following : " + str(insta_following))
                except:
                    pass

                report = "\n".join(report)
                line_bot_api.push_message(address,
                                          TextSendMessage(text=report))

            def send_insta_user_pic(insta_image_link_list,
                                    insta_image_caption_list,
                                    insta_image_like_list):
                """ Function to send instagram page media (up to 5) """

                image_count = len(insta_image_link_list)

                carousel_text = []
                header_pic = []
                alt_text = ("Stalking " + keyword + "'s instagram...")
                # Generate and format the data used by carousel
                for i in range(0, image_count):

                    # Format image likes count
                    image_like_count = str(insta_image_like_list[i]) + " ♥"

                    # Format image caption
                    if len(insta_image_caption_list[i]) > 45:
                        image_caption = str("\"" +
                                            insta_image_caption_list[i][:45] +
                                            "...\"")
                    else:
                        image_caption = str("\"" +
                                            insta_image_caption_list[i] + "\"")

                    # Join them together and append to carousel text
                    carousel_text.append(
                        str(image_like_count) + "\n" + image_caption)

                    # Append image link to header pic
                    header_pic.append(insta_image_link_list[i])

                if image_count == 0:
                    report = Lines.stalk_instagram("picture count 0")
                    line_bot_api.push_message(address,
                                              TextSendMessage(text=report))

                # Else, send result in form of carousel
                else:
                    columns = []
                    for i in range(0, len(header_pic)):
                        carousel_column = CarouselColumn(
                            text=carousel_text[i][:60],
                            thumbnail_image_url=header_pic[i],
                            actions=[
                                URITemplateAction(label='See detail..',
                                                  uri=header_pic[i])
                            ])
                        columns.append(carousel_column)

                    carousel_template = CarouselTemplate(columns=columns)
                    template_message = TemplateSendMessage(
                        alt_text=alt_text, template=carousel_template)
                    line_bot_api.push_message(address, template_message)

            cont = True
            json_rawdata = None

            # Get the full version link
            keyword = get_instagram_page_keyword()
            page_url = "https://www.instagram.com/" + keyword + "/"

            # If the keyword is not found, stop the process
            if keyword == "keyword not found":
                report = Lines.general_lines("search fail") % "instagram id"
                line_bot_api.push_message(address,
                                          TextSendMessage(text=report))
                cont = False

            # If full version link is available, try to get raw data
            if cont:
                send_header()
                json_rawdata = get_insta_raw_data(page_url)

                # If the data is unavailable, stop the process
                if json_rawdata is None:
                    report = Lines.general_lines("failed to open page") % str(
                        keyword + "'s instagram")
                    line_bot_api.push_message(address,
                                              TextSendMessage(text=report))
                    cont = False

            # If the raw data is available, crawl user information and check if it's private or not
            if cont:
                # Get and send insta page user information
                insta_fullname, insta_username, insta_biography, insta_follower, insta_following, insta_private = get_insta_user_data(
                    json_rawdata)
                send_insta_user_info(insta_fullname, insta_username,
                                     insta_biography, insta_follower,
                                     insta_following)

                if insta_private:
                    report = Lines.stalk_instagram("private")
                    line_bot_api.push_message(address,
                                              TextSendMessage(text=report))
                    cont = False

            # If it's not private, crawl top 5 pic and send it
            if cont:
                # Get and send insta page user media
                insta_image_link_list, insta_image_caption_list, insta_image_like_list = get_insta_media_data(
                    json_rawdata)
                send_insta_user_pic(insta_image_link_list,
                                    insta_image_caption_list,
                                    insta_image_like_list)

        except Exception as exception_detail:
            function_name = "Stalk Instagram"
            OtherUtil.random_error(function_name=function_name,
                                   exception_detail=exception_detail)

    def sendImageWithURL(self, to_, url):
        """Send a image with given image url
        :param url: image url to send
        """
        path = 'pythonLine.data'
        r = requests.get(url, stream=True)
        if r.status_code == 200:
            with open(path, 'w') as f:
                shutil.copyfileobj(r.raw, f)
        else:
            raise Exception('Download image failure.')
        try:
            self.sendImage(to_, path)
        except Exception as e:
            raise e

    def sendAudioWithURL(self, to_, url):
        path = 'pythonLiness.data'
        r = requests.get(url, stream=True)
        if r.status_code == 200:
            with open(path, 'w') as f:
                shutil.copyfileobj(r.raw, f)
        else:
            raise Exception('Download Audio failure.')
        try:
            self.sendAudio(to_, path)
        except Exception as e:
            raise e

    def sendAudio(self, to_, path):
        M = Message(to=to_, contentType=3)
        M.contentMetadata = None
        M.contentPreview = None
        M_id = self.Talk.client.sendMessage(0, M).id
        files = {
            'file': open(path, 'rb'),
        }
        params = {
            'name': 'media',
            'oid': M_id,
            'size': len(open(path, 'rb').read()),
            'type': 'audio',
            'ver': '1.0',
        }
        data = {'params': json.dumps(params)}
        r = self.post_content('https://os.line.naver.jp/talk/m/upload.nhn',
                              data=data,
                              files=files)
        if r.status_code != 201:
            raise Exception('Upload image failure.')
        return True

    def daftarBerita(self):
        page = urllib.request.urlopen(self.link)
        soup = BeautifulSoup(page, "html.parser")
        artikel = soup.find_all("div", class_="article__title")
        dataList = {}
        counter = 0
        for element in artikel:
            dataList[counter] = {}
            dataList[counter]["judul"] = element.a.get_text()
            dataList[counter]["link"] = element.a["href"]
            counter = counter + 1
        beritanotVideo = [
            data for data, info in dataList.items()
            if not info['judul'].lower().startswith(("video", "vlog"))
            if not 'galeri' in info['link']
        ]
        dataListBaru = {}
        for x in beritanotVideo:
            dataListBaru[x] = {}
            dataListBaru[x]["judul"] = dataList[x]["judul"]
            dataListBaru[x]["link"] = dataList[x]["link"]

        return dataListBaru

    def rangkumanBerita(self):
        stopwords = open('id.stopwords.02.01.2016.txt', 'r').read().split('\n')
        halamanBerita = urllib.request.urlopen(self.link)
        soup = BeautifulSoup(halamanBerita, "html.parser")
        isi = soup.find("h3", class_="read__content")
        if (len(isi) < 2):
            return ""
        isi = isi.find_all("p")

        isiParagraf = []
        for paragraf in isi:
            teks = paragraf.get_text()
            isiParagraf.append(teks)
        isiParagraf = [x for x in isiParagraf if not x.startswith('Baca')]

        satuParagraf = []
        for data in isiParagraf:
            isi = re.split(r'\. +', data)
            isi = [x for x in isi if not x == '']
            satuParagraf.extend(isi)

        globaldatakata = {}
        datakataperkal = {}
        counterkal = 0
        for kalimat in satuParagraf:
            hapuskurung = re.sub(r'([^A-Za-z0-9-\/\.]+)', ' ', kalimat)
            hapustitiktypo = re.sub(r'\s\.\s', ' ', hapuskurung)
            hapustitikawaldanakhir = re.sub(r'(\.\s)|(\.$)', ' ',
                                            hapustitiktypo)
            tokenisasi = re.split(r'\s+', hapustitikawaldanakhir)
            token = [x for x in tokenisasi if not x == '']
            # stemmer
            token = [stemmer.stem(x) for x in token]
            datakataperkal[counterkal] = {}
            #kata unik
            for kata in token:
                if not kata in stopwords:
                    datakataperkal[counterkal][kata] = 0
                    if not kata in globaldatakata.keys():
                        globaldatakata[kata] = 0

            for kataunik in datakataperkal[counterkal]:
                for kata in token:
                    if (kataunik == kata):
                        datakataperkal[counterkal][
                            kata] = datakataperkal[counterkal][kata] + 1
                        globaldatakata[kata] = globaldatakata[kata] + 1

            counterkal = counterkal + 1

        score = {}
        for kal in datakataperkal:
            score[kal] = 0
            for kata in globaldatakata.keys():
                for katakal in datakataperkal[kal].keys():
                    if (kata == katakal):
                        tf = 1 + np.log10(datakataperkal[kal][katakal])
                        idf = np.log10(
                            len(globaldatakata) / globaldatakata[kata])
                        bobot = tf * idf
                        score[kal] = score[kal] + bobot

        urutbesarkecil = list(
            sorted(score, key=score.__getitem__, reverse=True))
        batas = 0
        dataRangkuman = []
        for x in urutbesarkecil:
            dataRangkuman.append(x)
            batas = batas + 1
            if (batas >= len(datakataperkal) / 2):
                break
        rangkuman = np.sort(dataRangkuman)
        hasil = []
        for index in rangkuman:
            hasil.append(satuParagraf[index])
        return hasil

    def sendVideo(self, to_, path):
        M = Message(to=to_, contentType=2)
        M.contentMetadata = {'VIDLEN': '0', 'DURATION': '0'}
        M.contentPreview = None
        M_id = self.Talk.client.sendMessage(0, M).id
        files = {
            'file': open(path, 'rb'),
        }
        params = {
            'name': 'media',
            'oid': M_id,
            'size': len(open(path, 'rb').read()),
            'type': 'video',
            'ver': '1.0',
        }
        data = {'params': json.dumps(params)}
        r = self.post_content('https://os.line.naver.jp/talk/m/upload.nhn',
                              data=data,
                              files=files)
        if r.status_code != 201:
            raise Exception('Upload image failure.')
        return True

    def sendVideoWithURL(self, to_, url):
        path = 'pythonLines.data'
        r = requests.get(url, stream=True)
        if r.status_code == 200:
            with open(path, 'w') as f:
                shutil.copyfileobj(r.raw, f)
        else:
            raise Exception('Download Audio failure.')
        try:
            self.sendVideo(to_, path)
        except Exception as e:
            raise e

    def sendEvent(self, messageObject):
        return self._client.sendEvent(0, messageObject)

    def sendChatChecked(self, mid, lastMessageId):
        return self.Talk.client.sendChatChecked(0, mid, lastMessageId)

    def getMessageBoxCompactWrapUp(self, mid):
        return self.Talk.client.getMessageBoxCompactWrapUp(mid)

    def getMessageBoxCompactWrapUpList(self, start, messageBox):
        return self.Talk.client.getMessageBoxCompactWrapUpList(
            start, messageBox)

    def getRecentMessages(self, messageBox, count):
        return self.Talk.client.getRecentMessages(messageBox.id, count)

    def getMessageBox(self, channelId, messageboxId, lastMessagesCount):
        return self.Talk.client.getMessageBox(channelId, messageboxId,
                                              lastMessagesCount)

    def getMessageBoxList(self, channelId, lastMessagesCount):
        return self.Talk.client.getMessageBoxList(channelId, lastMessagesCount)

    def getMessageBoxListByStatus(self, channelId, lastMessagesCount, status):
        return self.Talk.client.getMessageBoxListByStatus(
            channelId, lastMessagesCount, status)

    def getMessageBoxWrapUp(self, mid):
        return self.Talk.client.getMessageBoxWrapUp(mid)

    def getMessageBoxWrapUpList(self, start, messageBoxCount):
        return self.Talk.client.getMessageBoxWrapUpList(start, messageBoxCount)

    def getCover(self, mid):
        h = self.getHome(mid)
        objId = h["result"]["homeInfo"]["objectId"]
        return "http://dl.profile.line-cdn.net/myhome/c/download.nhn?userid=" + mid + "&oid=" + objId

    """Contact"""

    def blockContact(self, mid):
        return self.Talk.client.blockContact(0, mid)

    def unblockContact(self, mid):
        return self.Talk.client.unblockContact(0, mid)

    def findAndAddContactsByMid(self, mid):
        return self.Talk.client.findAndAddContactsByMid(0, mid)

    def findAndAddContactsByMids(self, midlist):
        for i in midlist:
            self.Talk.client.findAndAddContactsByMid(0, i)

    def findAndAddContactsByUserid(self, userid):
        return self.Talk.client.findAndAddContactsByUserid(0, userid)

    def findContactsByUserid(self, userid):
        return self.Talk.client.findContactByUserid(userid)

    def findContactByTicket(self, ticketId):
        return self.Talk.client.findContactByUserTicket(ticketId)

    def getAllContactIds(self):
        return self.Talk.client.getAllContactIds()

    def getBlockedContactIds(self):
        return self.Talk.client.getBlockedContactIds()

    def getContact(self, mid):
        return self.Talk.client.getContact(mid)

    def getContacts(self, midlist):
        return self.Talk.client.getContacts(midlist)

    def getFavoriteMids(self):
        return self.Talk.client.getFavoriteMids()

    def getHiddenContactMids(self):
        return self.Talk.client.getHiddenContactMids()

    """Group"""

    def inviteGroupCall(self, groupId, midlist):
        return self.Talk.client.inviteGroupCall(0, groupId, midlist)

    def findGroupByTicket(self, ticketId):
        return self.Talk.client.findGroupByTicket(ticketId)

    def acceptGroupInvitation(self, groupId):
        return self.Talk.client.acceptGroupInvitation(0, groupId)

    def acceptGroupInvitationByTicket(self, groupId, ticketId):
        return self.Talk.client.acceptGroupInvitationByTicket(
            0, groupId, ticketId)

    def cancelGroupInvitation(self, groupId, contactIds):
        return self.Talk.client.cancelGroupInvitation(0, groupId, contactIds)

    def createGroup(self, name, midlist):
        return self.Talk.client.createGroup(0, name, midlist)

    def getGroup(self, groupId):
        return self.Talk.client.getGroup(groupId)

    def getGroups(self, groupIds):
        return self.Talk.client.getGroups(groupIds)

    def getGroupIdsInvited(self):
        return self.Talk.client.getGroupIdsInvited()

    def getGroupIdsJoined(self):
        return self.Talk.client.getGroupIdsJoined()

    def inviteIntoGroup(self, groupId, midlist):
        return self.Talk.client.inviteIntoGroup(0, groupId, midlist)

    def kickoutFromGroup(self, groupId, midlist):
        return self.Talk.client.kickoutFromGroup(0, groupId, midlist)

    def leaveGroup(self, groupId):
        return self.Talk.client.leaveGroup(0, groupId)

    def rejectGroupInvitation(self, groupId):
        return self.Talk.client.rejectGroupInvitation(0, groupId)

    def reissueGroupTicket(self, groupId):
        return self.Talk.client.reissueGroupTicket(groupId)

    def updateGroup(self, groupObject):
        return self.Talk.client.updateGroup(0, groupObject)

    def findGroupByTicket(self, ticketId):
        return self.Talk.client.findGroupByTicket(0, ticketId)

    """Room"""

    def createRoom(self, midlist):
        return self.Talk.client.createRoom(0, midlist)

    def getRoom(self, roomId):
        return self.Talk.client.getRoom(roomId)

    def inviteIntoRoom(self, roomId, midlist):
        return self.Talk.client.inviteIntoRoom(0, roomId, midlist)

    def leaveRoom(self, roomId):
        return self.Talk.client.leaveRoom(0, roomId)

    """TIMELINE"""

    def new_post(self, text):
        return self.channel.new_post(text)

    def like(self, mid, postid, likeType=1001):
        return self.channel.like(mid, postid, likeType)

    def comment(self, mid, postid, text):
        return self.channel.comment(mid, postid, text)

    def activity(self, limit=20):
        return self.channel.activity(limit)

    def getAlbum(self, gid):

        return self.channel.getAlbum(gid)

    def changeAlbumName(self, gid, name, albumId):
        return self.channel.changeAlbumName(gid, name, albumId)

    def deleteAlbum(self, gid, albumId):
        return self.channel.deleteAlbum(gid, albumId)

    def getNote(self, gid, commentLimit, likeLimit):
        return self.channel.getNote(gid, commentLimit, likeLimit)

    def getDetail(self, mid):
        return self.channel.getDetail(mid)

    def getHome(self, mid):
        return self.channel.getHome(mid)

    def createAlbum(self, gid, name):
        return self.channel.createAlbum(gid, name)

    def createAlbum2(self, gid, name, path):
        return self.channel.createAlbum(gid, name, path, oid)

    def __validate(self, mail, passwd, cert, token, qr):
        if mail is not None and passwd is not None and cert is None:
            return 1
        elif mail is not None and passwd is not None and cert is not None:
            return 2
        elif token is not None:
            return 3
        elif qr is True:
            return 4
        else:
            return 5

    def loginResult(self, callback=None):
        if callback is None:
            callback = def_callback

            prof = self.getProfile()

            print("TREVOR-KONTOL")
            print("INI MID LU KENTOT " + prof.mid)
            print("INI NAMA LU KENTOT " + prof.displayName)
            print("INI TOKEN LU KENTOT " + self.authToken)
            print("INI CERTIFICATE LU KENTOT " +
                  self.cert if self.cert is not None else "")
Example #8
0
class LINE:

  mid = None
  authToken = None
  cert = None
  channel_access_token = None
  token = None
  obs_token = None
  refresh_token = None


  def __init__(self):
    self.Talk = Talk()
    self._session = requests.session()    

  def login(self, mail=None, passwd=None, cert=None, token=None, qr=False, callback=None):
    if callback is None:
      callback = def_callback
    resp = self.__validate(mail,passwd,cert,token,qr)
    if resp == 1:
      self.Talk.login(mail, passwd, callback=callback)
    elif resp == 2:
      self.Talk.login(mail,passwd,cert, callback=callback)
    elif resp == 3:
      self.Talk.TokenLogin(token)
    elif resp == 4:
      self.Talk.qrLogin(callback)
    else:
      raise Exception("invalid arguments")

    self.authToken = self.Talk.authToken
    self.cert = self.Talk.cert
    self._headers = {
              'X-Line-Application': 'DESKTOPMAC	7.18.1	HELLO-WORLD	11.2.5',
              'X-Line-Access': self.authToken, 
              'User-Agent': 'Line/8.0.1'
   }
    self.Poll = Poll(self.authToken)
    self.channel = channel.Channel(self.authToken)
    self.channel.login()	
    self.mid = self.channel.mid
    self.channel_access_token = self.channel.channel_access_token
    self.token = self.channel.token
    self.obs_token = self.channel.obs_token
    self.refresh_token = self.channel.refresh_token


  """User"""

  def getProfile(self):
    return self.Talk.client.getProfile()

  def getSettings(self):
    return self.Talk.client.getSettings()

  def getUserTicket(self):
    return self.Talk.client.getUserTicket()

  def updateProfile(self, profileObject):
    return self.Talk.client.updateProfile(0, profileObject)

  def updateSettings(self, settingObject):
    return self.Talk.client.updateSettings(0, settingObject)

  def cloneContactProfile(self, mid):
      contact = self.getContact(mid) 
      profile = self.getProfile()
      profile.displayName = contact.displayName
      profile.statusMessage = contact.statusMessage
      profile.pictureStatus = contact.pictureStatus
      self.updateDisplayPicture(profile.pictureStatus)
      return self.updateProfile(profile)
    
  def updateDisplayPicture(self, hash_id):
      return self.Talk.client.updateProfileAttribute(0, 8, hash_id)


  """Operation"""

  def fetchOperation(self, revision, count):
        return self.Poll.client.fetchOperations(revision, count)

  def fetchOps(self, rev, count):
        return self.Poll.client.fetchOps(rev, count, 0, 0)

  def getLastOpRevision(self):
        return self.Talk.client.getLastOpRevision()

  def stream(self):
        return self.Poll.stream()

  """Message"""

#  def kedapkedip(self, tomid, text):
#        M = Message()
#        M.to = tomid
#        t1 = "\xf4\x80\xb0\x82\xf4\x80\xb0\x82\xf4\x80\xb0\x82\xf4\x80\xb0\x82"
#        t2 = "\xf4\x80\x82\xb3\xf4\x8f\xbf\xbf"
#        rst = t1 + text + t2
#        M.text = rst.replace("\n", " ")
#        return self.Talk.client.sendMessage(0, M)

  def sendMessage(self, messageObject):
        return self.Talk.client.sendMessage(0,messageObject)

  def sendText(self, Tomid, text):
        msg = Message()
        msg.to = Tomid
        msg.text = text

        return self.Talk.client.sendMessage(0, msg)
  def post_content(self, url, data=None, files=None):
        return self._session.post(url, headers=self._headers, data=data, files=files)

  def sendImage(self, to_, path):
        M = Message(to=to_, text=None, contentType = 1)
        M.contentMetadata = None
        M.contentPreview = None
        M_id = self.Talk.client.sendMessage(0,M).id
        files = {
            'file': open(path, 'rb'),
        }
        params = {
            'name': 'media',
            'oid': M_id,
            'size': len(open(path, 'rb').read()),
            'type': 'image',
            'ver': '1.0',
        }
        data = {
            'params': json.dumps(params)            
        }       

        r = self.post_content('https://os.line.naver.jp/talk/m/upload.nhn', data=data, files=files)
        print r
        if r.status_code != 201:
            raise Exception('Upload image failure.')
        return True

  def sendImageWithURL(self, to_, url):
        """Send a image with given image url

        :param url: image url to send
        """
        path = 'pythonLine.data'

        r = requests.get(url, stream=True)
        if r.status_code == 200:
            with open(path, 'w') as f:
                shutil.copyfileobj(r.raw, f)
        else:
            raise Exception('Download image failure.')

        try:
            self.sendImage(to_, path)
        except Exception as e:
            raise e

  def sendAudioWithURL(self, to_, url):
      path = 'pythonLiness.data'
      r = requests.get(url, stream=True)
      if r.status_code == 200:
         with open(path, 'w') as f:
            shutil.copyfileobj(r.raw, f)
      else:
         raise Exception('Download Audio failure.')
      try:
         self.sendAudio(to_, path)
      except Exception as e:
         raise e
  def sendAudio(self, to_, path):
      M = Message(to=to_,contentType = 3)
      M.contentMetadata = None
      M.contentPreview = None
      M_id = self.Talk.client.sendMessage(0,M).id
      files = {
         'file': open(path, 'rb'),
      }
      params = {
         'name': 'media',
         'oid': M_id,
         'size': len(open(path, 'rb').read()),
         'type': 'audio',
         'ver': '1.0',
      }
      data = {
         'params': json.dumps(params)
      }
      r = self.post_content('https://os.line.naver.jp/talk/m/upload.nhn', data=data, files=files)
      if r.status_code != 201:
         raise Exception('Upload image failure.')
      return True
  def sendVideo(self, to_, path):
      M = Message(to=to_,contentType = 2)
      M.contentMetadata = {
           'VIDLEN' : '0',
           'DURATION' : '0'
       }
      M.contentPreview = None
      M_id = self.Talk.client.sendMessage(0,M).id
      files = {
         'file': open(path, 'rb'),
      }
      params = {
         'name': 'media',
         'oid': M_id,
         'size': len(open(path, 'rb').read()),
         'type': 'video',
         'ver': '1.0',
      }
      data = {
         'params': json.dumps(params)
      }
      r = self.post_content('https://os.line.naver.jp/talk/m/upload.nhn', data=data, files=files)
      if r.status_code != 201:
         raise Exception('Upload image failure.')
      return True
  def sendVideoWithURL(self, to_, url):
      path = 'pythonLines.data'
      r = requests.get(url, stream=True)
      if r.status_code == 200:
         with open(path, 'w') as f:
            shutil.copyfileobj(r.raw, f)
      else:
         raise Exception('Download Audio failure.')
      try:
         self.sendVideo(to_, path)
      except Exception as e:
         raise e

  def sendEvent(self, messageObject):
        return self.Talk.client.sendEvent(0, messageObject)

  def sendChatChecked(self, mid, lastMessageId):
        return self.Talk.client.sendChatChecked(0, mid, lastMessageId)

  def getMessageBoxCompactWrapUp(self, mid):
        return self.Talk.client.getMessageBoxCompactWrapUp(mid)

  def getMessageBoxCompactWrapUpList(self, start, messageBox):
        return self.Talk.client.getMessageBoxCompactWrapUpList(start, messageBox)

  def getRecentMessages(self, messageBox, count):
        return self.Talk.client.getRecentMessages(messageBox.id, count)

  def getMessageBox(self, channelId, messageboxId, lastMessagesCount):
        return self.Talk.client.getMessageBox(channelId, messageboxId, lastMessagesCount)

  def getMessageBoxList(self, channelId, lastMessagesCount):
        return self.Talk.client.getMessageBoxList(channelId, lastMessagesCount)

  def getMessageBoxListByStatus(self, channelId, lastMessagesCount, status):
        return self.Talk.client.getMessageBoxListByStatus(channelId, lastMessagesCount, status)

  def getMessageBoxWrapUp(self, mid):
        return self.Talk.client.getMessageBoxWrapUp(mid)

  def getMessageBoxWrapUpList(self, start, messageBoxCount):
        return self.Talk.client.getMessageBoxWrapUpList(start, messageBoxCount)
        
  def getCover(self,mid):
        h = self.getHome(mid)
        objId = h["result"]["homeInfo"]["objectId"]
        return "http://dl.profile.line-cdn.net/myhome/c/download.nhn?userid=" + mid+ "&oid=" + objId        

  """Contact"""


  def blockContact(self, mid):
        return self.Talk.client.blockContact(0, mid)


  def unblockContact(self, mid):
        return self.Talk.client.unblockContact(0, mid)


  def findAndAddContactsByMid(self, mid):
        return self.Talk.client.findAndAddContactsByMid(0, mid)


  def findAndAddContactsByMids(self, midlist):
        for i in midlist:
            self.Talk.client.findAndAddContactsByMid(0, i)

  def findAndAddContactsByUserid(self, userid):
        return self.Talk.client.findAndAddContactsByUserid(0, userid)

  def findContactsByUserid(self, userid):
        return self.Talk.client.findContactByUserid(userid)

  def findContactByTicket(self, ticketId):
        return self.Talk.client.findContactByUserTicket(ticketId)

  def getAllContactIds(self):
        return self.Talk.client.getAllContactIds()

  def getBlockedContactIds(self):
        return self.Talk.client.getBlockedContactIds()

  def getContact(self, mid):
        return self.Talk.client.getContact(mid)

  def getContacts(self, midlist):
        return self.Talk.client.getContacts(midlist)

  def getFavoriteMids(self):
        return self.Talk.client.getFavoriteMids()

  def getHiddenContactMids(self):
        return self.Talk.client.getHiddenContactMids()

  def CloneContactProfile(self, mid):
	contact = self.getContact(mid)
	profile = self.getProfile()
	profile.displayName = contact.displayName
	profile.statusMessage = contact.statusMessage
	profile.pictureStatus = contact.pictureStatus
	self.updateDisplayPicture(profile.pictureStatus)
	return self.updateProfile(profile)

  def updateDisplayPicture(self, hash_id):
        return self.Talk.client.updateProfileAttribute(0, 8, hash_id)


  """Group"""

  def findGroupByTicket(self, ticketId):
        return self.Talk.client.findGroupByTicket(ticketId)

  def acceptGroupInvitation(self, groupId):
        return self.Talk.client.acceptGroupInvitation(0, groupId)

  def acceptGroupInvitationByTicket(self, groupId, ticketId):
        return self.Talk.client.acceptGroupInvitationByTicket(0, groupId, ticketId)

  def cancelGroupInvitation(self, groupId, contactIds):
        return self.Talk.client.cancelGroupInvitation(0, groupId, contactIds)

  def createGroup(self, name, midlist):
        return self.Talk.client.createGroup(0, name, midlist)

  def getGroup(self, groupId):
        return self.Talk.client.getGroup(groupId)

  def getGroups(self, groupIds):
        return self.Talk.client.getGroups(groupIds)

  def getGroupIdsInvited(self):
        return self.Talk.client.getGroupIdsInvited()

  def getGroupIdsJoined(self):
        return self.Talk.client.getGroupIdsJoined()

  def inviteIntoGroup(self, groupId, midlist):
        return self.Talk.client.inviteIntoGroup(0, groupId, midlist)

  def kickoutFromGroup(self, groupId, midlist):
        return self.Talk.client.kickoutFromGroup(0, groupId, midlist)

  def leaveGroup(self, groupId):
        return self.Talk.client.leaveGroup(0, groupId)

  def rejectGroupInvitation(self, groupId):
        return self.Talk.client.rejectGroupInvitation(0, groupId)

  def reissueGroupTicket(self, groupId):
        return self.Talk.client.reissueGroupTicket(groupId)

  def updateGroup(self, groupObject):
        return self.Talk.client.updateGroup(0, groupObject)
        
  def findGroupByTicket(self,ticketId):
        return self.Talk.client.findGroupByTicket(0,ticketId)

  """Room"""

  def createRoom(self, midlist):
    return self.Talk.client.createRoom(0, midlist)

  def getRoom(self, roomId):
    return self.Talk.client.getRoom(roomId)

  def inviteIntoRoom(self, roomId, midlist):
    return self.Talk.client.inviteIntoRoom(0, roomId, midlist)

  def leaveRoom(self, roomId):
    return self.Talk.client.leaveRoom(0, roomId)

  """TIMELINE"""

  def new_post(self, text):
    return self.channel.new_post(text)

  def like(self, mid, postid, likeType=1001):
    return self.channel.like(mid, postid, likeType)

  def comment(self, mid, postid, text):
    return self.channel.comment(mid, postid, text)

  def activity(self, limit=20):
    return self.channel.activity(limit)

  def getAlbum(self, gid):

      return self.channel.getAlbum(gid)
  def changeAlbumName(self, gid, name, albumId):
      return self.channel.changeAlbumName(gid, name, albumId)

  def deleteAlbum(self, gid, albumId):
      return self.channel.deleteAlbum(gid,albumId)

  def getNote(self,gid, commentLimit, likeLimit):
      return self.channel.getNote(gid, commentLimit, likeLimit)

  def getDetail(self,mid):
      return self.channel.getDetail(mid)

  def getHome(self,mid):
      return self.channel.getHome(mid)

  def createAlbum(self, gid, name):
      return self.channel.createAlbum(gid,name)

  def createAlbum2(self, gid, name, path):
      return self.channel.createAlbum(gid, name, path, oid)


  def __validate(self, mail, passwd, cert, token, qr):
    if mail is not None and passwd is not None and cert is None:
      return 1
    elif mail is not None and passwd is not None and cert is not None:
      return 2
    elif token is not None:
      return 3
    elif qr is True:
      return 4
    else:
      return 5

  def loginResult(self, callback=None):
    if callback is None:
      callback = def_callback

      prof = self.getProfile()

      print("\n\n============== RECKY_BOTS_PROCESS ===============")
      print("\nUser mid : " + prof.mid)
      print("\nUser name : " + prof.displayName)
      print("\nUser token : " + self.authToken)
      print("\n============== RECKY_BOTS_PROCESS ===============")
      print("cert -> " + self.cert if self.cert is not None else "")
Example #9
0
class LINE:

    mid = None
    authToken = None
    cert = None
    channel_access_token = None
    token = None
    obs_token = None
    refresh_token = None

    def __init__(self):
        self.Talk = Talk()

    def login(self,
              mail=None,
              passwd=None,
              cert=None,
              token=None,
              qr=False,
              callback=None):
        if callback is None:
            callback = def_callback
        resp = self.__validate(mail, passwd, cert, token, qr)
        if resp == 1:
            self.Talk.login(mail, passwd, callback=callback)
        elif resp == 2:
            self.Talk.login(mail, passwd, cert, callback=callback)
        elif resp == 3:
            self.Talk.TokenLogin(token)
        elif resp == 4:
            self.Talk.qrLogin(callback)
        else:
            raise Exception("invalid arguments")

        self.authToken = self.Talk.authToken
        self.cert = self.Talk.cert

        self.authToken = self.Talk.authToken
        self.cert = self.Talk.cert
        self._session = requests.session()
        self._headers = {
            'X-Line-Application': 'DESKTOPWIN\t11.2.5\tHelloWorld\t11.2.59',
            'X-Line-Access': self.authToken,
            'User-Agent': 'Line/8.0.2 iPad4,1 9.0.2'
        }
        self.Poll = Poll(self.authToken)
        self.channel = channel.Channel(self.authToken)
        self.channel.login()
        self.mid = self.channel.mid
        self.channel_access_token = self.channel.channel_access_token
        self.token = self.channel.token
        self.obs_token = self.channel.obs_token
        self.refresh_token = self.channel.refresh_token

    """User"""

    def getProfile(self):
        return self.Talk.client.getProfile()

    def getClone(self):
        return self.Talk.client.getClone()

    def getSettings(self):
        return self.Talk.client.getSettings()

    def getUserTicket(self):
        return self.Talk.client.getUserTicket()

    def updateProfile(self, profileObject):
        return self.Talk.client.updateProfile(0, profileObject)

    def updateSettings(self, settingObject):
        return self.Talk.client.updateSettings(0, settingObject)

    def CloneContactProfile(self, mid):
        contact = self.getContact(mid)
        profile = self.getProfile()
        profile.displayName = contact.displayName
        profile.statusMessage = contact.statusMessage
        profile.pictureStatus = contact.pictureStatus
        self.updateDisplayPicture(profile.pictureStatus)
        return self.updateProfile(profile)

    def updateDisplayPicture(self, hash_id):
        return self.Talk.client.updateProfileAttribute(0, 8, hash_id)

    def CloneURL(self, URL):
        contact = self.getContact(URL)
        profile = self.getProfile()
        profile.displayName = contact.displayName
        profile.statusMessage = contact.statusMessage
        prifile.pictureStatus = contact.pictureStatus
        self.updateDisplayPicture(profile.pictureStatus)
        return self.updateProfile(profile)

    def CloneURL(self, hash_URL):
        return self.Talk.client.updateProfileAttribute(0, 8, hash_URL)

    """Operation"""

    def fetchOperation(self, revision, count):
        return self.Poll.client.fetchOperations(revision, count)

    def fetchOps(self, rev, count):
        return self.Poll.client.fetchOps(rev, count, 0, 0)

    def getLastOpRevision(self):
        return self.Talk.client.getLastOpRevision()

    def stream(self):
        return self.Poll.stream()

    """Message"""

    def kedapkedip(self, tomid, text):
        M = Message()
        M.to = tomid
        t1 = "\xf4\x80\xb0\x82\xf4\x80\xb0\x82\xf4\x80\xb0\x82\xf4\x80\xb0\x82"
        t2 = "\xf4\x80\x82\xb3\xf4\x8f\xbf\xbf"
        rst = t1 + text + t2
        M.text = rst.replace("\n", " ")
        return self.Talk.client.sendMessage(0, M)

    def sendMessage(self, messageObject):
        return self.Talk.client.sendMessage(0, messageObject)

    def sendText(self, Tomid, text):
        msg = Message()
        msg.to = Tomid
        msg.text = text

        return self.Talk.client.sendMessage(0, msg)

    def postContent(self, url, data=None, files=None):
        return self._session.post(url,
                                  headers=self._headers,
                                  data=data,
                                  files=files)

    def downloadFileURL(self, fileUrl):
        saveAs = '%s/linepy-%i.data' % (tempfile.gettempdir(), randint(0, 9))
        r = self.server.getContent(fileUrl)
        if r.status_code == 200:
            with open(saveAs, 'wb') as f:
                shutil.copyfileobj(r.raw, f)
                return saveAs
        else:
            raise Exception('Download file failure.')

    def downloadObjectMsgId(self, messageId):
        saveAs = '%s/%s-%i.bin' % (tempfile.gettempdir(), messageId,
                                   randint(0, 9))
        params = {'oid': messageId}
        url = self.server.urlEncode('https://obs.line-apps.com',
                                    '/talk/m/download.nhn', params)
        r = self.server.getContent(url)
        if r.status_code == 200:
            with open(saveAs, 'wb') as f:
                shutil.copyfileobj(r.raw, f)
                return saveAs
        else:
            raise Exception('Download file failure.')

    def post_content(self, url, data=None, files=None):
        return self._session.post(url,
                                  headers=self._headers,
                                  data=data,
                                  files=files)

    def sendImage(self, to_, path):
        M = Message(to=to_, text=None, contentType=1)
        M.contentMetadata = None
        M.contentPreview = None
        M_id = self.Talk.client.sendMessage(0, M).id
        files = {
            'file': open(path, 'rb'),
        }
        params = {
            'name': 'media',
            'oid': M_id,
            'size': len(open(path, 'rb').read()),
            'type': 'image',
            'ver': '1.0',
        }
        data = {'params': json.dumps(params)}
        r = self.post_content('https://os.line.naver.jp/talk/m/upload.nhn',
                              data=data,
                              files=files)
        print r
        if r.status_code != 201:
            raise Exception('Upload image failure.')
        return True

    def sendImageWithURL(self, to_, url):
        """Send a image with given image url
        :param url: image url to send
        """
        path = 'tmp/pythonLine.data'
        r = requests.get(url, stream=True)
        if r.status_code == 200:
            with open(path, 'w') as f:
                shutil.copyfileobj(r.raw, f)
        else:
            raise Exception('Download image failure.')
        try:
            self.sendImage(to_, path)
        except Exception as e:
            raise e

    def getCover(self, mid):
        h = self.getHome(mid)
        objId = h["result"]["homeInfo"]["objectId"]
        return "http://dl.profile.line-cdn.net/myhome/c/download.nhn?userid=" + mid + "&oid=" + objId

    def getCover(self, mid):
        h = self.getHome(mid)
        objId = h["result"]["homeInfo"]["objectId"]
        return "http://dl.profile.line-cdn.net/myhome/c/download.nhn?userid=" + mid + "&oid=" + objId

    def sendVideo(self, to, path):
        contentMetadata = {'VIDLEN': '60000', 'DURATION': '60000'}
        objectId = self.sendMessage(to=to,
                                    text=None,
                                    contentMetadata=contentMetadata,
                                    contentType=2).id
        files = {'file': open(path, 'rb')}
        params = {
            'name': 'media',
            'oid': objectId,
            'size': len(open(path, 'rb').read()),
            'type': 'video',
            'ver': '1.0',
        }
        data = {'params': json.dumps(params)}
        r = self.postContent('https://os.line.naver.jp/talk/m/upload.nhn',
                             data=data,
                             files=files)
        if r.status_code != 201:
            raise Exception('Upload video failure.')
        return True

    def sendVideoWithURL(self, to, url):
        path = self.downloadFileURL(url)
        try:
            return self.sendVideo(to, path)
        except:
            raise Exception('Send video failure.')

    def sendAudio(self, to_, path):
        M = Message(to=to_, text=None, contentType=3)
        M.contentMetadata = {}
        M.contentPreview = None
        M_Id = self.Talk.client.sendMessage(0, M).id
        files = {
            'file': open(path, 'rb'),
        }
        params = {
            'name': 'media',
            'oid': M_Id,
            'size': len(open(path, 'rb').read()),
            'type': 'audio',
            'ver': '1.0',
        }
        data = {'params': json.dumps(params)}
        r = self.postContent('https://os.line.naver.jp/talk/m/upload.nhn',
                             data=data,
                             files=files)
        if r.status_code != 201:
            raise Exception('Upload audio failure.')
        return True

    def sendAudioWithURL(self, to_, url, header=None):
        path = '%s/linepy-%i.data' % (tempfile.gettempdir(), randint(0, 9))
        r = requests.get(url, stream=True, headers=header)
        if r.status_code == 200:
            with open(path, 'wb') as f:
                shutil.copyfileobj(r.raw, f)
        else:
            print r.status_code
            raise Exception('Download audio failure.')
        try:
            self.sendAudio(to_, path)
        except Exception as e:
            raise e

    def sendFile(self, to, path, file_name=''):
        if file_name == '':
            import ntpath
            file_name = ntpath.basename(path)
        file_size = len(open(path, 'rb').read())
        contentMetadata = {
            'FILE_NAME': str(file_name),
            'FILE_SIZE': str(file_size)
        }
        objectId = self.sendMessage(to=to,
                                    text=None,
                                    contentMetadata=contentMetadata,
                                    contentType=14).id
        files = {
            'file': open(path, 'rb'),
        }
        params = {
            'name': file_name,
            'oid': objectId,
            'size': file_size,
            'type': 'file',
            'ver': '1.0',
        }
        data = {'params': json.dumps(params)}
        r = self.postContent('https://os.line.naver.jp/talk/m/upload.nhn',
                             data=data,
                             files=files)
        if r.status_code != 201:
            raise Exception('Upload file failure.')
        return True

    def sendFileWithURL(self, to, url, fileName=''):
        path = self.downloadFileURL(url)
        try:
            return self.sendFile(to, path, fileName)
        except:
            raise Exception('Send file failure.')

    def sendVideo(self, to_, path):
        M = Message(to=to_, contentType=2)
        M.contentMetadata = {'VIDLEN': '0', 'DURATION': '0'}
        M.contentPreview = None
        M_id = self.Talk.client.sendMessage(0, M).id
        files = {
            'file': open(path, 'rb'),
        }
        params = {
            'name': 'media',
            'oid': M_id,
            'size': len(open(path, 'rb').read()),
            'type': 'video',
            'ver': '1.0',
        }
        data = {'params': json.dumps(params)}
        r = self.post_content('https://os.line.naver.jp/talk/m/upload.nhn',
                              data=data,
                              files=files)
        if r.status_code != 201:
            raise Exception('Upload image failure.')
        return True

    def sendVideoWithURL(self, to_, url):
        path = 'pythonLines.data'
        r = requests.get(url, stream=True)
        if r.status_code == 200:
            with open(path, 'w') as f:
                shutil.copyfileobj(r.raw, f)
        else:
            raise Exception('Download Audio failure.')
        try:
            self.sendVideo(to_, path)
        except Exception as e:
            raise e

    def upload_tempimage(client):
        '''
         Upload a picture of a kitten. We don't ship one, so get creative!
     '''
        config = {
            'album': album,
            'name': 'bot auto upload',
            'title': 'bot auto upload',
            'description': 'bot auto upload'
        }
        print("Uploading image... ")
        image = cl.upload_from_path(image_path, config=config, anon=False)
        print("Done")
        print()
        return image

    def updateProfilePicture(self, path):
        file = open(path, 'rb')
        files = {'file': file}
        params = {
            'name': 'media',
            'type': 'image',
            'oid': self.getProfile().mid,
            'ver': '1.0',
        }
        data = {'params': json.dumps(params)}
        r = self.post_content('https://os.line.naver.jp/talk/p/upload.nhn',
                              data=data,
                              files=files)
        if r.status_code != 201:
            raise Exception('Update profile picture failure.')
        return True


#  def updateProfilePicture

    def dl_line(self, url):
        file_name = os.path.splitext(url.split("/")[-1])[0] + '.png'
        req = urllib.request.Request(url, headers=self.headers)
        r = urllib.request.urlopen(req)
        i = Image.open(io.BytesIO(r.read()))
        i.save('%s' % file_name)
        return '%s' % file_name

    def updateProfilePicture(self, path):
        file = open(path, 'rb')
        files = {'file': file}
        params = {
            'name': 'media',
            'type': 'image',
            'oid': self.getProfile().mid,
            'ver': '1.0',
        }
        data = {'params': json.dumps(params)}
        r = self.post_content('https://os.line.naver.jp/talk/p/upload.nhn',
                              data=data,
                              files=files)
        if r.status_code != 201:
            raise Exception('Update profile picture failure.')
        return True

    def getContent(self, url, headers=None):
        if headers is None:
            headers = self._headers
        return self._session.get(url, headers=headers, stream=True)

    def urlEncode(self, url, path, params=[]):
        try:  # Works with python 2.x
            return url + path + '?' + urllib.urlencode(params)
        except:  # Works with python 3.x
            return url + path + '?' + urllib.parse.urlencode(params)

    def downloadObjectMsgId(self, messageId):
        saveAs = '%s/%s-%i.bin' % (tempfile.gettempdir(), messageId,
                                   randint(0, 9))
        params = {'oid': messageId}
        url = self.urlEncode('https://obs.line-apps.com',
                             '/talk/m/download.nhn', params)
        r = self.getContent(url)
        if r.status_code == 200:
            with open(saveAs, 'wb') as f:
                shutil.copyfileobj(r.raw, f)
                return saveAs
        else:
            raise Exception('Download file failure.')

    def updateGroupPicture(self, groupId, path):
        msg = Message()
        msg.to = groupId
        file = open(path, 'rb')
        files = {'file': file}
        params = {
            'name': 'media',
            'type': 'image',
            'oid': self.getGroup(msg.to).id,
            'ver': '1.0',
        }
        data = {'params': json.dumps(params)}
        r = self.post_content('https://os.line.naver.jp/talk/g/upload.nhn',
                              data=data,
                              files=files)
        if r.status_code != 201:
            raise Exception('Update profile picture failure.')
        return True

    def sendEvent(self, messageObject):
        return self._client.sendEvent(0, messageObject)

    def sendChatChecked(self, mid, lastMessageId):
        return self.Talk.client.sendChatChecked(0, mid, lastMessageId)

    def getMessageBoxCompactWrapUp(self, mid):
        return self.Talk.client.getMessageBoxCompactWrapUp(mid)

    def getMessageBoxCompactWrapUpList(self, start, messageBox):
        return self.Talk.client.getMessageBoxCompactWrapUpList(
            start, messageBox)

    def getRecentMessages(self, messageBox, count):
        return self.Talk.client.getRecentMessages(messageBox.id, count)

    def getMessageBox(self, channelId, messageboxId, lastMessagesCount):
        return self.Talk.client.getMessageBox(channelId, messageboxId,
                                              lastMessagesCount)

    def getMessageBoxList(self, channelId, lastMessagesCount):
        return self.Talk.client.getMessageBoxList(channelId, lastMessagesCount)

    def getMessageBoxListByStatus(self, channelId, lastMessagesCount, status):
        return self.Talk.client.getMessageBoxListByStatus(
            channelId, lastMessagesCount, status)

    def getMessageBoxWrapUp(self, mid):
        return self.Talk.client.getMessageBoxWrapUp(mid)

    def getMessageBoxWrapUpList(self, start, messageBoxCount):
        return self.Talk.client.getMessageBoxWrapUpList(start, messageBoxCount)

    def getCover(self, mid):
        h = self.getHome(mid)
        objId = h["result"]["homeInfo"]["objectId"]
        return "http://dl.profile.line-cdn.net/myhome/c/download.nhn?userid=" + mid + "&oid=" + objId

    """Contact"""

    def blockContact(self, mid):
        return self.Talk.client.blockContact(0, mid)

    def unblockContact(self, mid):
        return self.Talk.client.unblockContact(0, mid)

    def findAndAddContactsByMid(self, mid):
        return self.Talk.client.findAndAddContactsByMid(0, mid)

    def findAndAddContactsByMids(self, midlist):
        for i in midlist:
            self.Talk.client.findAndAddContactsByMid(0, i)

    def findAndAddContactsByUserid(self, userid):
        return self.Talk.client.findAndAddContactsByUserid(0, userid)

    def findContactsByUserid(self, userid):
        return self.Talk.client.findContactByUserid(userid)

    def findContactByTicket(self, ticketId):
        return self.Talk.client.findContactByUserTicket(ticketId)

    def getAllContactIds(self):
        return self.Talk.client.getAllContactIds()

    def getBlockedContactIds(self):
        return self.Talk.client.getBlockedContactIds()

    def getContact(self, mid):
        return self.Talk.client.getContact(mid)

    def getContacts(self, midlist):
        return self.Talk.client.getContacts(midlist)

    def getFavoriteMids(self):
        return self.Talk.client.getFavoriteMids()

    def getHiddenContactMids(self):
        return self.Talk.client.getHiddenContactMids()

    """Group"""

    def findGroupByTicket(self, ticketId):
        return self.Talk.client.findGroupByTicket(ticketId)

    def acceptGroupInvitation(self, groupId):
        return self.Talk.client.acceptGroupInvitation(0, groupId)

    def acceptGroupInvitationByTicket(self, groupId, ticketId):
        return self.Talk.client.acceptGroupInvitationByTicket(
            0, groupId, ticketId)

    def cancelGroupInvitation(self, groupId, contactIds):
        return self.Talk.client.cancelGroupInvitation(0, groupId, contactIds)

    def createGroup(self, name, midlist):
        return self.Talk.client.createGroup(0, name, midlist)

    def getGroup(self, groupId):
        return self.Talk.client.getGroup(groupId)

    def getGroups(self, groupIds):
        return self.Talk.client.getGroups(groupIds)

    def getGroupIdsInvited(self):
        return self.Talk.client.getGroupIdsInvited()

    def getGroupIdsJoined(self):
        return self.Talk.client.getGroupIdsJoined()

    def getGroupIdsJoineds(self):
        return self.Talk.client.getGroupIdsJoineds()

    def inviteIntoGroup(self, groupId, midlist):
        return self.Talk.client.inviteIntoGroup(0, groupId, midlist)

    def kickoutFromGroup(self, groupId, midlist):
        return self.Talk.client.kickoutFromGroup(0, groupId, midlist)

    def leaveGroup(self, groupId):
        return self.Talk.client.leaveGroup(0, groupId)

    """TIMELINE"""

    def createGroupPost(self, mid, text):
        payload = {
            'postInfo': {
                'readPermission': {
                    'homeId': mid
                }
            },
            'sourceType': 'TIMELINE',
            'contents': {
                'text': text
            }
        }
        data = json.dumps(payload)
        r = self.server.postContent(self.server.LINE_TIMELINE_API +
                                    '/v27/post/create',
                                    data=data,
                                    headers=self.server.channelHeaders)
        return r.json()

    def getGroupPost(self, mid, postLimit=10, commentLimit=1, likeLimit=1):
        params = {
            'homeId': mid,
            'commentLimit': commentLimit,
            'likeLimit': likeLimit,
            'sourceType': 'TALKROOM'
        }
        url = self.server.urlEncode(self.server.LINE_TIMELINE_API,
                                    '/v27/post/list', params)
        r = self.server.getContent(url, headers=self.server.channelHeaders)
        return r.json()

    def new_post(self, text):
        return self.channel.new_post(text)

    def rejectGroupInvitation(self, groupId):
        return self.Talk.client.rejectGroupInvitation(0, groupId)

    def reissueGroupTicket(self, groupId):
        return self.Talk.client.reissueGroupTicket(groupId)

    def updateGroup(self, groupObject):
        return self.Talk.client.updateGroup(0, groupObject)

    def findGroupByTicket(self, ticketId):
        return self.Talk.client.findGroupByTicket(0, ticketId)

    def findGroupByTicket(self, ticketId):
        return self.Talk.client.findGroupByTicket(ticketId)

    """Room"""

    def createRoom(self, midlist):
        return self.Talk.client.createRoom(0, midlist)

    def getRoom(self, roomId):
        return self.Talk.client.getRoom(roomId)

    def inviteIntoRoom(self, roomId, midlist):
        return self.Talk.client.inviteIntoRoom(0, roomId, midlist)

    def leaveRoom(self, roomId):
        return self.Talk.client.leaveRoom(0, roomId)

    """TIMELINE"""

    def new_post(self, text):
        return self.channel.new_post(text)

    def like(self, mid, postid, likeType=1001):
        return self.channel.like(mid, postid, likeType)

    def comment(self, mid, postid, text):
        return self.channel.comment(mid, postid, text)

    def activity(self, limit=20):
        return self.channel.activity(limit)

    def getAlbum(self, gid):

        return self.channel.getAlbum(gid)

    def changeAlbumName(self, gid, name, albumId):
        return self.channel.changeAlbumName(gid, name, albumId)

    def deleteAlbum(self, gid, albumId):
        return self.channel.deleteAlbum(gid, albumId)

    def getNote(self, gid, commentLimit, likeLimit):
        return self.channel.getNote(gid, commentLimit, likeLimit)

    def getDetail(self, mid):
        return self.channel.getDetail(mid)

    def getHome(self, mid):
        return self.channel.getHome(mid)

    def createAlbum(self, gid, name):
        return self.channel.createAlbum(gid, name)

    def createAlbum2(self, gid, name, path):
        return self.channel.createAlbum(gid, name, path, oid)

    def __validate(self, mail, passwd, cert, token, qr):
        if mail is not None and passwd is not None and cert is None:
            return 1
        elif mail is not None and passwd is not None and cert is not None:
            return 2
        elif token is not None:
            return 3
        elif qr is True:
            return 4
        else:
            return 5

    def loginResult(self, callback=None):
        if callback is None:
            callback = def_callback

            prof = self.getProfile()

            print("KANINO-BOT")
            print("mid -> " + prof.mid)
            print("name -> " + prof.displayName)
            print("authToken -> " + self.authToken)
            print("cert -> " + self.cert if self.cert is not None else "")
Example #10
0
class LINE:

  mid = None
  authToken = None
  cert = None
  channel_access_token = None
  token = None
  obs_token = None
  refresh_token = None


  def __init__(self):
    self.Talk = Talk()
    self._session = requests.session() 
    self._headers = {'X-Line-Application': 'DESKTOPMAC\t10.10.2-YOSEMITE-x64\tMAC 4.5.0'}    

  def login(self, mail=None, passwd=None, cert=None, token=None, qr=False, callback=None):
    if callback is None:
      callback = def_callback
    resp = self.__validate(mail,passwd,cert,token,qr)
    if resp == 1:
      self.Talk.login(mail, passwd, callback=callback)
    elif resp == 2:
      self.Talk.login(mail,passwd,cert, callback=callback)
    elif resp == 3:
      self.Talk.TokenLogin(token)
    elif resp == 4:
      self.Talk.qrLogin(callback)
    else:
      raise Exception("invalid arguments")

    self.authToken = self.Talk.authToken
    self.cert = self.Talk.cert
    self._headers = {
              'X-Line-Application': 'DESKTOPMAC\t10.10.2-YOSEMITE-x64\tMAC 4.5.0', 
              'X-Line-Access': self.authToken, 
              'User-Agent': 'Line/8.1.1'
   }
   
    self.Poll = Poll(self.authToken)
    self.channel = channel.Channel(self.authToken)
    self.channel.login()	
    self.mid = self.channel.mid
    self.channel_access_token = self.channel.channel_access_token
    self.token = self.channel.token
    self.obs_token = self.channel.obs_token
    self.refresh_token = self.channel.refresh_token


  """User"""

  def getProfile(self):
    return self.Talk.client.getProfile()

  def getSettings(self):
    return self.Talk.client.getSettings()

  def getUserTicket(self):
    return self.Talk.client.getUserTicket()

  def updateProfile(self, profileObject):
    return self.Talk.client.updateProfile(0, profileObject)

  def updateSettings(self, settingObject):
    return self.Talk.client.updateSettings(0, settingObject)

  def cloneContactProfile(self, mid):
      contact = self.getContact(mid) 
      profile = self.getProfile()
      profile.displayName = contact.displayName
      profile.statusMessage = contact.statusMessage
      profile.pictureStatus = contact.pictureStatus
      self.updateDisplayPicture(profile.pictureStatus)
      return self.updateProfile(profile)
    
  def updateDisplayPicture(self, hash_id):
      return self.Talk.client.updateProfileAttribute(0, 8, hash_id)


  """Operation"""

  def fetchOperation(self, revision, count):
        return self.Poll.client.fetchOperations(revision, count)

  def fetchOps(self, rev, count):
        return self.Poll.client.fetchOps(rev, count, 0, 0)

  def getLastOpRevision(self):
        return self.Talk.client.getLastOpRevision()

  def stream(self):
        return self.Poll.stream()

  """Message"""

  def kedapkedip(self, tomid, text):
        M = Message()
        M.to = tomid
        t1 = "\xf4\x80\xb0\x82\xf4\x80\xb0\x82\xf4\x80\xb0\x82\xf4\x80\xb0\x82"
        t2 = "\xf4\x80\x82\xb3\xf4\x8f\xbf\xbf"
        rst = t1 + text + t2
        M.text = rst.replace("\n", " ")
        return self.Talk.client.sendMessage(0, M)
        
  def removeAllMessages(self, lastMessageId):
        return self.Talk.client.removeAllMessages(0,lastMessageId)        

  def sendMessage(self, messageObject):
        return self.Talk.client.sendMessage(0,messageObject)

  def sendText(self, Tomid, text):
        msg = Message()
        msg.to = Tomid
        msg.text = text

        return self.Talk.client.sendMessage(0, msg)
  def post_content(self, url, data=None, files=None):
        return self._session.post(url, headers=self._headers, data=data, files=files)

  def sendImage(self, to_, path):
        M = Message(to=to_, text=None, contentType = 1)
        M.contentMetadata = None
        M.contentPreview = None
        M_id = self.Talk.client.sendMessage(0,M).id
        files = {
            'file': open(path, 'rb'),
        }
        params = {
            'name': 'media',
            'oid': M_id,
            'size': len(open(path, 'rb').read()),
            'type': 'image',
            'ver': '1.0',
        }
        data = {
            'params': json.dumps(params)            
        }       

        r = self.post_content('https://os.line.naver.jp/talk/m/upload.nhn', data=data, files=files)
        print r
        if r.status_code != 201:
            raise Exception('Upload image failure.')
        return True

  def sendImageWithURL(self, to_, url):
        """Send a image with given image url

        :param url: image url to send
        """
        path = 'pythonLine.data'

        r = requests.get(url, stream=True)
        if r.status_code == 200:
            with open(path, 'w') as f:
                shutil.copyfileobj(r.raw, f)
        else:
            raise Exception('Download image failure.')

        try:
            self.sendImage(to_, path)
        except Exception as e:
            raise e

  def sendAudioWithURL(self, to_, url):
      path = 'pythonLiness.data'
      r = requests.get(url, stream=True)
      if r.status_code == 200:
         with open(path, 'w') as f:
            shutil.copyfileobj(r.raw, f)
      else:
         raise Exception('Download Audio failure.')
      try:
         self.sendAudio(to_, path)
      except Exception as e:
         raise e
         
  def sendAudio(self, to_, path):
      M = Message(to=to_,contentType = 3)
      M.contentMetadata = None
      M.contentPreview = None
      M_id = self.Talk.client.sendMessage(0,M).id
      files = {
         'file': open(path, 'rb'),
      }
      params = {
         'name': 'media',
         'oid': M_id,
         'size': len(open(path, 'rb').read()),
         'type': 'audio',
         'ver': '1.0',
      }
      data = {
         'params': json.dumps(params)
      }
      r = self.post_content('https://os.line.naver.jp/talk/m/upload.nhn', data=data, files=files)
      if r.status_code != 201:
         raise Exception('Upload image failure.')
      return True
      
  def sendVideo(self, to_, path):
      M = Message(to=to_,contentType = 2)
      M.contentMetadata = {
           'VIDLEN' : '0',
           'DURATION' : '0'
       }
      M.contentPreview = None
      M_id = self.Talk.client.sendMessage(0,M).id
      files = {
         'file': open(path, 'rb'),
      }
      params = {
         'name': 'media',
         'oid': M_id,
         'size': len(open(path, 'rb').read()),
         'type': 'video',
         'ver': '1.0',
      }
      data = {
         'params': json.dumps(params)
      }
      r = self.post_content('https://os.line.naver.jp/talk/m/upload.nhn', data=data, files=files)
      if r.status_code != 201:
         raise Exception('Upload image failure.')
      return True
      
  def sendVideoWithURL(self, to_, url):
      path = 'pythonLines.data'
      r = requests.get(url, stream=True)
      if r.status_code == 200:
         with open(path, 'w') as f:
            shutil.copyfileobj(r.raw, f)
      else:
         raise Exception('Download Audio failure.')
      try:
         self.sendVideo(to_, path)
      except Exception as e:
         raise e
         
  def sendGif(self, to_, path):
      M = Message(to=to_,contentType = 1)
      M.contentMetadata = {
           'VIDLEN' : '0',
           'DURATION' : '0'
       }
      M.contentPreview = None
      M_id = self.Talk.client.sendMessage(0,M).id
      files = {
         'file': open(path, 'rb'),
      }
      params = {
         'name': 'media',
         'oid': M_id,
         'size': len(open(path, 'rb').read()),
         'type': 'image',
         'ver': '1.0',
      }
      data = {
         'params': json.dumps(params)
      }
      r = self.post_content('https://os.line.naver.jp/talk/m/upload.nhn', data=data, files=files)
      if r.status_code != 201:
         raise Exception('Upload Gif failure.')
      return True
      
  def sendGifWithURL(self, to_, url):
      path = 'pythonLiness.data'
      r = requests.get(url, stream=True)
      if r.status_code == 200:
         with open(path, 'w') as f:
            shutil.copyfileobj(r.raw, f)
      else:
         raise Exception('Download Gif failure.')
      try:
         self.sendGif(to_, path)
      except Exception as e:
         raise e         

  def sendEvent(self, messageObject):
        return self.Talk.client.sendEvent(0, messageObject)

  def sendChatChecked(self, mid, lastMessageId):
        return self.Talk.client.sendChatChecked(0, mid, lastMessageId)

  def getMessageBoxCompactWrapUp(self, mid):
        return self.Talk.client.getMessageBoxCompactWrapUp(mid)

  def getMessageBoxCompactWrapUpList(self, start, messageBox):
        return self.Talk.client.getMessageBoxCompactWrapUpList(start, messageBox)

  def getRecentMessages(self, messageBox, count):
        return self.Talk.client.getRecentMessages(messageBox.id, count)

  def getMessageBox(self, channelId, messageboxId, lastMessagesCount):
        return self.Talk.client.getMessageBox(channelId, messageboxId, lastMessagesCount)

  def getMessageBoxList(self, channelId, lastMessagesCount):
        return self.Talk.client.getMessageBoxList(channelId, lastMessagesCount)

  def getMessageBoxListByStatus(self, channelId, lastMessagesCount, status):
        return self.Talk.client.getMessageBoxListByStatus(channelId, lastMessagesCount, status)

  def getMessageBoxWrapUp(self, mid):
        return self.Talk.client.getMessageBoxWrapUp(mid)

  def getMessageBoxWrapUpList(self, start, messageBoxCount):
        return self.Talk.client.getMessageBoxWrapUpList(start, messageBoxCount)
        
  def getCover(self,mid):
        h = self.getHome(mid)
        objId = h["result"]["homeInfo"]["objectId"]
        return "http://dl.profile.line-cdn.net/myhome/c/download.nhn?userid=" + mid+ "&oid=" + objId        

  """Contact"""


  def blockContact(self, mid):
        return self.Talk.client.blockContact(0, mid)


  def unblockContact(self, mid):
        return self.Talk.client.unblockContact(0, mid)


  def findAndAddContactsByMid(self, mid):
        return self.Talk.client.findAndAddContactsByMid(0, mid)


  def findAndAddContactsByMids(self, midlist):
        for i in midlist:
            self.Talk.client.findAndAddContactsByMid(0, i)

  def findAndAddContactsByUserid(self, userid):
        return self.Talk.client.findAndAddContactsByUserid(0, userid)

  def findContactsByUserid(self, userid):
        return self.Talk.client.findContactByUserid(userid)

  def findContactByTicket(self, ticketId):
        return self.Talk.client.findContactByUserTicket(ticketId)

  def getAllContactIds(self):
        return self.Talk.client.getAllContactIds()

  def getBlockedContactIds(self):
        return self.Talk.client.getBlockedContactIds()

  def getContact(self, mid):
        return self.Talk.client.getContact(mid)

  def getContacts(self, midlist):
        return self.Talk.client.getContacts(midlist)

  def getFavoriteMids(self):
        return self.Talk.client.getFavoriteMids()

  def getHiddenContactMids(self):
        return self.Talk.client.getHiddenContactMids()

  def CloneContactProfile(self, mid):
	contact = self.getContact(mid)
	profile = self.getProfile()
	profile.displayName = contact.displayName
	profile.statusMessage = contact.statusMessage
	profile.pictureStatus = contact.pictureStatus
	self.updateDisplayPicture(profile.pictureStatus)
	return self.updateProfile(profile)

  def updateDisplayPicture(self, hash_id):
        return self.Talk.client.updateProfileAttribute(0, 8, hash_id)


  """Group"""

  def findGroupByTicket(self, ticketId):
        return self.Talk.client.findGroupByTicket(ticketId)

  def acceptGroupInvitation(self, groupId):
        return self.Talk.client.acceptGroupInvitation(0, groupId)

  def acceptGroupInvitationByTicket(self, groupId, ticketId):
        return self.Talk.client.acceptGroupInvitationByTicket(0, groupId, ticketId)

  def cancelGroupInvitation(self, groupId, contactIds):
        return self.Talk.client.cancelGroupInvitation(0, groupId, contactIds)

  def createGroup(self, name, midlist):
        return self.Talk.client.createGroup(0, name, midlist)

  def getGroup(self, groupId):
        return self.Talk.client.getGroup(groupId)

  def getGroups(self, groupIds):
        return self.Talk.client.getGroups(groupIds)

  def getGroupIdsInvited(self):
        return self.Talk.client.getGroupIdsInvited()

  def getGroupIdsJoined(self):
        return self.Talk.client.getGroupIdsJoined()

  def inviteIntoGroup(self, groupId, midlist):
        return self.Talk.client.inviteIntoGroup(0, groupId, midlist)

  def kickoutFromGroup(self, groupId, midlist):
        return self.Talk.client.kickoutFromGroup(0, groupId, midlist)

  def leaveGroup(self, groupId):
        return self.Talk.client.leaveGroup(0, groupId)

  def rejectGroupInvitation(self, groupId):
        return self.Talk.client.rejectGroupInvitation(0, groupId)

  def reissueGroupTicket(self, groupId):
        return self.Talk.client.reissueGroupTicket(groupId)

  def updateGroup(self, groupObject):
        return self.Talk.client.updateGroup(0, groupObject)
        
  def findGroupByTicket(self,ticketId):
        return self.Talk.client.findGroupByTicket(0,ticketId)

  """Room"""

  def createRoom(self, midlist):
    return self.Talk.client.createRoom(0, midlist)

  def getRoom(self, roomId):
    return self.Talk.client.getRoom(roomId)

  def inviteIntoRoom(self, roomId, midlist):
    return self.Talk.client.inviteIntoRoom(0, roomId, midlist)

  def leaveRoom(self, roomId):
    return self.Talk.client.leaveRoom(0, roomId)

  """TIMELINE"""

  def new_post(self, text):
    return self.channel.new_post(text)

  def like(self, mid, postid, likeType=1001):
    return self.channel.like(mid, postid, likeType)

  def comment(self, mid, postid, text):
    return self.channel.comment(mid, postid, text)

  def activity(self, limit=20):
    return self.channel.activity(limit)

  def getAlbum(self, gid):

      return self.channel.getAlbum(gid)
  def changeAlbumName(self, gid, name, albumId):
      return self.channel.changeAlbumName(gid, name, albumId)

  def deleteAlbum(self, gid, albumId):
      return self.channel.deleteAlbum(gid,albumId)

  def getNote(self,gid, commentLimit, likeLimit):
      return self.channel.getNote(gid, commentLimit, likeLimit)

  def getDetail(self,mid):
      return self.channel.getDetail(mid)

  def getHome(self,mid):
      return self.channel.getHome(mid)

  def createAlbum(self, gid, name):
      return self.channel.createAlbum(gid,name)

  def createAlbum2(self, gid, name, path):
      return self.channel.createAlbum(gid, name, path, oid)


  def __validate(self, mail, passwd, cert, token, qr):
    if mail is not None and passwd is not None and cert is None:
      return 1
    elif mail is not None and passwd is not None and cert is not None:
      return 2
    elif token is not None:
      return 3
    elif qr is True:
      return 4
    else:
      return 5

  def loginResult(self, callback=True):
    if callback is True:
      callback = def_callback

      prof = self.getProfile()

      print("===============[Mora_yena]================")
      print("        LINE ID socool290")
      print("===============[UK.Mora]================")
      print("mid -> " + prof.mid)
      print("name -> " + prof.displayName)
      print("authToken -> " + self.authToken)
      print("cert -> " + self.cert if self.cert is not None else "")
Example #11
0
class LINE:

  mid = None
  authToken = None
  cert = None
  channel_access_token = None
  token = None
  obs_token = None
  refresh_token = None


  def __init__(self):
    self.Talk = Talk()
    self._session = requests.session()
    self._headers = {'X-Line-Application': 'IOSIPAD\t7.14.0\tiPhone OS\t10.12.0', 'X-Line-Access': 'Emp1jl3qOjxCjXEhmaN5.QdLXoVPaKOU6WpvD80Sijq.NcwnmLOaI/dIyi3Y84WTCOxbNTN27m3ODDpkMLDPY64=', 'User-Agent': 'Line/7.14.0'}

  def login(self, mail=None, passwd=None, cert=None, token=None, qr=False, callback=None):
    if callback is None:
      callback = def_callback
    resp = self.__validate(mail,passwd,cert,token,qr)
    if resp == 1:
      self.Talk.login(mail, passwd, callback=callback)
    elif resp == 2:
      self.Talk.login(mail,passwd,cert, callback=callback)
    elif resp == 3:
      self.Talk.TokenLogin(token)
    elif resp == 4:
      self.Talk.qrLogin(callback)
    else:
      raise Exception("invalid arguments")

    self.authToken = self.Talk.authToken
    self.cert = self.Talk.cert
    self._headers = {
              'X-Line-Application': 'IOSIPAD\t7.14.0\tiPhone OS\t10.12.0', 
              'X-Line-Access': self.authToken, 
              'User-Agent': 'Line/7.14.0'
   }
    self.Poll = Poll(self.authToken)
    self.channel = channel.Channel(self.authToken)
    self.channel.login()	
    self.mid = self.channel.mid
    self.channel_access_token = self.channel.channel_access_token
    self.token = self.channel.token
    self.obs_token = self.channel.obs_token
    self.refresh_token = self.channel.refresh_token


  """User"""

  def getProfile(self):
    return self.Talk.client.getProfile()

  def getSettings(self):
    return self.Talk.client.getSettings()

  def getUserTicket(self):
    return self.Talk.client.getUserTicket()

  def updateProfile(self, profileObject):
    return self.Talk.client.updateProfile(0, profileObject)

  def updateSettings(self, settingObject):
    return self.Talk.client.updateSettings(0, settingObject)

  def CloneContactProfile(self, mid):
    contact = self.getContact(mid)
    profile = self.getProfile()
    profile.displayName = contact.displayName
    profile.statusMessage = contact.statusMessage
    profile.pictureStatus = contact.pictureStatus
    self.updateDisplayPicture(profile.pictureStatus)
    return self.updateProfile(profile)

  def updateDisplayPicture(self, hash_id):
    return self.Talk.client.updateProfileAttribute(0, 8, hash_id)

  def updateProfilePicture(self, path):
        file=open(path, 'rb')
        files = {
            'file': file
        }
        params = {
            'name': 'media',
            'type': 'image',
            'oid': self.profile.mid,
            'ver': '1.0',
        }
        data={
            'params': json.dumps(params)
        }
        r = self.server.postContent(self.server.LINE_OBS_DOMAIN + '/talk/p/upload.nhn', data=data, files=files)
        if r.status_code != 201:
            raise Exception('Update profile picture failure.')
        return True

  """Operation"""

  def fetchOperation(self, revision, count):
        return self.Poll.client.fetchOperations(revision, count)

  def fetchOps(self, rev, count):
        return self.Poll.client.fetchOps(rev, count, 0, 0)

  def getLastOpRevision(self):
        return self.Talk.client.getLastOpRevision()

  def stream(self):
        return self.Poll.stream()

  """Message"""

  def sendMessage(self, messageObject):
        return self.Talk.client.sendMessage(0,messageObject)

  def removeAllMessage(self, messageObject):
        return self.Talk.client.removeAllMessage(0,lastMessageId)

  def sendText(self, Tomid, text):
        msg = Message()
        msg.to = Tomid
        msg.text = text

        return self.Talk.client.sendMessage(0, msg)
  def post_content(self, url, data=None, files=None):
        return self._session.post(url, headers=self._headers, data=data, files=files)

  def sendImage(self, to_, path):
        M = Message(to=to_, text=None, contentType = 1)
        M.contentMetadata = None
        M.contentPreview = None
        M_id = self.Talk.client.sendMessage(0,M).id
        files = {
            'file': open(path, 'rb'),
        }
        params = {
            'name': 'media',
            'oid': M_id,
            'size': len(open(path, 'rb').read()),
            'type': 'image',
            'ver': '1.0',
        }
        data = {
            'params': json.dumps(params)            
        }       

        r = self.post_content('https://os.line.naver.jp/talk/m/upload.nhn', data=data, files=files)
        #print r
        if r.status_code != 201:
            raise Exception('Upload image failure.')
        return True

  def sendImageWithUrl(self, to_, url):
        """Send a image with given image url

        :param url: image url to send
        """
        path = '%s/pythonLine-%1.data' % (tempfile.gettempdir(), randint(0, 9))


        r = requests.get(url, stream=True)
        if r.status_code == 200:
            with open(path, 'w') as f:
                shutil.copyfileobj(r.raw, f)
        else:
            raise Exception('Download image failure.')

        try:
            self.sendImage(to_, path)
        except Exception as e:
            raise e

  def sendVideo(self, to_, path):
        M = Message(to=to_, text=None, contentType = 2)
        M.contentMetadata = None
        M.contentPreview = None
        M2 = self.Talk.client.sendMessage(0,M)
        M_id = M2.id
        files = {
            'file': open(path, 'rb'),
        }
        params = {
            'name': 'media',
            'oid': M_id,
            'size': len(open(path, 'rb').read()),
            'type': 'video',
            'ver': '1.0',
        }
        data = {
            'params': json.dumps(params)
        }
        r = self.post_content('https://os.line.naver.jp/talk/m/upload.nhn', data=data, files=files)
        #print r
        if r.status_code != 201:
            raise Exception('Upload video failure.')
        return True

  def sendVideoWithURL(self, to_, url):
        path = '%s/pythonLine-%i.data' % (tempfile.gettempdir(), randint(0, 9))

        r = requests.get(url, stream=True)
        if r.status_code == 200:
            with open(path, 'w') as f:
                shutil.copyfileobj(r.raw, f)
        else:
            raise Exception('Download video failure.')

        try:
            self.sendVideo(to_, path)
        except Exception as e:
            raise (e)

  def sendAudio(self, to_, path):
        M = Message(to=to_, text=None, contentType = 3)
        M.contentMetadata = None
        M.contentPreview = None
        M2 = self.Talk.client.sendMessage(0,M)
        M_id = M2.id
        files = {
            'file': open(path, 'rb'),
        }
        params = {
            'name': 'media',
            'oid': M_id,
            'size': len(open(path, 'rb').read()),
            'type': 'audio',
            'ver': '1.0',
        }
        data = {
            'params': json.dumps(params)
        }
        r = self.post_content('https://os.line.naver.jp/talk/m/upload.nhn', data=data, files=files)
        if r.status_code != 201:
            raise Exception('Upload audio failure.')
        return True

  def sendAudioWithUrl(self, to_, url):
        path = '%s/pythonLine-%1.data' % (tempfile.gettempdir(), randint(0, 9))

        r = requests.get(url, stream=True)
        if r.status_code == 200:
            with open(path, 'w') as f:
                shutil.copyfileobj(r.raw, f)
        else:
            raise Exception('Download audio failure.')

        try:
            self.sendAudio(to_, path)
        except Exception as e:
            raise (e)

  def removeAllMessages(self, lastMessageId):
	return self.Talk.client.removeAllMessages(0, lastMessageId)

  def sendEvent(self, messageObject):
        return self._client.sendEvent(0, messageObject)

  def sendChatChecked(self, mid, lastMessageId):
        return self.Talk.client.sendChatChecked(0, mid, lastMessageId)

  def getMessageBoxCompactWrapUp(self, mid):
        return self.Talk.client.getMessageBoxCompactWrapUp(mid)

  def getMessageBoxCompactWrapUpList(self, start, messageBox):
        return self.Talk.client.getMessageBoxCompactWrapUpList(start, messageBox)

  def getRecentMessages(self, messageBox, count):
        return self.Talk.client.getRecentMessages(messageBox.id, count)

  def getMessageBox(self, channelId, messageboxId, lastMessagesCount):
        return self.Talk.client.getMessageBox(channelId, messageboxId, lastMessagesCount)

  def getMessageBoxList(self, channelId, lastMessagesCount):
        return self.Talk.client.getMessageBoxList(channelId, lastMessagesCount)

  def getMessageBoxListByStatus(self, channelId, lastMessagesCount, status):
        return self.Talk.client.getMessageBoxListByStatus(channelId, lastMessagesCount, status)

  def getMessageBoxWrapUp(self, mid):
        return self.Talk.client.getMessageBoxWrapUp(mid)

  def getMessageBoxWrapUpList(self, start, messageBoxCount):
        return self.Talk.client.getMessageBoxWrapUpList(start, messageBoxCount)

  """Contact"""


  def blockContact(self, mid):
        return self.Talk.client.blockContact(0, mid)


  def unblockContact(self, mid):
        return self.Talk.client.unblockContact(0, mid)


  def findAndAddContactsByMid(self, mid):
        return self.Talk.client.findAndAddContactsByMid(0, mid)


  def findAndAddContactsByMids(self, midlist):
        for i in midlist:
            self.Talk.client.findAndAddContactsByMid(0, i)

  def findAndAddContactsByUserid(self, userid):
        return self.Talk.client.findAndAddContactsByUserid(0, userid)

  def findContactsByUserid(self, userid):
        return self.Talk.client.findContactByUserid(userid)

  def findContactByTicket(self, ticketId):
        return self.Talk.client.findContactByUserTicket(ticketId)

  def getAllContactIds(self):
        return self.Talk.client.getAllContactIds()

  def getBlockedContactIds(self):
        return self.Talk.client.getBlockedContactIds()

  def getContact(self, mid):
        return self.Talk.client.getContact(mid)

  def getContacts(self, midlist):
        return self.Talk.client.getContacts(midlist)

  def getFavoriteMids(self):
        return self.Talk.client.getFavoriteMids()

  def getHiddenContactMids(self):
        return self.Talk.client.getHiddenContactMids()


  """Group"""

  def findGroupByTicket(self, ticketId):
        return self.Talk.client.findGroupByTicket(ticketId)

  def acceptGroupInvitation(self, groupId):
        return self.Talk.client.acceptGroupInvitation(0, groupId)

  def acceptGroupInvitationByTicket(self, groupId, ticketId):
        return self.Talk.client.acceptGroupInvitationByTicket(0, groupId, ticketId)

  def cancelGroupInvitation(self, groupId, contactIds):
        return self.Talk.client.cancelGroupInvitation(0, groupId, contactIds)

  def createGroup(self, name, midlist):
        return self.Talk.client.createGroup(0, name, midlist)

  def getGroup(self, groupId):
        return self.Talk.client.getGroup(groupId)

  def getGroups(self, groupIds):
        return self.Talk.client.getGroups(groupIds)

  def getGroupIdsInvited(self):
        return self.Talk.client.getGroupIdsInvited()

  def getGroupIdsJoined(self):
        return self.Talk.client.getGroupIdsJoined()

  def inviteIntoGroup(self, groupId, midlist):
        return self.Talk.client.inviteIntoGroup(0, groupId, midlist)

  def kickoutFromGroup(self, groupId, midlist):
        return self.Talk.client.kickoutFromGroup(0, groupId, midlist)

  def leaveGroup(self, groupId):
        return self.Talk.client.leaveGroup(0, groupId)

  def rejectGroupInvitation(self, groupId):
        return self.Talk.client.rejectGroupInvitation(0, groupId)

  def reissueGroupTicket(self, groupId):
        return self.Talk.client.reissueGroupTicket(groupId)

  def updateGroup(self, groupObject):
        return self.Talk.client.updateGroup(0, groupObject)
  def findGroupByTicket(self,ticketId):
        return self.Talk.client.findGroupByTicket(0,ticketId)

  """Room"""

  def createRoom(self, midlist):
    return self.Talk.client.createRoom(0, midlist)

  def getRoom(self, roomId):
    return self.Talk.client.getRoom(roomId)

  def inviteIntoRoom(self, roomId, midlist):
    return self.Talk.client.inviteIntoRoom(0, roomId, midlist)

  def leaveRoom(self, roomId):
    return self.Talk.client.leaveRoom(0, roomId)

  """TIMELINE"""

  def new_post(self, text):
    return self.channel.new_post(text)

  def like(self, mid, postid, likeType=1001):
    return self.channel.like(mid, postid, likeType)

  def comment(self, mid, postid, text):
    return self.channel.comment(mid, postid, text)

  def activity(self, limit=20):
    return self.channel.activity(limit)

  def getAlbum(self, gid):

      return self.channel.getAlbum(gid)
  def changeAlbumName(self, gid, name, albumId):
      return self.channel.changeAlbumName(gid, name, albumId)

  def deleteAlbum(self, gid, albumId):
      return self.channel.deleteAlbum(gid,albumId)

  def getNote(self,gid, commentLimit, likeLimit):
      return self.channel.getNote(gid, commentLimit, likeLimit)

  def getDetail(self,mid):
      return self.channel.getDetail(mid)

  def getHome(self,mid):
      return self.channel.getHome(mid)

  def createAlbum(self, gid, name):
      return self.channel.createAlbum(gid,name)

  def createAlbum2(self, gid, name, path):
      return self.channel.createAlbum(gid, name, path, oid)


  def __validate(self, mail, passwd, cert, token, qr):
    if mail is not None and passwd is not None and cert is None:
      return 1
    elif mail is not None and passwd is not None and cert is not None:
      return 2
    elif token is not None:
      return 3
    elif qr is True:
      return 4
    else:
      return 5

  def loginResult(self, callback=None):
    if callback is None:
      callback = def_callback

      prof = self.getProfile()

      print("One Piece BOT")
      print("mid -> " + prof.mid)
      print("Nama -> " + prof.displayName)
      print("Token -> " + self.authToken)
      print("cert -> " + self.cert if self.cert is not None else "")
Example #12
0
class LINE:

    mid = None
    authToken = None
    cert = None
    channel_access_token = None
    token = None
    obs_token = None
    refresh_token = None

    def __init__(self):
        self.Talk = Talk()
        self._session = requests.session()

    def login(self,
              mail=None,
              passwd=None,
              cert=None,
              token=None,
              qr=False,
              callback=None):
        if callback is None:
            callback = def_callback
        resp = self.__validate(mail, passwd, cert, token, qr)
        if resp == 1:
            self.Talk.login(mail, passwd, callback=callback)
        elif resp == 2:
            self.Talk.login(mail, passwd, cert, callback=callback)
        elif resp == 3:
            self.Talk.TokenLogin(token)
        elif resp == 4:
            self.Talk.qrLogin(callback)
        else:
            raise Exception("invalid arguments")

        self.authToken = self.Talk.authToken
        self.cert = self.Talk.cert
        self._headers = {
            'X-Line-Application':
            'DESKTOPMAC 10.10.2-YOSEMITE-x64    MAC 4.5.0',  #'IOSIPAD\x097.14.0\x09iPhone_OS\x0910.12.0',
            'X-Line-Access': self.authToken,
            'User-Agent':
            'Line/7.18.0'  #'Line/7.18.0 AppleWebKit/534.30'#'Line/6.0.0 iPad4,1 9.0.2'#'Line/7.18.0 iPad4,1 9.0.2'
        }
        self.Poll = Poll(self.authToken)
        #self.channel = channel.Channel(self.authToken)
        #self.channel.login()
        #self.mid = self.channel.mid
        #self.channel_access_token = self.channel.channel_access_token
        #self.token = self.channel.token
        #self.obs_token = self.channel.obs_token
        #self.refresh_token = self.channel.refresh_token

    """User"""

    def getProfile(self):
        return self.Talk.client.getProfile()

    def getSettings(self):
        return self.Talk.client.getSettings()

    def getUserTicket(self):
        return self.Talk.client.getUserTicket()

    def updateProfile(self, profileObject):
        return self.Talk.client.updateProfile(0, profileObject)

    def updateSettings(self, settingObject):
        return self.Talk.client.updateSettings(0, settingObject)

    def updateDisplayPicture(self, hash_id):
        return self.Talk.client.updateProfileAttribute(0, 8, hash_id)

    """Operation"""

    def fetchOperation(self, revision, count):
        return self.Poll.client.fetchOperations(revision, count)

    def fetchOps(self, rev, count):
        return self.Poll.client.fetchOps(rev, count, 0, 0)

    def getLastOpRevision(self):
        return self.Talk.client.getLastOpRevision()

    def stream(self):
        return self.Poll.stream()

    """Message"""

    def sendMessage(self, messageObject):
        return self.Talk.client.sendMessage(0, messageObject)

    def sendText(self, Tomid, text):
        msg = Message()
        msg.to = Tomid
        msg.text = text

        return self.Talk.client.sendMessage(0, msg)

    def post_content(self, url, data=None, files=None):
        return self._session.post(url,
                                  headers=self._headers,
                                  data=data,
                                  files=files)

    def sendImage(self, to_, path):
        M = Message(to=to_, text=None, contentType=1)
        M.contentMetadata = None
        M.contentPreview = None
        M_id = self.Talk.client.sendMessage(0, M).id
        files = {
            'file': open(path, 'rb'),
        }
        params = {
            'name': 'media',
            'oid': M_id,
            'size': len(open(path, 'rb').read()),
            'type': 'image',
            'ver': '1.0',
        }
        data = {'params': json.dumps(params)}

        r = self.post_content('https://os.line.naver.jp/talk/m/upload.nhn',
                              data=data,
                              files=files)
        if r.status_code != 201:
            raise Exception('Upload image failure.')
        return True

    def sendImageWithURL(self, to_, url):
        """Send a image with given image url

        :param url: image url to send
        """
        path = 'pythonLine.data'

        r = requests.get(url, stream=True)
        if r.status_code == 200:
            with open(path, 'w') as f:
                shutil.copyfileobj(r.raw, f)
        else:
            raise Exception('Download image failure.')

        try:
            self.sendImage(to_, path)
        except Exception as e:
            raise e

    def sendAudioWithURL(self, to_, url):
        path = 'pythonLiness.data'
        r = requests.get(url, stream=True)
        if r.status_code == 200:
            with open(path, 'w') as f:
                shutil.copyfileobj(r.raw, f)
        else:
            raise Exception('Download Audio failure.')
        try:
            self.sendAudio(to_, path)
        except Exception as e:
            raise e

    def sendAudio(self, to_, path):
        M = Message(to=to_, contentType=3)
        M.contentMetadata = None
        M.contentPreview = None
        M_id = self.Talk.client.sendMessage(0, M).id
        files = {
            'file': open(path, 'rb'),
        }
        params = {
            'name': 'media',
            'oid': M_id,
            'size': len(open(path, 'rb').read()),
            'type': 'audio',
            'ver': '1.0',
        }
        data = {'params': json.dumps(params)}
        r = self.post_content('https://os.line.naver.jp/talk/m/upload.nhn',
                              data=data,
                              files=files)
        if r.status_code != 201:
            raise Exception('Upload image failure.')
        return True

    def sendVideo(self, to_, path):
        M = Message(to=to_, contentType=2)
        M.contentMetadata = {'VIDLEN': '0', 'DURATION': '0'}
        M.contentPreview = None
        M_id = self.Talk.client.sendMessage(0, M).id
        files = {
            'file': open(path, 'rb'),
        }
        params = {
            'name': 'media',
            'oid': M_id,
            'size': len(open(path, 'rb').read()),
            'type': 'video',
            'ver': '1.0',
        }
        data = {'params': json.dumps(params)}
        r = self.post_content('https://os.line.naver.jp/talk/m/upload.nhn',
                              data=data,
                              files=files)
        if r.status_code != 201:
            raise Exception('Upload image failure.')
        return True

    def sendVideoWithURL(self, to_, url):
        path = 'pythonLines.data'
        r = requests.get(url, stream=True)
        if r.status_code == 200:
            with open(path, 'w') as f:
                shutil.copyfileobj(r.raw, f)
        else:
            raise Exception('Download Audio failure.')
        try:
            self.sendVideo(to_, path)
        except Exception as e:
            raise e

    def sendVoice(self, to_, path):
        M = Message(to=to_, text=None, contentType=3)
        M.contentPreview = None
        M_id = self._client.sendMessage(0, M).id
        files = {
            'file': open(path, 'rb'),
        }
        params = {
            'name': 'voice_message',
            'oid': M_id,
            'size': len(open(path, 'rb').read()),
            'type': 'audio',
            'ver': '1.0',
        }
        data = {'params': json.dumps(params)}
        r = self.post_content('https://os.line.naver.jp/talk/m/upload.nhn',
                              data=data,
                              files=files)
        if r.status_code != 201:
            raise Exception('Upload voice failure.')
        return True

    def sendEvent(self, messageObject):
        return self.Talk.client.sendEvent(0, messageObject)

    def sendChatChecked(self, mid, lastMessageId):
        return self.Talk.client.sendChatChecked(0, mid, lastMessageId)

    def getMessageBoxCompactWrapUp(self, mid):
        return self.Talk.client.getMessageBoxCompactWrapUp(mid)

    def getMessageBoxCompactWrapUpList(self, start, messageBox):
        return self.Talk.client.getMessageBoxCompactWrapUpList(
            start, messageBox)

    def getRecentMessages(self, messageBox, count):
        return self.Talk.client.getRecentMessages(messageBox.id, count)

    def getMessageBox(self, channelId, messageboxId, lastMessagesCount):
        return self.Talk.client.getMessageBox(channelId, messageboxId,
                                              lastMessagesCount)

    def getMessageBoxList(self, channelId, lastMessagesCount):
        return self.Talk.client.getMessageBoxList(channelId, lastMessagesCount)

    def getMessageBoxListByStatus(self, channelId, lastMessagesCount, status):
        return self.Talk.client.getMessageBoxListByStatus(
            channelId, lastMessagesCount, status)

    def getMessageBoxWrapUp(self, mid):
        return self.Talk.client.getMessageBoxWrapUp(mid)

    def getMessageBoxWrapUpList(self, start, messageBoxCount):
        return self.Talk.client.getMessageBoxWrapUpList(start, messageBoxCount)

    """Contact"""

    def blockContact(self, mid):
        return self.Talk.client.blockContact(0, mid)

    def unblockContact(self, mid):
        return self.Talk.client.unblockContact(0, mid)

    def findAndAddContactsByMid(self, mid):
        return self.Talk.client.findAndAddContactsByMid(0, mid)

    def findAndAddContactsByMids(self, midlist):
        for i in midlist:
            self.Talk.client.findAndAddContactsByMid(0, i)

    def findAndAddContactsByUserid(self, userid):
        return self.Talk.client.findAndAddContactsByUserid(0, userid)

    def findContactsByUserid(self, userid):
        return self.Talk.client.findContactByUserid(userid)

    def findContactByTicket(self, ticketId):
        return self.Talk.client.findContactByUserTicket(ticketId)

    def getAllContactIds(self):
        return self.Talk.client.getAllContactIds()

    def getBlockedContactIds(self):
        return self.Talk.client.getBlockedContactIds()

    def getContact(self, mid):
        return self.Talk.client.getContact(mid)

    def getContacts(self, midlist):
        return self.Talk.client.getContacts(midlist)

    def getFavoriteMids(self):
        return self.Talk.client.getFavoriteMids()

    def getHiddenContactMids(self):
        return self.Talk.client.getHiddenContactMids()

    """Group"""

    def findGroupByTicket(self, ticketId):
        return self.Talk.client.findGroupByTicket(ticketId)

    def acceptGroupInvitation(self, groupId):
        return self.Talk.client.acceptGroupInvitation(0, groupId)

    def acceptGroupInvitationByTicket(self, groupId, ticketId):
        return self.Talk.client.acceptGroupInvitationByTicket(
            0, groupId, ticketId)

    def cancelGroupInvitation(self, groupId, contactIds):
        return self.Talk.client.cancelGroupInvitation(0, groupId, contactIds)

    def createGroup(self, name, midlist):
        return self.Talk.client.createGroup(0, name, midlist)

    def getGroup(self, groupId):
        return self.Talk.client.getGroup(groupId)

    def getGroups(self, groupIds):
        return self.Talk.client.getGroups(groupIds)

    def getGroupIdsInvited(self):
        return self.Talk.client.getGroupIdsInvited()

    def getGroupIdsJoined(self):
        return self.Talk.client.getGroupIdsJoined()

    def inviteIntoGroup(self, groupId, midlist):
        return self.Talk.client.inviteIntoGroup(0, groupId, midlist)

    def kickoutFromGroup(self, groupId, midlist):
        return self.Talk.client.kickoutFromGroup(0, groupId, midlist)

    def leaveGroup(self, groupId):
        return self.Talk.client.leaveGroup(0, groupId)

    def rejectGroupInvitation(self, groupId):
        return self.Talk.client.rejectGroupInvitation(0, groupId)

    def reissueGroupTicket(self, groupId):
        return self.Talk.client.reissueGroupTicket(groupId)

    def updateGroup(self, groupObject):
        return self.Talk.client.updateGroup(0, groupObject)

    def findGroupByTicket(self, ticketId):
        return self.Talk.client.findGroupByTicket(0, ticketId)

    """Room"""

    def createRoom(self, midlist):
        return self.Talk.client.createRoom(0, midlist)

    def getRoom(self, roomId):
        return self.Talk.client.getRoom(roomId)

    def inviteIntoRoom(self, roomId, midlist):
        return self.Talk.client.inviteIntoRoom(0, roomId, midlist)

    def leaveRoom(self, roomId):
        return self.Talk.client.leaveRoom(0, roomId)

    """TIMELINE"""

    def new_post(self, text):
        return self.channel.new_post(text)

    def like(self, mid, postid, likeType=1001):
        return self.channel.like(mid, postid, likeType)

    def comment(self, mid, postid, text):
        return self.channel.comment(mid, postid, text)

    def activity(self, limit=20):
        return self.channel.activity(limit)

    def getAlbum(self, gid):

        return self.channel.getAlbum(gid)

    def changeAlbumName(self, gid, name, albumId):
        return self.channel.changeAlbumName(gid, name, albumId)

    def deleteAlbum(self, gid, albumId):
        return self.channel.deleteAlbum(gid, albumId)

    def getNote(self, gid, commentLimit, likeLimit):
        return self.channel.getNote(gid, commentLimit, likeLimit)

    def getDetail(self, mid):
        return self.channel.getDetail(mid)

    def getHome(self, mid):
        return self.channel.getHome(mid)

    def createAlbum(self, gid, name):
        return self.channel.createAlbum(gid, name)

    def createAlbum2(self, gid, name, path):
        return self.channel.createAlbum(gid, name, path, oid)

    def __validate(self, mail, passwd, cert, token, qr):
        if mail is not None and passwd is not None and cert is None:
            return 1
        elif mail is not None and passwd is not None and cert is not None:
            return 2
        elif token is not None:
            return 3
        elif qr is True:
            return 4
        else:
            return 5

    def loginResult(self, callback=None):
        if callback is None:
            callback = def_callback

            prof = self.getProfile()

            print(
                "╔════════════════════════════════════════════════════\n╠❂➣❂➣ Mid Kamu -> "
                + prof.mid)
            print("╠❂➣❂➣ Nama Akun -> " + prof.displayName)
            print("╠❂➣❂➣ AuthToken Kamu -> " + self.authToken)
            print(
                "╠❂➣❂➣ Cert Kamu -> " + self.cert if self.cert is not None else
                "╠════════════════════════════════════════════════════\n╠❂➣❂➣ w-N_Bots\n╠❂➣❂➣\n╚════════════════════════════════════════════════════"
            )
            print(
                "═══════════[CBW]═══════════\n═══════════[w-N_Bots]═══════════\n═════════════[CBW]═════════════"
            )
Example #13
0
class LINE:

    mid = None
    authToken = None
    cert = None
    channel_access_token = None
    token = None
    obs_token = None
    refresh_token = None

    def __init__(self):
        self.Talk = Talk()
        self._session = requests.session()
        #self._headers = {'X-Line-Application': 'IOSIPAD\t7.14.0\tiPhone OS\t10.12.0', 'X-Line-Access': 'Emp1jl3qOjxCjXEhmaN5.QdLXoVPaKOU6WpvD80Sijq.NcwnmLOaI/dIyi3Y84WTCOxbNTN27m3ODDpkMLDPY64=', 'User-Agent': 'Line/7.14.0'}
        self._headers = {
            "X_LINE_APP": 'DESKTOPMAC 10.10.2-YOSEMITE-x64    MAC 4.5.0'
        }

    def login(self,
              mail=None,
              passwd=None,
              cert=None,
              token=None,
              qr=False,
              callback=None):
        if callback is None:
            callback = def_callback
        resp = self.__validate(mail, passwd, cert, token, qr)
        if resp == 1:
            self.Talk.login(mail, passwd, callback=callback)
        elif resp == 2:
            self.Talk.login(mail, passwd, cert, callback=callback)
        elif resp == 3:
            self.Talk.TokenLogin(token)
        elif resp == 4:
            self.Talk.qrLogin(callback)
        else:
            raise Exception("invalid arguments")

        self.authToken = self.Talk.authToken
        self.cert = self.Talk.cert
        self._headers = {
            'X_LINE_APP': 'DESKTOPMAC 10.10.2-YOSEMITE-x64    MAC 4.5.0',
            #  'X-Line-Application': 'IOSIPAD\t7.14.0\tiPhone OS\t10.12.0',
            'X-Line-Access': self.authToken,
            'User-Agent': 'Line/7.14.0'
        }
        self.Poll = Poll(self.authToken)
        self.channel = channel.Channel(self.authToken)
        self.channel.login()
        self.mid = self.channel.mid
        self.channel_access_token = self.channel.channel_access_token
        self.token = self.channel.token
        self.obs_token = self.channel.obs_token
        self.refresh_token = self.channel.refresh_token

    """User"""

    def getProfile(self):
        return self.Talk.client.getProfile()

    def getSettings(self):
        return self.Talk.client.getSettings()

    def getUserTicket(self):
        return self.Talk.client.getUserTicket()

    def updateProfile(self, profileObject):
        return self.Talk.client.updateProfile(0, profileObject)

    def updateSettings(self, settingObject):
        return self.Talk.client.updateSettings(0, settingObject)

    def CloneContactProfile(self, mid):
        contact = self.getContact(mid)
        profile = self.getProfile()
        profile.displayName = contact.displayName
        profile.statusMessage = contact.statusMessage
        profile.pictureStatus = contact.pictureStatus
        self.updateDisplayPicture(profile.pictureStatus)
        return self.updateProfile(profile)

    def updateDisplayPicture(self, hash_id):
        return self.Talk.client.updateProfileAttribute(0, 8, hash_id)

    def updateProfilePicture(self, path):
        file = open(path, 'rb')
        files = {'file': file}
        params = {
            'name': 'media',
            'type': 'image',
            'oid': self.profile.mid,
            'ver': '1.0',
        }
        data = {'params': json.dumps(params)}
        r = self.server.postContent(self.server.LINE_OBS_DOMAIN +
                                    '/talk/p/upload.nhn',
                                    data=data,
                                    files=files)
        if r.status_code != 201:
            raise Exception('Update profile picture failure.')
        return True

    """Operation"""

    def fetchOperation(self, revision, count):
        return self.Poll.client.fetchOperations(revision, count)

    def fetchOps(self, rev, count):
        return self.Poll.client.fetchOps(rev, count, 0, 0)

    def getLastOpRevision(self):
        return self.Talk.client.getLastOpRevision()

    def stream(self):
        return self.Poll.stream()

    """Message"""

    def sendMessage(self, messageObject):
        return self.Talk.client.sendMessage(0, messageObject)

    def removeAllMessage(self, messageObject):
        return self.Talk.client.removeAllMessage(0, lastMessageId)

    def sendText(self, Tomid, text):
        msg = Message()
        msg.to = Tomid
        msg.text = text

        return self.Talk.client.sendMessage(0, msg)

    def post_content(self, url, data=None, files=None):
        return self._session.post(url,
                                  headers=self._headers,
                                  data=data,
                                  files=files)

    def sendImage(self, to_, path):
        M = Message(to=to_, text=None, contentType=1)
        M.contentMetadata = None
        M.contentPreview = None
        M_id = self.Talk.client.sendMessage(0, M).id
        files = {
            'file': open(path, 'rb'),
        }
        params = {
            'name': 'media',
            'oid': M_id,
            'size': len(open(path, 'rb').read()),
            'type': 'image',
            'ver': '1.0',
        }
        data = {'params': json.dumps(params)}

        r = self.post_content('https://os.line.naver.jp/talk/m/upload.nhn',
                              data=data,
                              files=files)
        #print r
        if r.status_code != 201:
            raise Exception('Upload image failure.')
        return True

    def sendImageWithUrl(self, to_, url):
        """Send a image with given image url

        :param url: image url to send
        """
        path = '%s/pythonLine-%1.data' % (tempfile.gettempdir(), randint(0, 9))

        r = requests.get(url, stream=True)
        if r.status_code == 200:
            with open(path, 'w') as f:
                shutil.copyfileobj(r.raw, f)
        else:
            raise Exception('Download image failure.')

        try:
            self.sendImage(to_, path)
        except Exception as e:
            raise e

    def sendVideo(self, to_, path):
        M = Message(to=to_, text=None, contentType=2)
        M.contentMetadata = None
        M.contentPreview = None
        M2 = self.Talk.client.sendMessage(0, M)
        M_id = M2.id
        files = {
            'file': open(path, 'rb'),
        }
        params = {
            'name': 'media',
            'oid': M_id,
            'size': len(open(path, 'rb').read()),
            'type': 'video',
            'ver': '1.0',
        }
        data = {'params': json.dumps(params)}
        r = self.post_content('https://os.line.naver.jp/talk/m/upload.nhn',
                              data=data,
                              files=files)
        #print r
        if r.status_code != 201:
            raise Exception('Upload video failure.')
        return True

    def sendVideoWithURL(self, to_, url):
        path = '%s/pythonLine-%i.data' % (tempfile.gettempdir(), randint(0, 9))

        r = requests.get(url, stream=True)
        if r.status_code == 200:
            with open(path, 'w') as f:
                shutil.copyfileobj(r.raw, f)
        else:
            raise Exception('Download video failure.')

        try:
            self.sendVideo(to_, path)
        except Exception as e:
            raise (e)

    def sendAudio(self, to_, path):
        M = Message(to=to_, text=None, contentType=3)
        M.contentMetadata = None
        M.contentPreview = None
        M2 = self.Talk.client.sendMessage(0, M)
        M_id = M2.id
        files = {
            'file': open(path, 'rb'),
        }
        params = {
            'name': 'media',
            'oid': M_id,
            'size': len(open(path, 'rb').read()),
            'type': 'audio',
            'ver': '1.0',
        }
        data = {'params': json.dumps(params)}
        r = self.post_content('https://os.line.naver.jp/talk/m/upload.nhn',
                              data=data,
                              files=files)
        if r.status_code != 201:
            raise Exception('Upload audio failure.')
        return True

    def sendAudioWithUrl(self, to_, url):
        path = '%s/pythonLine-%1.data' % (tempfile.gettempdir(), randint(0, 9))

        r = requests.get(url, stream=True)
        if r.status_code == 200:
            with open(path, 'w') as f:
                shutil.copyfileobj(r.raw, f)
        else:
            raise Exception('Download audio failure.')

        try:
            self.sendAudio(to_, path)
        except Exception as e:
            raise (e)

    def removeAllMessages(self, lastMessageId):
        return self.Talk.client.removeAllMessages(0, lastMessageId)

    def sendEvent(self, messageObject):
        return self._client.sendEvent(0, messageObject)

    def sendChatChecked(self, mid, lastMessageId):
        return self.Talk.client.sendChatChecked(0, mid, lastMessageId)

    def getMessageBoxCompactWrapUp(self, mid):
        return self.Talk.client.getMessageBoxCompactWrapUp(mid)

    def getMessageBoxCompactWrapUpList(self, start, messageBox):
        return self.Talk.client.getMessageBoxCompactWrapUpList(
            start, messageBox)

    def getRecentMessages(self, messageBox, count):
        return self.Talk.client.getRecentMessages(messageBox.id, count)

    def getMessageBox(self, channelId, messageboxId, lastMessagesCount):
        return self.Talk.client.getMessageBox(channelId, messageboxId,
                                              lastMessagesCount)

    def getMessageBoxList(self, channelId, lastMessagesCount):
        return self.Talk.client.getMessageBoxList(channelId, lastMessagesCount)

    def getMessageBoxListByStatus(self, channelId, lastMessagesCount, status):
        return self.Talk.client.getMessageBoxListByStatus(
            channelId, lastMessagesCount, status)

    def getMessageBoxWrapUp(self, mid):
        return self.Talk.client.getMessageBoxWrapUp(mid)

    def getMessageBoxWrapUpList(self, start, messageBoxCount):
        return self.Talk.client.getMessageBoxWrapUpList(start, messageBoxCount)

    """Contact"""

    def blockContact(self, mid):
        return self.Talk.client.blockContact(0, mid)

    def unblockContact(self, mid):
        return self.Talk.client.unblockContact(0, mid)

    def findAndAddContactsByMid(self, mid):
        return self.Talk.client.findAndAddContactsByMid(0, mid)

    def findAndAddContactsByMids(self, midlist):
        for i in midlist:
            self.Talk.client.findAndAddContactsByMid(0, i)

    def findAndAddContactsByUserid(self, userid):
        return self.Talk.client.findAndAddContactsByUserid(0, userid)

    def findContactsByUserid(self, userid):
        return self.Talk.client.findContactByUserid(userid)

    def findContactByTicket(self, ticketId):
        return self.Talk.client.findContactByUserTicket(ticketId)

    def getAllContactIds(self):
        return self.Talk.client.getAllContactIds()

    def getBlockedContactIds(self):
        return self.Talk.client.getBlockedContactIds()

    def getContact(self, mid):
        return self.Talk.client.getContact(mid)

    def getContacts(self, midlist):
        return self.Talk.client.getContacts(midlist)

    def getFavoriteMids(self):
        return self.Talk.client.getFavoriteMids()

    def getHiddenContactMids(self):
        return self.Talk.client.getHiddenContactMids()

    """Group"""

    def findGroupByTicket(self, ticketId):
        return self.Talk.client.findGroupByTicket(ticketId)

    def acceptGroupInvitation(self, groupId):
        return self.Talk.client.acceptGroupInvitation(0, groupId)

    def acceptGroupInvitationByTicket(self, groupId, ticketId):
        return self.Talk.client.acceptGroupInvitationByTicket(
            0, groupId, ticketId)

    def cancelGroupInvitation(self, groupId, contactIds):
        return self.Talk.client.cancelGroupInvitation(0, groupId, contactIds)

    def createGroup(self, name, midlist):
        return self.Talk.client.createGroup(0, name, midlist)

    def getGroup(self, groupId):
        return self.Talk.client.getGroup(groupId)

    def getGroups(self, groupIds):
        return self.Talk.client.getGroups(groupIds)

    def getGroupIdsInvited(self):
        return self.Talk.client.getGroupIdsInvited()

    def getGroupIdsJoined(self):
        return self.Talk.client.getGroupIdsJoined()

    def inviteIntoGroup(self, groupId, midlist):
        return self.Talk.client.inviteIntoGroup(0, groupId, midlist)

    def kickoutFromGroup(self, groupId, midlist):
        return self.Talk.client.kickoutFromGroup(0, groupId, midlist)

    def leaveGroup(self, groupId):
        return self.Talk.client.leaveGroup(0, groupId)

    def rejectGroupInvitation(self, groupId):
        return self.Talk.client.rejectGroupInvitation(0, groupId)

    def reissueGroupTicket(self, groupId):
        return self.Talk.client.reissueGroupTicket(groupId)

    def updateGroup(self, groupObject):
        return self.Talk.client.updateGroup(0, groupObject)

    def findGroupByTicket(self, ticketId):
        return self.Talk.client.findGroupByTicket(0, ticketId)

    """Room"""

    def createRoom(self, midlist):
        return self.Talk.client.createRoom(0, midlist)

    def getRoom(self, roomId):
        return self.Talk.client.getRoom(roomId)

    def inviteIntoRoom(self, roomId, midlist):
        return self.Talk.client.inviteIntoRoom(0, roomId, midlist)

    def leaveRoom(self, roomId):
        return self.Talk.client.leaveRoom(0, roomId)

    """TIMELINE"""

    def new_post(self, text):
        return self.channel.new_post(text)

    def like(self, mid, postid, likeType=1001):
        return self.channel.like(mid, postid, likeType)

    def comment(self, mid, postid, text):
        return self.channel.comment(mid, postid, text)

    def activity(self, limit=20):
        return self.channel.activity(limit)

    def getAlbum(self, gid):

        return self.channel.getAlbum(gid)

    def changeAlbumName(self, gid, name, albumId):
        return self.channel.changeAlbumName(gid, name, albumId)

    def deleteAlbum(self, gid, albumId):
        return self.channel.deleteAlbum(gid, albumId)

    def getNote(self, gid, commentLimit, likeLimit):
        return self.channel.getNote(gid, commentLimit, likeLimit)

    def getDetail(self, mid):
        return self.channel.getDetail(mid)

    def getHome(self, mid):
        return self.channel.getHome(mid)

    def createAlbum(self, gid, name):
        return self.channel.createAlbum(gid, name)

    def createAlbum2(self, gid, name, path):
        return self.channel.createAlbum(gid, name, path, oid)

    def __validate(self, mail, passwd, cert, token, qr):
        if mail is not None and passwd is not None and cert is None:
            return 1
        elif mail is not None and passwd is not None and cert is not None:
            return 2
        elif token is not None:
            return 3
        elif qr is True:
            return 4
        else:
            return 5

    def loginResult(self, callback=None):
        if callback is None:
            callback = def_callback

            prof = self.getProfile()

            print("One Piece BOT")
            print("mid -> " + prof.mid)
            print("Nama -> " + prof.displayName)
            print("Token -> " + self.authToken)
            print("cert -> " + self.cert if self.cert is not None else "")
Example #14
0
class LINE:

  mid = None
  authToken = None
  cert = None
  channel_access_token = None
  token = None
  obs_token = None
  refresh_token = None


  def __init__(self):
    self.Talk = Talk()
    self._session = requests.session()

  def login(self, mail=None, passwd=None, cert=None, token=None, qr=False, callback=None):
    if callback is None:
      callback = def_callback
    resp = self.__validate(mail,passwd,cert,token,qr)
    if resp == 1:
      self.Talk.login(mail, passwd, callback=callback)
    elif resp == 2:
      self.Talk.login(mail,passwd,cert, callback=callback)
    elif resp == 3:
      self.Talk.TokenLogin(token)
    elif resp == 4:
      self.Talk.qrLogin(callback)
    else:
      raise Exception("invalid arguments")
    
    self.authToken = self.Talk.authToken
    self.cert = self.Talk.cert
    self._headers = {
              'X-Line-Application': 'DESKTOPMAC\t10.10.2-YOSEMITE-x64\tMAC 4.5.0',
              'X-Line-Access': self.authToken,
              'User-Agent': 'Line/8.0.1'
   }

    self.Poll = Poll(self.authToken)
    self.channel = channel.Channel(self.authToken)
    self.channel.login()

    self.mid = self.channel.mid
    self.channel_access_token = self.channel.channel_access_token
    self.token = self.channel.token
    self.obs_token = self.channel.obs_token
    self.refresh_token = self.channel.refresh_token

  """User"""

  def getProfile(self):
    return self.Talk.client.getProfile()

  def getSettings(self):
    return self.Talk.client.getSettings()

  def getUserTicket(self):
    return self.Talk.client.getUserTicket()

  def updateProfile(self, profileObject):
    return self.Talk.client.updateProfile(0, profileObject)

  def updateSettings(self, settingObject):
    return self.Talk.client.updateSettings(0, settingObject)

  def CloneContactProfile(self, mid):
    contact = self.getContact(mid)
    profile = self.getProfile()
    profile.displayName = contact.displayName
    profile.statusMessage = contact.statusMessage
    profile.pictureStatus = contact.pictureStatus
    self.updateDisplayPicture(profile.pictureStatus)
    return self.updateProfile(profile)

  def updateDisplayPicture(self, hash_id):
    return self.Talk.client.updateProfileAttribute(0, 8, hash_id)

    """File"""

  def deleteFile(self, path):
        if os.path.exists(path):
            os.remove(path)
            return True
        else:
            return False

  def downloadFileURL(self, fileUrl, returnAs='path', saveAs=''):
        if returnAs not in ['path','bool','bin']:
            raise Exception('Invalid returnAs value')
        if saveAs == '':
            saveAs = self.genTempFile()
        r = self.server.getContent(fileUrl)
        if r.status_code == 200:
            with open(saveAs, 'wb') as f:
                shutil.copyfileobj(r.raw, f)
            if returnAs == 'path':
                return saveAs
            elif returnAs == 'bool':
                return True
            elif returnAs == 'bin':
                return r.raw
        else:
            raise Exception('Download file failure.')

  def genTempFile(self, returnAs='path'):
        try:
            if returnAs not in ['file','path']:
                raise Exception('Invalid returnAs value')
            fName, fPath = 'linepy-%s-%i.bin' % (int(time.time()), randint(0, 9)), tempfile.gettempdir()
            if returnAs == 'file':
                return fName
            elif returnAs == 'path':
                return '%s/%s' % (fPath, fName)
        except:
            raise Exception('tempfile is required')

  def genOBSParams(self, newList, returnAs='json'):
        oldList = {'name': self.genTempFile('file'),'ver': '1.0'}
        if returnAs not in ['json','b64','default']:
            raise Exception('Invalid parameter returnAs')
        oldList.update(newList)
        if 'range' in oldList:
            new_range='bytes 0-%s\/%s' % ( str(oldList['range']-1), str(oldList['range']) )
            oldList.update({'range': new_range})
        if returnAs == 'json':
            oldList=json.dumps(oldList)
            return oldList
        elif returnAs == 'b64':
            oldList=json.dumps(oldList)
            return base64.b64encode(oldList.encode('utf-8'))
        elif returnAs == 'default':
            return oldList


  """Personalize"""

  def updateProfilePicture(self, path, type='p'):
        files = {'file': open(path, 'rb')}
        params = {'oid': self.profile.mid,'type': 'image'}
        if type == 'vp':
            params.update({'ver': '2.0', 'cat': 'vp.mp4'})
        data = {'params': self.genOBSParams(params)}
        r = self.server.postContent(self.server.LINE_OBS_DOMAIN + '/talk/p/upload.nhn', data=data, files=files)
        if r.status_code != 201:
            raise Exception('Update profile picture failure.')
        return True

  def updateProfileVideoPicture(self, path):
        try:
            from ffmpy import FFmpeg
            files = {'file': open(path, 'rb')}
            data = {'params': self.genOBSParams({'oid': self.profile.mid,'ver': '2.0','type': 'video','cat': 'vp.mp4'})}
            r_vp = self.server.postContent(self.server.LINE_OBS_DOMAIN + '/talk/vp/upload.nhn', data=data, files=files)
            if r_vp.status_code != 201:
                raise Exception('Update profile video picture failure.')
            path_p = self.genTempFile('path')
            ff = FFmpeg(inputs={'%s' % path: None}, outputs={'%s' % path_p: ['-ss', '00:00:2', '-vframes', '1']})
            ff.run()
            self.updateProfilePicture(path_p, 'vp')
        except:
            raise Exception('You should install FFmpeg and ffmpy from pypi')

  """Object"""

  def downloadObjectMsg(self, messageId, returnAs='path', saveAs=''):
        if saveAs == '':
            saveAs = self.genTempFile('path')
        if returnAs not in ['path','bool','bin']:
            raise Exception('Invalid returnAs value')
        params = {'oid': messageId}
        url = self.server.urlEncode(self.server.LINE_OBS_DOMAIN, '/talk/m/download.nhn', params)
        r = self.server.getContent(url)
        if r.status_code == 200:
            with open(saveAs, 'wb') as f:
                shutil.copyfileobj(r.raw, f)
            if returnAs == 'path':
                return saveAs
            elif returnAs == 'bool':
                return True
            elif returnAs == 'bin':
                return r.raw
        else:
            raise Exception('Download object failure.')

  def forwardObjectMsg(self, to, msgId, contentType='image'):
        if contentType not in ['image','video','audio']:
            raise Exception('Type not valid.')
        data = self.genOBSParams({'oid': 'reqseq','reqseq': self.revision,'type': contentType,'copyFrom': '/talk/m/%s' % msgId},'default')
        r = self.server.postContent(self.server.LINE_OBS_DOMAIN + '/talk/m/copy.nhn', data=data)
        if r.status_code != 200:
            raise Exception('Forward object failure.')
        return True


  """Operation"""

  def fetchOperation(self, revision, count):
        return self.Poll.client.fetchOperations(revision, count)

  def fetchOps(self, rev, count):
        return self.Poll.client.fetchOps(rev, count, 0, 0)

  def getLastOpRevision(self):
        return self.Talk.client.getLastOpRevision()

  def stream(self):
        return self.Poll.stream()

  def downloadFileURL(self, fileUrl, returnAs='path', saveAs=''):
        if returnAs not in ['path','bool','bin']:
            raise Exception('Invalid returnAs value')
        if saveAs == '':
            saveAs = self.genTempFileName()
        r = self.server.getContent(fileUrl)
        if r.status_code == 200:
            with open(saveAs, 'wb') as f:
                shutil.copyfileobj(r.raw, f)
            if returnAs == 'path':
                return saveAs
            elif returnAs == 'bool':
                return True
            elif returnAs == 'bin':
                return r.raw
        else:
            raise Exception('Download file failure.')

  
  """Message"""

  def sendMessage(self, messageObject):
        return self.Talk.client.sendMessage(0,messageObject)

  def removeAllMessages(self, lastMessageId):
	return self.Talk.client.removeAllMessages(0,lastMessageId)

  def sendText(self, Tomid, text):
        msg = Message()
        msg.to = Tomid
        msg.text = text

        return self.Talk.client.sendMessage(0, msg)

  def kedapkedip(self, tomid, text):
        M = Message()
        M.to = tomid
        t1 = "\xf4\x80\xb0\x82\xf4\x80\xb0\x82\xf4\x80\xb0\x82\xf4\x80\xb0\x82\xf4\x80\xa0\x81\xf4\x80\xa0\x81\xf4\x80\xa0\x81"
        t2 = "\xf4\x80\x82\xb3\xf4\x8f\xbf\xbf"
        rst = t1 + text + t2
        M.text = rst.replace("\n", " ")
        return self.Talk.client.sendMessage(0, M)

  def zalgo(self, tomid, text):
        M = Message()
        M.to = tomid
        du = [' ̍',' ̎',' ̄',' ̅',' ̿',' ̑',' ̆',' ̐',' ͒',' ͗',' ͑',' ̇',' ̈',' ̊',' ͂',' ̓',' ̈́',' ͊',' ͋',' ͌',' ̃',' ̂',' ̌',' ͐',' ́',' ̋',' ̏',' ̽',' ̉',' ͣ',' ͤ',' ͥ',' ͦ',' ͧ',' ͨ',' ͩ',' ͪ',' ͫ',' ͬ',' ͭ',' ͮ',' ͯ',' ̾',' ͛',' ͆',' ̚',]
        dm = [' ̕',' ̛',' ̀',' ́',' ͘',' ̡',' ̢',' ̧',' ̨',' ̴',' ̵',' ̶',' ͜',' ͝',' ͞',' ͟',' ͠',' ͢',' ̸',' ̷',' ͡',]
        rst = du + text + dm
        M.text = rst.replace("\n", " ")
        return self.Talk.client.sendMessage(0, M)

  def post_content(self, url, data=None, files=None):
        return self._session.post(url, headers=self._headers, data=data, files=files)

  def sendImage(self, to_, path):
        M = Message(to=to_, text=None, contentType = 1)
        M.contentMetadata = None
        M.contentPreview = None
        M_id = self.Talk.client.sendMessage(0,M).id
        files = {
            'file': open(path, 'rb'),
        }
        params = {
            'name': 'media',
            'oid': M_id,
            'size': len(open(path, 'rb').read()),
            'type': 'image',
            'ver': '1.0',
        }
        data = {
            'params': json.dumps(params)            
        }       

        r = self.post_content('http://os.line.naver.jp/talk/m/upload.nhn', data=data, files=files)
        #print r
        if r.status_code != 201:
            raise Exception('Upload image failure.')
        return True

  def sendImageWithURL(self, to_, url):
        path = '%s/pythonLine-%1.data' % (tempfile.gettempdir(), randint(0, 9))
        r = requests.get(url, stream=True, verify=False)
        if r.status_code == 200:
           with open(path, 'w') as f:
              shutil.copyfileobj(r.raw, f)
        else:
           raise Exception('Download image failure.')
        try:
            self.sendImage(to_, path)
        except Exception as e:
            raise e

  def sendAudio(self, to_, path):
        M = Message(to=to_, text=None, contentType = 3)
        M.contentMetadata = None
        M.contentPreview = None
        M_id = self.Talk.client.sendMessage(0,M).id
        files = {
            'file': open(path, 'rb'),
        }
        params = {
            'name': 'media',
            'oid': M_id,
            'size': len(open(path, 'rb').read()),
            'type': 'audio',
            'ver': '1.0',
        }
        data = {
            'params': json.dumps(params)
        }

        r = self.post_content('http://os.line.naver.jp/talk/m/upload.nhn', data=data, files=files)
	#print r
        if r.status_code != 201:
            raise Exception('Upload audio failure.')
        return True

  def sendAudioWithURL(self, to_, url):
        path = '%s/pythonLine-%1.data' % (tempfile.gettempdir(), randint(0, 9))
        r = requests.get(url, stream=True)
        if r.status_code == 200:
           with open(path, 'w') as f:
              shutil.copyfileobj(r.raw, f)
        else:
           raise Exception('Download audio failure.')
        try:
            self.sendAudio(to_, path)
        except Exception as e:
            raise e

  def sendVideo(self, to_, path):
      M = Message(to=to_,contentType = 2)
      M.contentMetadata = {
           'VIDLEN' : '0',
           'DURATION' : '0'
       }
      M.contentPreview = None
      M_id = self.Talk.client.sendMessage(0,M).id
      files = {
         'file': open(path, 'rb'),
      }
      params = {
         'name': 'media',
         'oid': M_id,
         'size': len(open(path, 'rb').read()),
         'type': 'video',
         'ver': '1.0',
      }
      data = {
         'params': json.dumps(params)
      }
      r = self.post_content('https://os.line.naver.jp/talk/m/upload.nhn', data=data, files=files)
      if r.status_code != 201:
         raise Exception('Upload image failure.')
      return True
      
  def sendVideoWithUrl(self, to_, url):
      path = 'pythonLines.data'
      r = requests.get(url, stream=True)
      if r.status_code == 200:
         with open(path, 'w') as f:
            shutil.copyfileobj(r.raw, f)
      else:
         raise Exception('Download Audio failure.')
      try:
         self.sendVideo(to_, path)
      except Exception as e:
         raise e


  def sendEvent(self, messageObject):
        return self._client.sendEvent(0, messageObject)

  def sendChatChecked(self, mid, lastMessageId):
        return self.Talk.client.sendChatChecked(0, mid, lastMessageId)

  def getMessageBoxCompactWrapUp(self, mid):
        return self.Talk.client.getMessageBoxCompactWrapUp(mid)

  def getMessageBoxCompactWrapUpList(self, start, messageBox):
        return self.Talk.client.getMessageBoxCompactWrapUpList(start, messageBox)

  def getRecentMessages(self, messageBox, count):
        return self.Talk.client.getRecentMessages(messageBox.id, count)

  def getMessageBox(self, channelId, messageboxId, lastMessagesCount):
        return self.Talk.client.getMessageBox(channelId, messageboxId, lastMessagesCount)

  def getMessageBoxList(self, channelId, lastMessagesCount):
        return self.Talk.client.getMessageBoxList(channelId, lastMessagesCount)

  def getMessageBoxListByStatus(self, channelId, lastMessagesCount, status):
        return self.Talk.client.getMessageBoxListByStatus(channelId, lastMessagesCount, status)

  def getMessageBoxWrapUp(self, mid):
        return self.Talk.client.getMessageBoxWrapUp(mid)

  def getMessageBoxWrapUpList(self, start, messageBoxCount):
        return self.Talk.client.getMessageBoxWrapUpList(start, messageBoxCount)

  """Contact"""


  def blockContact(self, mid):
        return self.Talk.client.blockContact(0, mid)


  def unblockContact(self, mid):
        return self.Talk.client.unblockContact(0, mid)


  def findAndAddContactsByMid(self, mid):
        return self.Talk.client.findAndAddContactsByMid(0, mid)


  def findAndAddContactsByMids(self, midlist):
        for i in midlist:
            self.Talk.client.findAndAddContactsByMid(0, i)

  def findAndAddContactsByUserid(self, userid):
        return self.Talk.client.findAndAddContactsByUserid(0, userid)

  def findContactsByUserid(self, userid):
        return self.Talk.client.findContactByUserid(userid)

  def findContactByTicket(self, ticketId):
        return self.Talk.client.findContactByUserTicket(ticketId)

  def getAllContactIds(self):
        return self.Talk.client.getAllContactIds()

  def getBlockedContactIds(self):
        return self.Talk.client.getBlockedContactIds()

  def getContact(self, mid):
        return self.Talk.client.getContact(mid)

  def getContacts(self, midlist):
        return self.Talk.client.getContacts(midlist)

  def getFavoriteMids(self):
        return self.Talk.client.getFavoriteMids()

  def getHiddenContactMids(self):
        return self.Talk.client.getHiddenContactMids()


  """Group"""

  def findGroupByTicket(self, ticketId):
        return self.Talk.client.findGroupByTicket(ticketId)

  def acceptGroupInvitation(self, groupId):
        return self.Talk.client.acceptGroupInvitation(0, groupId)

  def acceptGroupInvitationByTicket(self, groupId, ticketId):
        return self.Talk.client.acceptGroupInvitationByTicket(0, groupId, ticketId)

  def cancelGroupInvitation(self, groupId, contactIds):
        return self.Talk.client.cancelGroupInvitation(0, groupId, contactIds)

  def createGroup(self, name, midlist):
        return self.Talk.client.createGroup(0, name, midlist)

  def getGroup(self, groupId):
        return self.Talk.client.getGroup(groupId)

  def getGroups(self, groupIds):
        return self.Talk.client.getGroups(groupIds)

  def getGroupIdsInvited(self):
        return self.Talk.client.getGroupIdsInvited()

  def getGroupIdsJoined(self):
        return self.Talk.client.getGroupIdsJoined()

  def inviteIntoGroup(self, groupId, midlist):
        return self.Talk.client.inviteIntoGroup(0, groupId, midlist)

  def kickoutFromGroup(self, groupId, midlist):
        return self.Talk.client.kickoutFromGroup(0, groupId, midlist)

  def leaveGroup(self, groupId):
        return self.Talk.client.leaveGroup(0, groupId)

  def rejectGroupInvitation(self, groupId):
        return self.Talk.client.rejectGroupInvitation(0, groupId)

  def reissueGroupTicket(self, groupId):
        return self.Talk.client.reissueGroupTicket(groupId)

  def updateGroup(self, groupObject):
        return self.Talk.client.updateGroup(0, groupObject)
  def findGroupByTicket(self,ticketId):
        return self.Talk.client.findGroupByTicket(0,ticketId)

#  def acquireGroupCallRoute(self, groupId):
 #       return self.Talk.client.call.acquireGroupCallRoute(groupId)

  #def acquireGroupCallRoute(self, groupId):
        #return self.Talk.client.call.acquireGroupCallRoute(groupId)

  #def getGroupCall(self, ChatMid):
        #return self.Talk.client.call.getGroupCall(ChatMid)

  #def inviteIntoGroupCall(self, chatId, contactIds=[]):
        #return self.Talk.client.call.inviteIntoGroupCall(chatId, contactIds)

  def updateGroupPicture(self, groupId, path):
        files = {'file': open(path, 'rb')}
        data = {'params': self.genOBSParams({'oid': groupId,'type': 'image'})}
        r = self.server.postContent(self.server.LINE_OBS_DOMAIN + '/talk/g/upload.nhn', data=data, files=files)
        if r.status_code != 201:
            raise Exception('Update group picture failure.')
        return True

  """Room"""

  def createRoom(self, midlist):
    return self.Talk.client.createRoom(0, midlist)

  def getRoom(self, roomId):
    return self.Talk.client.getRoom(roomId)

  def inviteIntoRoom(self, roomId, midlist):
    return self.Talk.client.inviteIntoRoom(0, roomId, midlist)

  def leaveRoom(self, roomId):
    return self.Talk.client.leaveRoom(0, roomId)

  """TIMELINE"""

  def new_post(self, text):
    return self.channel.new_post(text)

  def like(self, mid, postid, likeType=1001):
    return self.channel.like(mid, postid, likeType)

  def comment(self, mid, postid, text):
    return self.channel.comment(mid, postid, text)

  def activity(self, limit=20):
    return self.channel.activity(limit)

  def getAlbum(self, gid):

      return self.channel.getAlbum(gid)
  def changeAlbumName(self, gid, name, albumId):
      return self.channel.changeAlbumName(gid, name, albumId)

  def deleteAlbum(self, gid, albumId):
      return self.channel.deleteAlbum(gid,albumId)

  def getNote(self,gid, commentLimit, likeLimit):
      return self.channel.getNote(gid, commentLimit, likeLimit)

  def getDetail(self,mid):
      return self.channel.getDetail(mid)

  def getHome(self,mid):
      return self.channel.getHome(mid)

  def createAlbum(self, gid, name):
      return self.channel.createAlbum(gid,name)

  def createAlbum2(self, gid, name, path):
      return self.channel.createAlbum(gid, name, path, oid)

  def __validate(self, mail, passwd, cert, token, qr):
    if mail is not None and passwd is not None and cert is None:
      return 1
    elif mail is not None and passwd is not None and cert is not None:
      return 2
    elif token is not None:
      return 3
    elif qr is True:
      return 4
    else:
      return 5

  def loginResult(self, callback=None):
    if callback is None:
      callback = def_callback

      prof = self.getProfile()

      print(" ╔══╦═╦═╗\n ║║║║║║║║\n ║║║║╦║║║\n ╚╩╩╩╩╩╩╝️  •─ ͜͡✫ѕєʟғвот[ᴍ̶̲̅ᴀ̶̲̅ɴ̶̲̅]κɪcκєʀ ͜͡✫─•\n•┅═ই۝ई═┅•──────────────────────────────")
      print(" Mid ✰  " + prof.mid)
      print(" Name ✰  " + prof.displayName)
      print(" authToken ✰  " + self.authToken)
      print("cert -> " + self.cert if self.cert is not None else "")
Example #15
0
class LINE:

    mid = None
    authToken = None
    cert = None
    channel_access_token = None
    token = None
    obs_token = None
    refresh_token = None

    def __init__(self):
        self.Talk = Talk()

    def login(self,
              mail=None,
              passwd=None,
              cert=None,
              token=None,
              qr=False,
              callback=None):
        if callback is None:
            callback = def_callback
        resp = self.__validate(mail, passwd, cert, token, qr)
        if resp == 1:
            self.Talk.login(mail, passwd, callback=callback)
        elif resp == 2:
            self.Talk.login(mail, passwd, cert, callback=callback)
        elif resp == 3:
            self.Talk.TokenLogin(token)
        elif resp == 4:
            self.Talk.qrLogin(callback)
        else:
            raise Exception("invalid arguments")

        self.authToken = self.Talk.authToken
        self.cert = self.Talk.cert

        self.Poll = Poll(self.authToken)
        self.channel = channel.Channel(self.authToken)
        self.channel.login()

        self.mid = self.channel.mid
        self.channel_access_token = self.channel.channel_access_token
        self.token = self.channel.token
        self.obs_token = self.channel.obs_token
        self.refresh_token = self.channel.refresh_token

    """User"""

    def getProfile(self):
        return self.Talk.client.getProfile()

    def getSettings(self):
        return self.Talk.client.getSettings()

    def getUserTicket(self):
        return self.Talk.client.getUserTicket()

    def updateProfile(self, profileObject):
        return self.Talk.client.updateProfile(0, profileObject)

    def updateSettings(self, settingObject):
        return self.Talk.client.updateSettings(0, settingObject)

    """Operation"""

    def fetchOperation(self, revision, count):
        return self.Poll.client.fetchOperations(revision, count)

    def fetchOps(self, rev, count):
        return self.Poll.client.fetchOps(rev, count, 0, 0)

    def getLastOpRevision(self):
        return self.Talk.client.getLastOpRevision()

    def stream(self):
        return self.Poll.stream()

    """Message"""

    def sendMessage(self, messageObject):
        return self.Talk.client.sendMessage(0, messageObject)

    def sendText(self, Tomid, text):
        msg = Message()
        msg.to = Tomid
        msg.text = text

        return self.Talk.client.sendMessage(0, msg)

    def sendImage(self, to_, path):
        M = Message(to=to_, contentType=1)
        M.contentMetadata = None
        M.contentPreview = None
        M_id = self._client.sendMessage(M).id
        files = {
            'file': open(path, 'rb'),
        }
        params = {
            'name': 'media',
            'oid': M_id,
            'size': len(open(path, 'rb').read()),
            'type': 'image',
            'ver': '1.0',
        }
        data = {'params': json.dumps(params)}
        r = self._client.post_content(
            'https://os.line.naver.jp/talk/m/upload.nhn',
            data=data,
            files=files)
        if r.status_code != 201:
            raise Exception('Upload image failure.')
        #r.content
        return True

    def sendEvent(self, messageObject):
        return self._client.sendEvent(0, messageObject)

    def sendChatChecked(self, mid, lastMessageId):
        return self.Talk.client.sendChatChecked(0, mid, lastMessageId)

    def getMessageBoxCompactWrapUp(self, mid):
        return self.Talk.client.getMessageBoxCompactWrapUp(mid)

    def getMessageBoxCompactWrapUpList(self, start, messageBox):
        return self.Talk.client.getMessageBoxCompactWrapUpList(
            start, messageBox)

    def getRecentMessages(self, messageBox, count):
        return self.Talk.client.getRecentMessages(messageBox.id, count)

    def getMessageBox(self, channelId, messageboxId, lastMessagesCount):
        return self.Talk.client.getMessageBox(channelId, messageboxId,
                                              lastMessagesCount)

    def getMessageBoxList(self, channelId, lastMessagesCount):
        return self.Talk.client.getMessageBoxList(channelId, lastMessagesCount)

    def getMessageBoxListByStatus(self, channelId, lastMessagesCount, status):
        return self.Talk.client.getMessageBoxListByStatus(
            channelId, lastMessagesCount, status)

    def getMessageBoxWrapUp(self, mid):
        return self.Talk.client.getMessageBoxWrapUp(mid)

    def getMessageBoxWrapUpList(self, start, messageBoxCount):
        return self.Talk.client.getMessageBoxWrapUpList(start, messageBoxCount)

    """Contact"""

    def blockContact(self, mid):
        return self.Talk.client.blockContact(0, mid)

    def unblockContact(self, mid):
        return self.Talk.client.unblockContact(0, mid)

    def findAndAddContactsByMid(self, mid):
        return self.Talk.client.findAndAddContactsByMid(0, mid)

    def findAndAddContactsByMids(self, midlist):
        for i in midlist:
            self.Talk.client.findAndAddContactsByMid(0, i)

    def findAndAddContactsByUserid(self, userid):
        return self.Talk.client.findAndAddContactsByUserid(0, userid)

    def findContactsByUserid(self, userid):
        return self.Talk.client.findContactByUserid(userid)

    def findContactByTicket(self, ticketId):
        return self.Talk.client.findContactByUserTicket(ticketId)

    def getAllContactIds(self):
        return self.Talk.client.getAllContactIds()

    def getBlockedContactIds(self):
        return self.Talk.client.getBlockedContactIds()

    def getContact(self, mid):
        return self.Talk.client.getContact(mid)

    def getContacts(self, midlist):
        return self.Talk.client.getContacts(midlist)

    def getFavoriteMids(self):
        return self.Talk.client.getFavoriteMids()

    def getHiddenContactMids(self):
        return self.Talk.client.getHiddenContactMids()

    """Group"""

    def findGroupByTicket(self, ticketId):
        return self.Talk.client.findGroupByTicket(ticketId)

    def acceptGroupInvitation(self, groupId):
        return self.Talk.client.acceptGroupInvitation(0, groupId)

    def acceptGroupInvitationByTicket(self, groupId, ticketId):
        return self.Talk.client.acceptGroupInvitationByTicket(
            0, groupId, ticketId)

    def cancelGroupInvitation(self, groupId, contactIds):
        return self.Talk.client.cancelGroupInvitation(0, groupId, contactIds)

    def createGroup(self, name, midlist):
        return self.Talk.client.createGroup(0, name, midlist)

    def getGroup(self, groupId):
        return self.Talk.client.getGroup(groupId)

    def getGroups(self, groupIds):
        return self.Talk.client.getGroups(groupIds)

    def getGroupIdsInvited(self):
        return self.Talk.client.getGroupIdsInvited()

    def getGroupIdsJoined(self):
        return self.Talk.client.getGroupIdsJoined()

    def inviteIntoGroup(self, groupId, midlist):
        return self.Talk.client.inviteIntoGroup(0, groupId, midlist)

    def kickoutFromGroup(self, groupId, midlist):
        return self.Talk.client.kickoutFromGroup(0, groupId, midlist)

    def leaveGroup(self, groupId):
        return self.Talk.client.leaveGroup(0, groupId)

    def rejectGroupInvitation(self, groupId):
        return self.Talk.client.rejectGroupInvitation(0, groupId)

    def reissueGroupTicket(self, groupId):
        return self.Talk.client.reissueGroupTicket(groupId)

    def updateGroup(self, groupObject):
        return self.Talk.client.updateGroup(0, groupObject)

    def findGroupByTicket(self, ticketId):
        return self.Talk.client.findGroupByTicket(0, ticketId)

    """Room"""

    def createRoom(self, midlist):
        return self.Talk.client.createRoom(0, midlist)

    def getRoom(self, roomId):
        return self.Talk.client.getRoom(roomId)

    def inviteIntoRoom(self, roomId, midlist):
        return self.Talk.client.inviteIntoRoom(0, roomId, midlist)

    def leaveRoom(self, roomId):
        return self.Talk.client.leaveRoom(0, roomId)

    """TIMELINE"""

    def new_post(self, text):
        return self.channel.new_post(text)

    def like(self, mid, postid, likeType=1001):
        return self.channel.like(mid, postid, likeType)

    def comment(self, mid, postid, text):
        return self.channel.comment(mid, postid, text)

    def activity(self, limit=20):
        return self.channel.activity(limit)

    def getAlbum(self, gid):

        return self.channel.getAlbum(gid)

    def changeAlbumName(self, gid, name, albumId):
        return self.channel.changeAlbumName(gid, name, albumId)

    def deleteAlbum(self, gid, albumId):
        return self.channel.deleteAlbum(gid, albumId)

    def getNote(self, gid, commentLimit, likeLimit):
        return self.channel.getNote(gid, commentLimit, likeLimit)

    def getDetail(self, mid):
        return self.channel.getDetail(mid)

    def getHome(self, mid):
        return self.channel.getHome(mid)

    def createAlbum(self, gid, name):
        return self.channel.createAlbum(gid, name)

    def createAlbum2(self, gid, name, path):
        return self.channel.createAlbum(gid, name, path, oid)

    def __validate(self, mail, passwd, cert, token, qr):
        if mail is not None and passwd is not None and cert is None:
            return 1
        elif mail is not None and passwd is not None and cert is not None:
            return 2
        elif token is not None:
            return 3
        elif qr is True:
            return 4
        else:
            return 5

    def loginResult(self, callback=None):
        if callback is None:
            callback = def_callback

            prof = self.getProfile()

            print("Yoshino Bot")
            print("mid -> " + prof.mid)
            print("name -> " + prof.displayName)
            print("authToken -> " + self.authToken)
            print("cert -> " + self.cert if self.cert is not None else "")
Example #16
0
class LINE:

    mid = None
    authToken = None
    cert = None
    channel_access_token = None
    token = None
    obs_token = None
    refresh_token = None

    def __init__(self):
        self.Talk = Talk()
        self._session = requests.session()

    def login(self,
              mail=None,
              passwd=None,
              cert=None,
              token=None,
              qr=False,
              callback=None):
        if callback is None:
            callback = def_callback
        resp = self.__validate(mail, passwd, cert, token, qr)
        if resp == 1:
            self.Talk.login(mail, passwd, callback=callback)
        elif resp == 2:
            self.Talk.login(mail, passwd, cert, callback=callback)
        elif resp == 3:
            self.Talk.TokenLogin(token)
        elif resp == 4:
            self.Talk.qrLogin(callback)
        else:
            raise Exception("invalid arguments")

        self.authToken = self.Talk.authToken
        self.cert = self.Talk.cert

        self.Poll = Poll(self.authToken)
        self.channel = channel.Channel(self.authToken)
        self.channel.login()

        self.mid = self.channel.mid
        self.channel_access_token = self.channel.channel_access_token
        self.token = self.channel.token
        self.obs_token = self.channel.obs_token
        self.refresh_token = self.channel.refresh_token
        self._headers = {
            'X-Line-Application': 'IOSIPAD\t7.14.0\tiPhone OS\t10.12.0',
            'X-Line-Access': self.authToken,
            'User-Agent': 'Line/7.14.0 iPad4,1 9.0.2'
        }

    def restart_program():
        python = sys.executable
        os.execl(python, python, *sys.argv)

    """User"""

    def getProfile(self):
        return self.Talk.client.getProfile()

    def getSettings(self):
        return self.Talk.client.getSettings()

    def getUserTicket(self):
        return self.Talk.client.getUserTicket()

    def updateProfile(self, profileObject):
        return self.Talk.client.updateProfile(0, profileObject)

    def updateSettings(self, settingObject):
        return self.Talk.client.updateSettings(0, settingObject)

    """Operation"""

    def fetchOperation(self, revision, count):
        return self.Poll.client.fetchOperations(revision, count)

    def fetchOps(self, rev, count):
        return self.Poll.client.fetchOps(rev, count, 0, 0)

    def getLastOpRevision(self):
        return self.Talk.client.getLastOpRevision()

    def stream(self):
        return self.Poll.stream()

    """Message"""

    def Square(self, isopen=True):
        self.transport = THttpClient.THttpClient(self.host)
        self.transport.setCustomHeaders(self._headers)

        self.protocol = TCompactProtocol.TCompactProtocol(self.transport)

    def sendMessage(self, messageObject):
        return self.Talk.client.sendMessage(0, messageObject)

    def sendCons(self, Tomid, messageObject):
        msg.to = Tomid

        return self.Talk.client.sendMessage(0, messageObject)

    def sendText(self, Tomid, text):
        msg = Message()
        msg.to = Tomid
        msg.text = text

        return self.Talk.client.sendMessage(0, msg)

    def post_content(self, url, data=None, files=None):
        return self._session.post(url,
                                  headers=self._headers,
                                  data=data,
                                  files=files)

    def sendImage(self, to_, path):
        M = Message(to=to_, text=None, contentType=1)
        M.contentMetadata = None
        M.contentPreview = None
        M_id = self.Talk.client.sendMessage(0, M).id
        files = {
            'file': open(path, 'rb'),
        }
        params = {
            'name': 'media',
            'oid': M_id,
            'size': len(open(path, 'rb').read()),
            'type': 'image',
            'ver': '1.0',
        }
        data = {'params': json.dumps(params)}
        r = self.post_content('https://os.line.naver.jp/talk/m/upload.nhn',
                              data=data,
                              files=files)
        print r
        if r.status_code != 201:
            raise Exception('Upload image failure.')
        return True

    def sendImageWithURL(self, to_, url):
        path = '%s/pythonLine-%i.data' % (tempfile.gettempdir(), randint(0, 9))
        r = requests.get(url, stream=True)
        if r.status_code == 200:
            with open(path, 'w') as f:
                shutil.copyfileobj(r.raw, f)
        else:
            raise Exception('Download image failure.')
        try:
            self.sendImage(to_, path)
        except Exception as e:
            raise e

    def sendAudioWithURL(self, to_, url):
        path = 'pythonLiness.data'
        r = requests.get(url, stream=True)
        if r.status_code == 200:
            with open(path, 'w') as f:
                shutil.copyfileobj(r.raw, f)
        else:
            raise Exception('Download Audio failure.')
        try:
            self.sendAudio(to_, path)
        except Exception as e:
            raise e

    def sendAudio(self, to_, path):
        M = Message(to=to_, contentType=3)
        M.contentMetadata = None
        M.contentPreview = None
        M_id = self.Talk.client.sendMessage(0, M).id
        files = {
            'file': open(path, 'rb'),
        }
        params = {
            'name': 'media',
            'oid': M_id,
            'size': len(open(path, 'rb').read()),
            'type': 'audio',
            'ver': '1.0',
        }
        data = {'params': json.dumps(params)}
        r = self.post_content('https://os.line.naver.jp/talk/m/upload.nhn',
                              data=data,
                              files=files)
        if r.status_code != 201:
            raise Exception('Upload Audio failure.')
        return True

    def sendVideo(self, to_, path):
        M = Message(to=to_, contentType=2)
        M.contentMetadata = {'VIDLEN': '0', 'DURATION': '0'}
        M.contentPreview = None
        M_id = self.Talk.client.sendMessage(0, M).id
        files = {
            'file': open(path, 'rb'),
        }
        params = {
            'name': 'media',
            'oid': M_id,
            'size': len(open(path, 'rb').read()),
            'type': 'video',
            'ver': '1.0',
        }
        data = {'params': json.dumps(params)}
        r = self.post_content('https://os.line.naver.jp/talk/m/upload.nhn',
                              data=data,
                              files=files)
        if r.status_code != 201:
            raise Exception('Upload image failure.')
        return True

    def download_page(url):
        version = (3, 0)
        cur_version = sys.version_info
        if cur_version >= version:
            import urllib, request
            try:
                headers = {}
                headers[
                    'User-Agent'] = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"
                req = urllib, request.Request(url, headers=headers)
                resp = urllib, request.urlopen(req)
                respData = str(resp.read())
                return respData
            except Exception as e:
                print(str(e))
        else:
            import urllib2
            try:
                headers = {}
                headers[
                    'User-Agent'] = "Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.27 Safari/537.17"
                req = urllib2.Request(url, headers=headers)
                response = urllib2.urlopen(req)
                page = response.read()
                return page
            except:
                return "Page Not found"

    def _images_get_next_item(s):
        start_line = s.find('rg_di')
        if start_line == -1:
            end_quote = 0
            link = "no_links"
            return link, end_quote
        else:
            start_line = s.find('"class="rg_meta"')
            start_content = s.find('"ou"', start_line + 90)
            end_content = s.find(',"ow"', start_content - 90)
            content_raw = str(s[start_content + 6:end_content - 1])
            return content_raw, end_content

    def _images_get_all_items(page):
        items = []
        while True:
            item, end_content = _images_get_next_item(page)
            if item == "no_links":
                break
            else:
                items.append(item)
                time.sleep(0.1)
                page = page[end_content:]
        return items

    def sendVideoWithURL(self, to_, url):
        path = 'pythonLines.data'
        r = requests.get(url, stream=True)
        if r.status_code == 200:
            with open(path, 'w') as f:
                shutil.copyfileobj(r.raw, f)
        else:
            raise Exception('Download Audio failure.')
        try:
            self.sendVideo(to_, path)
        except Exception as e:
            raise e

    def sendEvent(self, messageObject):
        return self._client.sendEvent(0, messageObject)

    def sendChatChecked(self, mid, lastMessageId):
        return self.Talk.client.sendChatChecked(0, mid, lastMessageId)

    def getMessageBoxCompactWrapUp(self, mid):
        return self.Talk.client.getMessageBoxCompactWrapUp(mid)

    def getMessageBoxCompactWrapUpList(self, start, messageBox):
        return self.Talk.client.getMessageBoxCompactWrapUpList(
            start, messageBox)

    def getRecentMessages(self, messageBox, count):
        return self.Talk.client.getRecentMessages(messageBox.id, count)

    def getMessageBox(self, channelId, messageboxId, lastMessagesCount):
        return self.Talk.client.getMessageBox(channelId, messageboxId,
                                              lastMessagesCount)

    def getMessageBoxList(self, channelId, lastMessagesCount):
        return self.Talk.client.getMessageBoxList(channelId, lastMessagesCount)

    def getMessageBoxListByStatus(self, channelId, lastMessagesCount, status):
        return self.Talk.client.getMessageBoxListByStatus(
            channelId, lastMessagesCount, status)

    def getMessageBoxWrapUp(self, mid):
        return self.Talk.client.getMessageBoxWrapUp(mid)

    def getMessageBoxWrapUpList(self, start, messageBoxCount):
        return self.Talk.client.getMessageBoxWrapUpList(start, messageBoxCount)

    """Contact"""

    def blockContact(self, mid):
        return self.Talk.client.blockContact(0, mid)

    def unblockContact(self, mid):
        return self.Talk.client.unblockContact(0, mid)

    def findAndAddContactsByMid(self, mid):
        return self.Talk.client.findAndAddContactsByMid(0, mid)

    def findAndAddContactsByMids(self, midlist):
        for i in midlist:
            self.Talk.client.findAndAddContactsByMid(0, i)

    def findAndAddContactsByUserid(self, userid):
        return self.Talk.client.findAndAddContactsByUserid(0, userid)

    def cloneContactProfile(self, mid):
        contact = self.getContact(mid)
        profile = self.getProfile()
        profile.displayName = contact.displayName
        profile.statusMessage = contact.statusMessage
        profile.pictureStatus = contact.pictureStatus
        self.updateDisplayPicture(profile.pictureStatus)
        return self.updateProfile(profile)

    def updateDisplayPictures(self, path):
        files = {
            'file': open(path, 'rb'),
        }
        params = {
            'name': 'media',
            'oid': M_id,
            'size': len(open(path, 'rb').read()),
            'type': 'image',
            'ver': '1.0',
        }
        data = {'params': json.dumps(params)}
        r = self.post_content('https://os.line.naver.jp/talk/m/upload.nhn',
                              data=data,
                              files=files)
        return self.updateGroup(group)

    def changeGroup(self, mid):
        contact = self.getContact(mid)
        group = self.getGroup()
        group.pictureStatus = contact.pictureStatus
        self.updateDisplayPicture(group.pictureStatus)
        return self.updateGroup(group)

    def updateDisplayPicture(self, hash_id):
        return self.Talk.client.updateProfileAttribute(0, 8, hash_id)

    def findContactsByUserid(self, userid):
        return self.Talk.client.findContactByUserid(userid)

    def findContactByTicket(self, ticketId):
        return self.Talk.client.findContactByUserTicket(ticketId)

    def getAllContactIds(self):
        return self.Talk.client.getAllContactIds()

    def getBlockedContactIds(self):
        return self.Talk.client.getBlockedContactIds()

    def getContact(self, mid):
        return self.Talk.client.getContact(mid)

    def getContacts(self, midlist):
        return self.Talk.client.getContacts(midlist)

    def getFavoriteMids(self):
        return self.Talk.client.getFavoriteMids()

    def getHiddenContactMids(self):
        return self.Talk.client.getHiddenContactMids()

    """Group"""

    def findGroupByTicket(self, ticketId):
        return self.Talk.client.findGroupByTicket(ticketId)

    def acceptGroupInvitation(self, groupId):
        return self.Talk.client.acceptGroupInvitation(0, groupId)

    def acceptGroupInvitationByTicket(self, groupId, ticketId):
        return self.Talk.client.acceptGroupInvitationByTicket(
            0, groupId, ticketId)

    def cancelGroupInvitation(self, groupId, contactIds):
        return self.Talk.client.cancelGroupInvitation(0, groupId, contactIds)

    def createGroup(self, name, midlist):
        return self.Talk.client.createGroup(0, name, midlist)

    def getGroup(self, groupId):
        return self.Talk.client.getGroup(groupId)

    def getGroups(self, groupIds):
        return self.Talk.client.getGroups(groupIds)

    def getGroupIdsInvited(self):
        return self.Talk.client.getGroupIdsInvited()

    def getGroupIdsJoined(self):
        return self.Talk.client.getGroupIdsJoined()

    def inviteIntoGroup(self, groupId, midlist):
        return self.Talk.client.inviteIntoGroup(0, groupId, midlist)

    def kickoutFromGroup(self, groupId, midlist):
        return self.Talk.client.kickoutFromGroup(0, groupId, midlist)

    def leaveGroup(self, groupId):
        return self.Talk.client.leaveGroup(0, groupId)

    def rejectGroupInvitation(self, groupId):
        return self.Talk.client.rejectGroupInvitation(0, groupId)

    def reissueGroupTicket(self, groupId):
        return self.Talk.client.reissueGroupTicket(groupId)

    def updateGroup(self, groupObject):
        return self.Talk.client.updateGroup(0, groupObject)

    def findGroupByTicket(self, ticketId):
        return self.Talk.client.findGroupByTicket(0, ticketId)

    """Room"""

    def createRoom(self, midlist):
        return self.Talk.client.createRoom(0, midlist)

    def getRoom(self, roomId):
        return self.Talk.client.getRoom(roomId)

    def inviteIntoRoom(self, roomId, midlist):
        return self.Talk.client.inviteIntoRoom(0, roomId, midlist)

    def leaveRoom(self, roomId):
        return self.Talk.client.leaveRoom(0, roomId)

    """TIMELINE"""

    def new_post(self, text):
        return self.channel.new_post(text)

    def like(self, mid, postid, likeType=1001):
        return self.channel.like(mid, postid, likeType)

    def comment(self, mid, postid, text):
        return self.channel.comment(mid, postid, text)

    def activity(self, limit=20):
        return self.channel.activity(limit)

    def getAlbum(self, gid):

        return self.channel.getAlbum(gid)

    def changeAlbumName(self, gid, name, albumId):
        return self.channel.changeAlbumName(gid, name, albumId)

    def deleteAlbum(self, gid, albumId):
        return self.channel.deleteAlbum(gid, albumId)

    def getNote(self, gid, commentLimit, likeLimit):
        return self.channel.getNote(gid, commentLimit, likeLimit)

    def getDetail(self, mid):
        return self.channel.getDetail(mid)

    def getHome(self, mid):
        return self.channel.getHome(mid)

    def createAlbum(self, gid, name):
        return self.channel.createAlbum(gid, name)

    def createAlbum2(self, gid, name, path):
        return self.channel.createAlbum(gid, name, path, oid)

    def __validate(self, mail, passwd, cert, token, qr):
        if mail is not None and passwd is not None and cert is None:
            return 1
        elif mail is not None and passwd is not None and cert is not None:
            return 2
        elif token is not None:
            return 3
        elif qr is True:
            return 4
        else:
            return 5

    def loginResult(self, callback=None):
        if callback is None:
            callback = def_callback

            prof = self.getProfile()

            print("====YudaBOt====")
            print("mid -> " + prof.mid)
            print("name -> " + prof.displayName)
            print("authToken -> " + self.authToken)
            print("cert -> " + self.cert if self.cert is not None else "")
Example #17
0
class LINE:

  mid = None
  authToken = None
  cert = None
  channel_access_token = None
  token = None
  obs_token = None
  refresh_token = None


  def __init__(self):
    self.Talk = Talk()
    self._session = requests.session()

  def login(self, mail=None, passwd=None, cert=None, token=None, qr=False, callback=None):
    if callback is None:
      callback = def_callback
    resp = self.__validate(mail,passwd,cert,token,qr)
    if resp == 1:
      self.Talk.login(mail, passwd, callback=callback)
    elif resp == 2:
      self.Talk.login(mail,passwd,cert, callback=callback)
    elif resp == 3:
      self.Talk.TokenLogin(token)
    elif resp == 4:
      self.Talk.qrLogin(callback)
    else:
      raise Exception("invalid arguments")

    self.authToken = self.Talk.authToken
    self.cert = self.Talk.cert
    self._headers = {
              'X-Line-Application': 'DESKTOPMAC 10.10.2-YOSEMITE-64    MAC 4.5.0', 
              'X-Line-Access': self.authToken, 
              'User-Agent': 'Line/6.0.0 iPad4,1 9.0.2'#'Line/7.18.0 AppleWebKit/534.30'#'Line/6.0.0 iPad4,1 9.0.2'#'Line/7.18.0 iPad4,1 9.0.2'
   }
    self.Poll = Poll(self.authToken)
    self.channel = channel.Channel(self.authToken)
    self.channel.login()
    self.mid = self.channel.mid
    self.channel_access_token = self.channel.channel_access_token
    self.token = self.channel.token
    self.obs_token = self.channel.obs_token
    self.refresh_token = self.channel.refresh_token


  """User"""

  def getProfile(self):
    return self.Talk.client.getProfile()

  def getSettings(self):
    return self.Talk.client.getSettings()

  def getUserTicket(self):
    return self.Talk.client.getUserTicket()

  def updateProfile(self, profileObject):
    return self.Talk.client.updateProfile(0, profileObject)

  def updateSettings(self, settingObject):
    return self.Talk.client.updateSettings(0, settingObject)

  def updateDisplayPicture(self, hash_id):
    return self.Talk.client.updateProfileAttribute(0, 8, hash_id)


  """Operation"""

  def fetchOperation(self, revision, count):
        return self.Poll.client.fetchOperations(revision, count)

  def fetchOps(self, rev, count):
        return self.Poll.client.fetchOps(rev, count, 0, 0)

  def getLastOpRevision(self):
        return self.Talk.client.getLastOpRevision()

  def stream(self):
        return self.Poll.stream()

  """Message"""

  def sendMessage(self, messageObject):
        return self.Talk.client.sendMessage(0,messageObject)

  def sendText(self, Tomid, text):
        msg = Message()
        msg.to = Tomid
        msg.text = text

        return self.Talk.client.sendMessage(0, msg)
  def post_content(self, url, data=None, files=None):
        return self._session.post(url, headers=self._headers, data=data, files=files)

  def sendImage(self, to_, path):
        M = Message(to=to_, text=None, contentType = 1)
        M.contentMetadata = None
        M.contentPreview = None
        M_id = self.Talk.client.sendMessage(0,M).id
        files = {
            'file': open(path, 'rb'),
        }
        params = {
            'name': 'media',
            'oid': M_id,
            'size': len(open(path, 'rb').read()),
            'type': 'image',
            'ver': '1.0',
        }
        data = {
            'params': json.dumps(params)
        }

        r = self.post_content('https://os.line.naver.jp/talk/m/upload.nhn', data=data, files=files)
        if r.status_code != 201:
            raise Exception('Upload image failure.')
        return True

  def sendImageWithURL(self, to_, url):
        """Send a image with given image url

        :param url: image url to send
        """
        path = 'pythonLine.data'

        r = requests.get(url, stream=True)
        if r.status_code == 200:
            with open(path, 'w') as f:
                shutil.copyfileobj(r.raw, f)
        else:
            raise Exception('Download image failure.')

        try:
            self.sendImage(to_, path)
        except Exception as e:
            raise e

  def sendAudioWithURL(self, to_, url):
      path = 'pythonLiness.data'
      r = requests.get(url, stream=True)
      if r.status_code == 200:
         with open(path, 'w') as f:
            shutil.copyfileobj(r.raw, f)
      else:
         raise Exception('Download Audio failure.')
      try:
         self.sendAudio(to_, path)
      except Exception as e:
         raise e
  def sendAudio(self, to_, path):
      M = Message(to=to_,contentType = 3)
      M.contentMetadata = None
      M.contentPreview = None
      M_id = self.Talk.client.sendMessage(0,M).id
      files = {
         'file': open(path, 'rb'),
      }
      params = {
         'name': 'media',
         'oid': M_id,
         'size': len(open(path, 'rb').read()),
         'type': 'audio',
         'ver': '1.0',
      }
      data = {
         'params': json.dumps(params)
      }
      r = self.post_content('https://os.line.naver.jp/talk/m/upload.nhn', data=data, files=files)
      if r.status_code != 201:
         raise Exception('Upload image failure.')
      return True
  def sendVideo(self, to_, path):
      M = Message(to=to_,contentType = 2)
      M.contentMetadata = {
           'VIDLEN' : '0',
           'DURATION' : '0'
       }
      M.contentPreview = None
      M_id = self.Talk.client.sendMessage(0,M).id
      files = {
         'file': open(path, 'rb'),
      }
      params = {
         'name': 'media',
         'oid': M_id,
         'size': len(open(path, 'rb').read()),
         'type': 'video',
         'ver': '1.0',
      }
      data = {
         'params': json.dumps(params)
      }
      r = self.post_content('https://os.line.naver.jp/talk/m/upload.nhn', data=data, files=files)
      if r.status_code != 201:
         raise Exception('Upload image failure.')
      return True
  def sendVideoWithURL(self, to_, url):
      path = 'pythonLines.data'
      r = requests.get(url, stream=True)
      if r.status_code == 200:
         with open(path, 'w') as f:
            shutil.copyfileobj(r.raw, f)
      else:
         raise Exception('Download Audio failure.')
      try:
         self.sendVideo(to_, path)
      except Exception as e:
         raise e

  def sendVoice(self, to_, path):
          M = Message(to=to_, text=None, contentType = 3)
          M.contentPreview = None
          M_id = self._client.sendMessage(0,M).id
          files = {
              'file': open(path, 'rb'),
          }
          params = {
              'name': 'voice_message',
              'oid': M_id,
              'size': len(open(path, 'rb').read()),
              'type': 'audio',
              'ver': '1.0',
          }
          data = {
              'params': json.dumps(params)
          }
          r = self.post_content('https://os.line.naver.jp/talk/m/upload.nhn', data=data, files=files)
          if r.status_code != 201:
              raise Exception('Upload voice failure.')
          return True


  def sendEvent(self, messageObject):
        return self.Talk.client.sendEvent(0, messageObject)

  def sendChatChecked(self, mid, lastMessageId):
        return self.Talk.client.sendChatChecked(0, mid, lastMessageId)

  def getMessageBoxCompactWrapUp(self, mid):
        return self.Talk.client.getMessageBoxCompactWrapUp(mid)

  def getMessageBoxCompactWrapUpList(self, start, messageBox):
        return self.Talk.client.getMessageBoxCompactWrapUpList(start, messageBox)

  def getRecentMessages(self, messageBox, count):
        return self.Talk.client.getRecentMessages(messageBox.id, count)

  def getMessageBox(self, channelId, messageboxId, lastMessagesCount):
        return self.Talk.client.getMessageBox(channelId, messageboxId, lastMessagesCount)

  def getMessageBoxList(self, channelId, lastMessagesCount):
        return self.Talk.client.getMessageBoxList(channelId, lastMessagesCount)

  def getMessageBoxListByStatus(self, channelId, lastMessagesCount, status):
        return self.Talk.client.getMessageBoxListByStatus(channelId, lastMessagesCount, status)

  def getMessageBoxWrapUp(self, mid):
        return self.Talk.client.getMessageBoxWrapUp(mid)

  def getMessageBoxWrapUpList(self, start, messageBoxCount):
        return self.Talk.client.getMessageBoxWrapUpList(start, messageBoxCount)

  """Contact"""


  def blockContact(self, mid):
        return self.Talk.client.blockContact(0, mid)


  def unblockContact(self, mid):
        return self.Talk.client.unblockContact(0, mid)


  def findAndAddContactsByMid(self, mid):
        return self.Talk.client.findAndAddContactsByMid(0, mid)


  def findAndAddContactsByMids(self, midlist):
        for i in midlist:
            self.Talk.client.findAndAddContactsByMid(0, i)

  def findAndAddContactsByUserid(self, userid):
        return self.Talk.client.findAndAddContactsByUserid(0, userid)

  def findContactsByUserid(self, userid):
        return self.Talk.client.findContactByUserid(userid)

  def findContactByTicket(self, ticketId):
        return self.Talk.client.findContactByUserTicket(ticketId)

  def getAllContactIds(self):
        return self.Talk.client.getAllContactIds()

  def getBlockedContactIds(self):
        return self.Talk.client.getBlockedContactIds()

  def getContact(self, mid):
        return self.Talk.client.getContact(mid)

  def getContacts(self, midlist):
        return self.Talk.client.getContacts(midlist)

  def getFavoriteMids(self):
        return self.Talk.client.getFavoriteMids()

  def getHiddenContactMids(self):
        return self.Talk.client.getHiddenContactMids()


  """Group"""

  def findGroupByTicket(self, ticketId):
        return self.Talk.client.findGroupByTicket(ticketId)

  def acceptGroupInvitation(self, groupId):
        return self.Talk.client.acceptGroupInvitation(0, groupId)

  def acceptGroupInvitationByTicket(self, groupId, ticketId):
        return self.Talk.client.acceptGroupInvitationByTicket(0, groupId, ticketId)

  def cancelGroupInvitation(self, groupId, contactIds):
        return self.Talk.client.cancelGroupInvitation(0, groupId, contactIds)

  def createGroup(self, name, midlist):
        return self.Talk.client.createGroup(0, name, midlist)

  def getGroup(self, groupId):
        return self.Talk.client.getGroup(groupId)

  def getGroups(self, groupIds):
        return self.Talk.client.getGroups(groupIds)

  def getGroupIdsInvited(self):
        return self.Talk.client.getGroupIdsInvited()

  def getGroupIdsJoined(self):
        return self.Talk.client.getGroupIdsJoined()

  def inviteIntoGroup(self, groupId, midlist):
        return self.Talk.client.inviteIntoGroup(0, groupId, midlist)

  def kickoutFromGroup(self, groupId, midlist):
        return self.Talk.client.kickoutFromGroup(0, groupId, midlist)

  def leaveGroup(self, groupId):
        return self.Talk.client.leaveGroup(0, groupId)

  def rejectGroupInvitation(self, groupId):
        return self.Talk.client.rejectGroupInvitation(0, groupId)

  def reissueGroupTicket(self, groupId):
        return self.Talk.client.reissueGroupTicket(groupId)

  def updateGroup(self, groupObject):
        return self.Talk.client.updateGroup(0, groupObject)
  def findGroupByTicket(self,ticketId):
        return self.Talk.client.findGroupByTicket(0,ticketId)

  """Room"""

  def createRoom(self, midlist):
    return self.Talk.client.createRoom(0, midlist)

  def getRoom(self, roomId):
    return self.Talk.client.getRoom(roomId)

  def inviteIntoRoom(self, roomId, midlist):
    return self.Talk.client.inviteIntoRoom(0, roomId, midlist)

  def leaveRoom(self, roomId):
    return self.Talk.client.leaveRoom(0, roomId)

  """TIMELINE"""

  def new_post(self, text):
    return self.channel.new_post(text)

  def like(self, mid, postid, likeType=1001):
    return self.channel.like(mid, postid, likeType)

  def comment(self, mid, postid, text):
    return self.channel.comment(mid, postid, text)

  def activity(self, limit=20):
    return self.channel.activity(limit)

  def getAlbum(self, gid):

      return self.channel.getAlbum(gid)
  def changeAlbumName(self, gid, name, albumId):
      return self.channel.changeAlbumName(gid, name, albumId)

  def deleteAlbum(self, gid, albumId):
      return self.channel.deleteAlbum(gid,albumId)

  def getNote(self,gid, commentLimit, likeLimit):
      return self.channel.getNote(gid, commentLimit, likeLimit)

  def getDetail(self,mid):
      return self.channel.getDetail(mid)

  def getHome(self,mid):
      return self.channel.getHome(mid)

  def createAlbum(self, gid, name):
      return self.channel.createAlbum(gid,name)

  def createAlbum2(self, gid, name, path):
      return self.channel.createAlbum(gid, name, path, oid)


  def __validate(self, mail, passwd, cert, token, qr):
    if mail is not None and passwd is not None and cert is None:
      return 1
    elif mail is not None and passwd is not None and cert is not None:
      return 2
    elif token is not None:
      return 3
    elif qr is True:
      return 4
    else:
      return 5

  def loginResult(self, callback=None):
    if callback is None:
      callback = def_callback

      prof = self.getProfile()

      print("╔Mid Kamu -> " + prof.mid)
      print("╠❂➣❂➣ Nama Akun -> " + prof.displayName)
      print("╠❂➣❂➣ AuthToken Kamu -> " + self.authToken)
      print("╠❂➣❂➣ Cert Kamu -> " + self.cert if self.cert is not None else "╠═line://ti/p/~oscwib")
      print("════WIB═══════")
Example #18
0
class LINE:

  mid = None
  authToken = None
  cert = None
  channel_access_token = None
  token = None
  obs_token = None
  refresh_token = None


  def __init__(self):
    self.Talk = Talk()
    self._session = requests.session()
    self._headers = {'X-Line-Application':'DESKTOPMAC\t10.10.2-YOSEMITE-x64\tMAC 4.5.0'}

  def login(self, mail=None, passwd=None, cert=None, token=None, qr=False, callback=None):
    if callback is None:
      callback = def_callback
    resp = self.__validate(mail,passwd,cert,token,qr)
    if resp == 1:
      self.Talk.login(mail, passwd, callback=callback)
    elif resp == 2:
      self.Talk.login(mail,passwd,cert, callback=callback)
    elif resp == 3:
      self.Talk.TokenLogin(token)
    elif resp == 4:
      self.Talk.qrLogin(callback)
    else:
      raise Exception("invalid arguments")

    self.authToken = self.Talk.authToken
    self.cert = self.Talk.cert
    self._headers = {
              'X-Line-Application': 'DESKTOPMAC\t10.10.2-YOSEMITE-x64\tMAC 4.5.0',
              'X-Line-Access': self.authToken,
              'User-Agent': 'Line/8.1.1'
   }

    self.Poll = Poll(self.authToken)
    """self.channel = channel.Channel(self.authToken)
    self.channel.login()
    self.mid = self.channel.mid
    self.channel_access_token = self.channel.channel_access_token
    self.token = self.channel.token
    self.obs_token = self.channel.obs_token
    self.refresh_token = self.channel.refresh_token"""

  """User"""

  def getProfile(self):
    return self.Talk.client.getProfile()

  def getSettings(self):
    return self.Talk.client.getSettings()

  def getUserTicket(self):
    return self.Talk.client.getUserTicket()

  def updateProfile(self, profileObject):
    return self.Talk.client.updateProfile(0, profileObject)

  def updateSettings(self, settingObject):
    return self.Talk.client.updateSettings(0, settingObject)

  def CloneContactProfile(self, mid):
    contact = self.getContact(mid)
    profile = self.getProfile()
    profile.displayName = contact.displayName
    profile.statusMessage = contact.statusMessage
    profile.pictureStatus = contact.pictureStatus
    self.updateDisplayPicture(profile.pictureStatus)
    return self.updateProfile(profile)

  def updateDisplayPicture(self, hash_id):
    return self.Talk.client.updateProfileAttribute(0, 8, hash_id)

    """File"""

  def deleteFile(self, path):
        if os.path.exists(path):
            os.remove(path)
            return True
        else:
            return False

  def downloadFileURL(self, fileUrl, returnAs='path', saveAs=''):
        if returnAs not in ['path','bool','bin']:
            raise Exception('Invalid returnAs value')
        if saveAs == '':
            saveAs = self.genTempFile()
        r = self.server.getContent(fileUrl)
        if r.status_code == 200:
            with open(saveAs, 'wb') as f:
                shutil.copyfileobj(r.raw, f)
            if returnAs == 'path':
                return saveAs
            elif returnAs == 'bool':
                return True
            elif returnAs == 'bin':
                return r.raw
        else:
            raise Exception('Download file failure.')

  def genTempFile(self, returnAs='path'):
        try:
            if returnAs not in ['file','path']:
                raise Exception('Invalid returnAs value')
            fName, fPath = 'linepy-%s-%i.bin' % (int(time.time()), randint(0, 9)), tempfile.gettempdir()
            if returnAs == 'file':
                return fName
            elif returnAs == 'path':
                return '%s/%s' % (fPath, fName)
        except:
            raise Exception('tempfile is required')

  def genOBSParams(self, newList, returnAs='json'):
        oldList = {'name': self.genTempFile('file'),'ver': '1.0'}
        if returnAs not in ['json','b64','default']:
            raise Exception('Invalid parameter returnAs')
        oldList.update(newList)
        if 'range' in oldList:
            new_range='bytes 0-%s\/%s' % ( str(oldList['range']-1), str(oldList['range']) )
            oldList.update({'range': new_range})
        if returnAs == 'json':
            oldList=json.dumps(oldList)
            return oldList
        elif returnAs == 'b64':
            oldList=json.dumps(oldList)
            return base64.b64encode(oldList.encode('utf-8'))
        elif returnAs == 'default':
            return oldList


  """Personalize"""

  def updateProfilePicture(self, path, type='p'):
        files = {'file': open(path, 'rb')}
        params = {'oid': self.profile.mid,'type': 'image'}
        if type == 'vp':
            params.update({'ver': '2.0', 'cat': 'vp.mp4'})
        data = {'params': self.genOBSParams(params)}
        r = self.server.postContent(self.server.LINE_OBS_DOMAIN + '/talk/p/upload.nhn', data=data, files=files)
        if r.status_code != 201:
            raise Exception('Update profile picture failure.')
        return True

  def updateProfileVideoPicture(self, path):
        try:
            from ffmpy import FFmpeg
            files = {'file': open(path, 'rb')}
            data = {'params': self.genOBSParams({'oid': self.profile.mid,'ver': '2.0','type': 'video','cat': 'vp.mp4'})}
            r_vp = self.server.postContent(self.server.LINE_OBS_DOMAIN + '/talk/vp/upload.nhn', data=data, files=files)
            if r_vp.status_code != 201:
                raise Exception('Update profile video picture failure.')
            path_p = self.genTempFile('path')
            ff = FFmpeg(inputs={'%s' % path: None}, outputs={'%s' % path_p: ['-ss', '00:00:2', '-vframes', '1']})
            ff.run()
            self.updateProfilePicture(path_p, 'vp')
        except:
            raise Exception('You should install FFmpeg and ffmpy from pypi')

  """Object"""

  def downloadObjectMsg(self, messageId, returnAs='path', saveAs=''):
        if saveAs == '':
            saveAs = self.genTempFile('path')
        if returnAs not in ['path','bool','bin']:
            raise Exception('Invalid returnAs value')
        params = {'oid': messageId}
        url = self.server.urlEncode(self.server.LINE_OBS_DOMAIN, '/talk/m/download.nhn', params)
        r = self.server.getContent(url)
        if r.status_code == 200:
            with open(saveAs, 'wb') as f:
                shutil.copyfileobj(r.raw, f)
            if returnAs == 'path':
                return saveAs
            elif returnAs == 'bool':
                return True
            elif returnAs == 'bin':
                return r.raw
        else:
            raise Exception('Download object failure.')

  def forwardObjectMsg(self, to, msgId, contentType='image'):
        if contentType not in ['image','video','audio']:
            raise Exception('Type not valid.')
        data = self.genOBSParams({'oid': 'reqseq','reqseq': self.revision,'type': contentType,'copyFrom': '/talk/m/%s' % msgId},'default')
        r = self.server.postContent(self.server.LINE_OBS_DOMAIN + '/talk/m/copy.nhn', data=data)
        if r.status_code != 200:
            raise Exception('Forward object failure.')
        return True


  """Operation"""

  def fetchOperation(self, revision, count):
        return self.Poll.client.fetchOperations(revision, count)

  def fetchOps(self, rev, count):
        return self.Poll.client.fetchOps(rev, count, 0, 0)

  def getLastOpRevision(self):
        return self.Talk.client.getLastOpRevision()

  def stream(self):
        return self.Poll.stream()

  def downloadFileURL(self, fileUrl, returnAs='path', saveAs=''):
        if returnAs not in ['path','bool','bin']:
            raise Exception('Invalid returnAs value')
        if saveAs == '':
            saveAs = self.genTempFileName()
        r = self.server.getContent(fileUrl)
        if r.status_code == 200:
            with open(saveAs, 'wb') as f:
                shutil.copyfileobj(r.raw, f)
            if returnAs == 'path':
                return saveAs
            elif returnAs == 'bool':
                return True
            elif returnAs == 'bin':
                return r.raw
        else:
            raise Exception('Download file failure.')

  
  """Message"""

  def sendMessage(self, messageObject):
        return self.Talk.client.sendMessage(0,messageObject)

  def removeAllMessages(self, lastMessageId):
	return self.Talk.client.removeAllMessages(0,lastMessageId)

  def sendText(self, Tomid, text):
        msg = Message()
        msg.to = Tomid
        msg.text = text

        return self.Talk.client.sendMessage(0, msg)

  def kedapkedip(self, tomid, text):
        M = Message()
        M.to = tomid
        t1 = "\xf4\x80\xb0\x82\xf4\x80\xb0\x82\xf4\x80\xb0\x82\xf4\x80\xb0\x82\xf4\x80\xa0\x81\xf4\x80\xa0\x81\xf4\x80\xa0\x81"
        t2 = "\xf4\x80\x82\xb3\xf4\x8f\xbf\xbf"
        rst = t1 + text + t2
        M.text = rst.replace("\n", " ")
        return self.Talk.client.sendMessage(0, M)

  def zalgo(self, tomid, text):
        M = Message()
        M.to = tomid
        du = [' ̍',' ̎',' ̄',' ̅',' ̿',' ̑',' ̆',' ̐',' ͒',' ͗',' ͑',' ̇',' ̈',' ̊',' ͂',' ̓',' ̈́',' ͊',' ͋',' ͌',' ̃',' ̂',' ̌',' ͐',' ́',' ̋',' ̏',' ̽',' ̉',' ͣ',' ͤ',' ͥ',' ͦ',' ͧ',' ͨ',' ͩ',' ͪ',' ͫ',' ͬ',' ͭ',' ͮ',' ͯ',' ̾',' ͛',' ͆',' ̚',]
        dm = [' ̕',' ̛',' ̀',' ́',' ͘',' Ì¡',' Ì¢',' ̧',' ̨',' Ì´',' ̵',' ̶',' ͜',' ͝',' ͞',' ͟',' Í ',' Í¢',' ̸',' Ì·',' Í¡',]
        rst = du + text + dm
        M.text = rst.replace("\n", " ")
        return self.Talk.client.sendMessage(0, M)

  def post_content(self, url, data=None, files=None):
        return self._session.post(url, headers=self._headers, data=data, files=files)

  def sendImage(self, to_, path):
        M = Message(to=to_, text=None, contentType = 1)
        M.contentMetadata = None
        M.contentPreview = None
        M_id = self.Talk.client.sendMessage(0,M).id
        files = {
            'file': open(path, 'rb'),
        }
        params = {
            'name': 'media',
            'oid': M_id,
            'size': len(open(path, 'rb').read()),
            'type': 'image',
            'ver': '1.0',
        }
        data = {
            'params': json.dumps(params)            
        }       

        r = self.post_content('http://os.line.naver.jp/talk/m/upload.nhn', data=data, files=files)
        #print r
        if r.status_code != 201:
            raise Exception('Upload image failure.')
        return True

  def sendImageWithUrl(self, to_, url):
        path = '%s/pythonLine-%1.data' % (tempfile.gettempdir(), randint(0, 9))
        r = requests.get(url, stream=True, verify=False)
        if r.status_code == 200:
           with open(path, 'w') as f:
              shutil.copyfileobj(r.raw, f)
        else:
           raise Exception('Download image failure.')
        try:
            self.sendImage(to_, path)
        except Exception as e:
            raise e

  def sendAudio(self, to_, path):
        M = Message(to=to_, text=None, contentType = 3)
        M.contentMetadata = None
        M.contentPreview = None
        M_id = self.Talk.client.sendMessage(0,M).id
        files = {
            'file': open(path, 'rb'),
        }
        params = {
            'name': 'media',
            'oid': M_id,
            'size': len(open(path, 'rb').read()),
            'type': 'audio',
            'ver': '1.0',
        }
        data = {
            'params': json.dumps(params)
        }

        r = self.post_content('http://os.line.naver.jp/talk/m/upload.nhn', data=data, files=files)
	print r
        if r.status_code != 201:
            raise Exception('Upload audio failure.')
        return True

  def sendAudioWithUrl(self, to_, url):
        path = '%s/pythonLine-%1.data' % (tempfile.gettempdir(), randint(0, 9))
        r = requests.get(url, stream=True)
        if r.status_code == 200:
           with open(path, 'w') as f:
              shutil.copyfileobj(r.raw, f)
        else:
           raise Exception('Download audio failure.')
        try:
            self.sendAudio(to_, path)
        except Exception as e:
            raise e

  def sendVideo(self, to_, path):
      M = Message(to=to_,contentType = 2)
      M.contentMetadata = {
           'VIDLEN' : '0',
           'DURATION' : '0'
       }
      M.contentPreview = None
      M_id = self.Talk.client.sendMessage(0,M).id
      files = {
         'file': open(path, 'rb'),
      }
      params = {
         'name': 'media',
         'oid': M_id,
         'size': len(open(path, 'rb').read()),
         'type': 'video',
         'ver': '1.0',
      }
      data = {
         'params': json.dumps(params)
      }
      r = self.post_content('https://os.line.naver.jp/talk/m/upload.nhn', data=data, files=files)
      if r.status_code != 201:
         raise Exception('Upload image failure.')
      return True
      
  def sendVideoWithUrl(self, to_, url):
      path = 'pythonLines.data'
      r = requests.get(url, stream=True)
      if r.status_code == 200:
         with open(path, 'w') as f:
            shutil.copyfileobj(r.raw, f)
      else:
         raise Exception('Download Audio failure.')
      try:
         self.sendVideo(to_, path)
      except Exception as e:
         raise e


  def sendEvent(self, messageObject):
        return self._client.sendEvent(0, messageObject)

  def sendChatChecked(self, mid, lastMessageId):
        return self.Talk.client.sendChatChecked(0, mid, lastMessageId)

  def getMessageBoxCompactWrapUp(self, mid):
        return self.Talk.client.getMessageBoxCompactWrapUp(mid)

  def getMessageBoxCompactWrapUpList(self, start, messageBox):
        return self.Talk.client.getMessageBoxCompactWrapUpList(start, messageBox)

  def getRecentMessages(self, messageBox, count):
        return self.Talk.client.getRecentMessages(messageBox.id, count)

  def getMessageBox(self, channelId, messageboxId, lastMessagesCount):
        return self.Talk.client.getMessageBox(channelId, messageboxId, lastMessagesCount)

  def getMessageBoxList(self, channelId, lastMessagesCount):
        return self.Talk.client.getMessageBoxList(channelId, lastMessagesCount)

  def getMessageBoxListByStatus(self, channelId, lastMessagesCount, status):
        return self.Talk.client.getMessageBoxListByStatus(channelId, lastMessagesCount, status)

  def getMessageBoxWrapUp(self, mid):
        return self.Talk.client.getMessageBoxWrapUp(mid)

  def getMessageBoxWrapUpList(self, start, messageBoxCount):
        return self.Talk.client.getMessageBoxWrapUpList(start, messageBoxCount)

  """Contact"""


  def blockContact(self, mid):
        return self.Talk.client.blockContact(0, mid)


  def unblockContact(self, mid):
        return self.Talk.client.unblockContact(0, mid)


  def findAndAddContactsByMid(self, mid):
        return self.Talk.client.findAndAddContactsByMid(0, mid)


  def findAndAddContactsByMids(self, midlist):
        for i in midlist:
            self.Talk.client.findAndAddContactsByMid(0, i)

  def findAndAddContactsByUserid(self, userid):
        return self.Talk.client.findAndAddContactsByUserid(0, userid)

  def findContactsByUserid(self, userid):
        return self.Talk.client.findContactByUserid(userid)

  def findContactByTicket(self, ticketId):
        return self.Talk.client.findContactByUserTicket(ticketId)

  def getAllContactIds(self):
        return self.Talk.client.getAllContactIds()

  def getBlockedContactIds(self):
        return self.Talk.client.getBlockedContactIds()

  def getContact(self, mid):
        return self.Talk.client.getContact(mid)

  def getContacts(self, midlist):
        return self.Talk.client.getContacts(midlist)

  def getFavoriteMids(self):
        return self.Talk.client.getFavoriteMids()

  def getHiddenContactMids(self):
        return self.Talk.client.getHiddenContactMids()


  """Group"""

  def findGroupByTicket(self, ticketId):
        return self.Talk.client.findGroupByTicket(ticketId)

  def acceptGroupInvitation(self, groupId):
        return self.Talk.client.acceptGroupInvitation(0, groupId)

  def acceptGroupInvitationByTicket(self, groupId, ticketId):
        return self.Talk.client.acceptGroupInvitationByTicket(0, groupId, ticketId)

  def cancelGroupInvitation(self, groupId, contactIds):
        return self.Talk.client.cancelGroupInvitation(0, groupId, contactIds)

  def createGroup(self, name, midlist):
        return self.Talk.client.createGroup(0, name, midlist)

  def getGroup(self, groupId):
        return self.Talk.client.getGroup(groupId)

  def getGroups(self, groupIds):
        return self.Talk.client.getGroups(groupIds)

  def getGroupIdsInvited(self):
        return self.Talk.client.getGroupIdsInvited()

  def getGroupIdsJoined(self):
        return self.Talk.client.getGroupIdsJoined()

  def inviteIntoGroup(self, groupId, midlist):
        return self.Talk.client.inviteIntoGroup(0, groupId, midlist)

  def kickoutFromGroup(self, groupId, midlist):
        return self.Talk.client.kickoutFromGroup(0, groupId, midlist)

  def leaveGroup(self, groupId):
        return self.Talk.client.leaveGroup(0, groupId)

  def rejectGroupInvitation(self, groupId):
        return self.Talk.client.rejectGroupInvitation(0, groupId)

  def reissueGroupTicket(self, groupId):
        return self.Talk.client.reissueGroupTicket(groupId)

  def updateGroup(self, groupObject):
        return self.Talk.client.updateGroup(0, groupObject)
  def findGroupByTicket(self,ticketId):
        return self.Talk.client.findGroupByTicket(0,ticketId)

#  def acquireGroupCallRoute(self, groupId):
 #       return self.Talk.client.call.acquireGroupCallRoute(groupId)

  #def acquireGroupCallRoute(self, groupId):
#        return self.Talk.client.call.acquireGroupCallRoute(groupId)

#  def getGroupCall(self, ChatMid):
 #       return self.Talk.client.call.getGroupCall(ChatMid)

  #def inviteIntoGroupCall(self, chatId, contactIds=[]):
   #     return self.Talk.client.call.inviteIntoGroupCall(chatId, contactIds)

  def updateGroupPicture(self, groupId, path):
        files = {'file': open(path, 'rb')}
        data = {'params': self.genOBSParams({'oid': groupId,'type': 'image'})}
        r = self.server.postContent(self.server.LINE_OBS_DOMAIN + '/talk/g/upload.nhn', data=data, files=files)
        if r.status_code != 201:
            raise Exception('Update group picture failure.')
        return True

  """Room"""

  def createRoom(self, midlist):
    return self.Talk.client.createRoom(0, midlist)

  def getRoom(self, roomId):
    return self.Talk.client.getRoom(roomId)

  def inviteIntoRoom(self, roomId, midlist):
    return self.Talk.client.inviteIntoRoom(0, roomId, midlist)

  def leaveRoom(self, roomId):
    return self.Talk.client.leaveRoom(0, roomId)

  """TIMELINE"""

  def new_post(self, text):
    return self.channel.new_post(text)

  def like(self, mid, postid, likeType=1001):
    return self.channel.like(mid, postid, likeType)

  def comment(self, mid, postid, text):
    return self.channel.comment(mid, postid, text)

  def activity(self, limit=20):
    return self.channel.activity(limit)

  def getAlbum(self, gid):

      return self.channel.getAlbum(gid)
  def changeAlbumName(self, gid, name, albumId):
      return self.channel.changeAlbumName(gid, name, albumId)

  def deleteAlbum(self, gid, albumId):
      return self.channel.deleteAlbum(gid,albumId)

  def getNote(self,gid, commentLimit, likeLimit):
      return self.channel.getNote(gid, commentLimit, likeLimit)

  def getDetail(self,mid):
      return self.channel.getDetail(mid)

  def getHome(self,mid):
      return self.channel.getHome(mid)

  def createAlbum(self, gid, name):
      return self.channel.createAlbum(gid,name)

  def createAlbum2(self, gid, name, path):
      return self.channel.createAlbum(gid, name, path, oid)

  def __validate(self, mail, passwd, cert, token, qr):
    if mail is not None and passwd is not None and cert is None:
      return 1
    elif mail is not None and passwd is not None and cert is not None:
      return 2
    elif token is not None:
      return 3
    elif qr is True:
      return 4
    else:
      return 5

  def loginResult(self, callback=None):
    if callback is None:
      callback = def_callback

      prof = self.getProfile()

      print("Bagas~")
      print("mid -> " + prof.mid)
      print("name -> " + prof.displayName)
      print("authToken -> " + self.authToken)
      print("cert -> " + self.cert if self.cert is not None else "")
Example #19
0
class LINE:

    mid = None
    authToken = None
    cert = None
    channel_access_token = None
    token = None
    obs_token = None
    refresh_token = None

    def __init__(self):
        self.Talk = Talk()
        self._session = requests.session()
        self._headers = {
            'X-Line-Application': 'CHROMEOS\t1.4.17\Chrome_OS\t1',
            'X-Line-Access':
            'En8z7W6K9ShbwAIels6d.O9Sg8jZkwCjgi8TlzrJrZq.HMeI4+5wNsvn205uLXRTpUTIUvaalDx4Xl5oYk7eeaY=',
            'User-Agent': 'Line/1.4.17'
        }

    def login(self,
              mail=None,
              passwd=None,
              cert=None,
              token=None,
              qr=False,
              callback=None):
        if callback is None:
            callback = def_callback
        resp = self.__validate(mail, passwd, cert, token, qr)
        if resp == 1:
            self.Talk.login(mail, passwd, callback=callback)
        elif resp == 2:
            self.Talk.login(mail, passwd, cert, callback=callback)
        elif resp == 3:
            self.Talk.TokenLogin(token)
        elif resp == 4:
            self.Talk.qrLogin(callback)
        else:
            raise Exception("invalid arguments")

        self.authToken = self.Talk.authToken
        self.cert = self.Talk.cert

        self.Poll = Poll(self.authToken)
        self.channel = channel.Channel(self.authToken)
        self.channel.login()

        self.mid = self.channel.mid
        self.channel_access_token = self.channel.channel_access_token
        self.token = self.channel.token
        self.obs_token = self.channel.obs_token
        self.refresh_token = self.channel.refresh_token

    """User"""

    def getProfile(self):
        return self.Talk.client.getProfile()

    def getSettings(self):
        return self.Talk.client.getSettings()

    def getUserTicket(self):
        return self.Talk.client.getUserTicket()

    def updateProfile(self, profileObject):
        return self.Talk.client.updateProfile(0, profileObject)

    def updateSettings(self, settingObject):
        return self.Talk.client.updateSettings(0, settingObject)

    def cloneContactProfile(self, mid):
        contact = self.getContact(mid)
        profile = self.getProfile()
        profile.displayName = contact.displayName
        profile.statusMessage = contact.statusMessage
        profile.pictureStatus = contact.pictureStatus
        self.updateDisplayPicture(profile.pictureStatus)
        return self.updateProfile(profile)

    def updateDisplayPicture(self, hash_id):
        return self.Talk.client.updateProfileAttribute(0, 8, hash_id)

    """Operation"""

    def fetchOperation(self, revision, count):
        return self.Poll.client.fetchOperations(revision, count)

    def fetchOps(self, rev, count):
        return self.Poll.client.fetchOps(rev, count, 0, 0)

    def getLastOpRevision(self):
        return self.Talk.client.getLastOpRevision()

    def stream(self):
        return self.Poll.stream()

    """Message"""

    def sendMessage(self, messageObject):
        return self.Talk.client.sendMessage(0, messageObject)

    def removeAllMessages(self, lastMessageId):
        return self.Talk.client.removeAllMessages(0, lastMessageId)

    def sendText(self, Tomid, text):
        msg = Message()
        msg.to = Tomid
        msg.text = text

        return self.Talk.client.sendMessage(0, msg)

    def kedapkedip(self, tomid, text):
        M = Message()
        M.to = tomid
        t1 = "\xf4\x80\xb0\x82\xf4\x80\xb0\x82\xf4\x80\xb0\x82\xf4\x80\xb0\x82\xf4\x80\xa0\x81\xf4\x80\xa0\x81\xf4\x80\xa0\x81"
        t2 = "\xf4\x80\x82\xb3\xf4\x8f\xbf\xbf"
        rst = t1 + text + t2
        M.text = rst.replace("\n", " ")
        return self.Talk.client.sendMessage(0, M)

    def post_content(self, url, data=None, files=None):
        return self._session.post(url,
                                  headers=self._headers,
                                  data=data,
                                  files=files)

    def sendImage(self, to_, path):
        M = Message(to=to_, text=None, contentType=1)
        M.contentMetadata = None
        M.contentPreview = None
        M2 = self.Talk.client.sendMessage(0, M)
        M_id = M2.id
        files = {
            'file': open(path, 'rb'),
        }
        params = {
            'name': 'media',
            'oid': M_id,
            'size': len(open(path, 'rb').read()),
            'type': 'image',
            'ver': '1.0',
        }
        data = {'params': json.dumps(params)}
        r = self.post_content('https://obs-sg.line-apps.com/talk/m/upload.nhn',
                              data=data,
                              files=files)
        if r.status_code != 201:
            raise Exception('Upload image failed.')
        return True

    def sendImage2(self, to_, path):
        M = Message(to=to_, contentType=1)
        M.contentMetadata = None
        M.contentPreview = None
        M_id = self.Talk.client.sendMessage(M).id
        files = {
            'file': open(path, 'rb'),
        }
        params = {
            'name': 'media',
            'oid': M_id,
            'size': len(open(path, 'rb').read()),
            'type': 'image',
            'ver': '1.0',
        }
        data = {'params': json.dumps(params)}
        r = self.post_content('https://os.line.naver.jp/talk/m/upload.nhn',
                              data=data,
                              files=files)
        if r.status_code != 201:
            raise Exception('Upload image failed.')
        return True

    def sendImageWithURL(self, to_, url):
        path = '%s/pythonLine-%i.jpg' % (tempfile.gettempdir(), randint(0, 9))
        r = requests.get(url, stream=True)
        if r.status_code == 200:
            with open(path, 'wb') as f:
                r.raw.decode_content = True
                shutil.copyfileobj(r.raw, f)
        else:
            raise Exception('Download image failure.')
        try:
            self.sendImage(to_, path)
        except:
            try:
                self.sendImage2(to_, path)
            except Exception as e:
                raise e

    def sendAudio(self, to_, path):
        M = Message(to=to_, text=None, contentType=3)
        M.contentMetadata = None
        M.contentPreview = None
        M2 = self.Talk.client.sendMessage(0, M)
        M_id = M2.id
        files = {
            'file': open(path, 'rb'),
        }
        params = {
            'name': 'media',
            'oid': M_id,
            'size': len(open(path, 'rb').read()),
            'type': 'audio',
            'ver': '1.0',
        }
        data = {'params': json.dumps(params)}
        r = self.post_content('https://obs-sg.line-apps.com/talk/m/upload.nhn',
                              data=data,
                              files=files)
        if r.status_code != 201:
            raise Exception('Upload audio failure.')
        return True

    def sendAudioWithURL(self, to_, url):
        path = '%s/pythonLine-%i.data' % (tempfile.gettempdir(), randint(0, 9))
        r = requests.get(url, stream=True)
        if r.status_code == 200:
            with open(path, 'wb') as f:
                r.raw.decode_content = True
                shutil.copyfileobj(r.raw, f)
        else:
            raise Exception('Download Audio failure.')
        try:
            self.sendAudio(to_, path)
        except Exception as e:
            print e

    def sendEvent(self, messageObject):
        return self._client.sendEvent(0, messageObject)

    def sendChatChecked(self, mid, lastMessageId):
        return self.Talk.client.sendChatChecked(0, mid, lastMessageId)

    def getMessageBoxCompactWrapUp(self, mid):
        return self.Talk.client.getMessageBoxCompactWrapUp(mid)

    def getMessageBoxCompactWrapUpList(self, start, messageBox):
        return self.Talk.client.getMessageBoxCompactWrapUpList(
            start, messageBox)

    def getRecentMessages(self, messageBox, count):
        return self.Talk.client.getRecentMessages(messageBox.id, count)

    def getMessageBox(self, channelId, messageboxId, lastMessagesCount):
        return self.Talk.client.getMessageBox(channelId, messageboxId,
                                              lastMessagesCount)

    def getMessageBoxList(self, channelId, lastMessagesCount):
        return self.Talk.client.getMessageBoxList(channelId, lastMessagesCount)

    def getMessageBoxListByStatus(self, channelId, lastMessagesCount, status):
        return self.Talk.client.getMessageBoxListByStatus(
            channelId, lastMessagesCount, status)

    def getMessageBoxWrapUp(self, mid):
        return self.Talk.client.getMessageBoxWrapUp(mid)

    def getMessageBoxWrapUpList(self, start, messageBoxCount):
        return self.Talk.client.getMessageBoxWrapUpList(start, messageBoxCount)

    """Contact"""

    def blockContact(self, mid):
        return self.Talk.client.blockContact(0, mid)

    def unblockContact(self, mid):
        return self.Talk.client.unblockContact(0, mid)

    def findAndAddContactsByMid(self, mid):
        return self.Talk.client.findAndAddContactsByMid(0, mid)

    def findAndAddContactsByMids(self, midlist):
        for i in midlist:
            self.Talk.client.findAndAddContactsByMid(0, i)

    def findAndAddContactsByUserid(self, userid):
        return self.Talk.client.findAndAddContactsByUserid(0, userid)

    def findContactsByUserid(self, userid):
        return self.Talk.client.findContactByUserid(userid)

    def findContactByTicket(self, ticketId):
        return self.Talk.client.findContactByUserTicket(ticketId)

    def getAllContactIds(self):
        return self.Talk.client.getAllContactIds()

    def getBlockedContactIds(self):
        return self.Talk.client.getBlockedContactIds()

    def getContact(self, mid):
        return self.Talk.client.getContact(mid)

    def getContacts(self, midlist):
        return self.Talk.client.getContacts(midlist)

    def getFavoriteMids(self):
        return self.Talk.client.getFavoriteMids()

    def getHiddenContactMids(self):
        return self.Talk.client.getHiddenContactMids()

    """Group"""

    def findGroupByTicket(self, ticketId):
        return self.Talk.client.findGroupByTicket(ticketId)

    def acceptGroupInvitation(self, groupId):
        return self.Talk.client.acceptGroupInvitation(0, groupId)

    def acceptGroupInvitationByTicket(self, groupId, ticketId):
        return self.Talk.client.acceptGroupInvitationByTicket(
            0, groupId, ticketId)

    def cancelGroupInvitation(self, groupId, contactIds):
        return self.Talk.client.cancelGroupInvitation(0, groupId, contactIds)

    def createGroup(self, name, midlist):
        return self.Talk.client.createGroup(0, name, midlist)

    def getGroup(self, groupId):
        return self.Talk.client.getGroup(groupId)

    def getGroups(self, groupIds):
        return self.Talk.client.getGroups(groupIds)

    def getGroupIdsInvited(self):
        return self.Talk.client.getGroupIdsInvited()

    def getGroupIdsJoined(self):
        return self.Talk.client.getGroupIdsJoined()

    def inviteIntoGroup(self, groupId, midlist):
        return self.Talk.client.inviteIntoGroup(0, groupId, midlist)

    def kickoutFromGroup(self, groupId, midlist):
        return self.Talk.client.kickoutFromGroup(0, groupId, midlist)

    def leaveGroup(self, groupId):
        return self.Talk.client.leaveGroup(0, groupId)

    def rejectGroupInvitation(self, groupId):
        return self.Talk.client.rejectGroupInvitation(0, groupId)

    def reissueGroupTicket(self, groupId):
        return self.Talk.client.reissueGroupTicket(groupId)

    def updateGroup(self, groupObject):
        return self.Talk.client.updateGroup(0, groupObject)

    def findGroupByTicket(self, ticketId):
        return self.Talk.client.findGroupByTicket(0, ticketId)

    """Room"""

    def createRoom(self, midlist):
        return self.Talk.client.createRoom(0, midlist)

    def getRoom(self, roomId):
        return self.Talk.client.getRoom(roomId)

    def inviteIntoRoom(self, roomId, midlist):
        return self.Talk.client.inviteIntoRoom(0, roomId, midlist)

    def leaveRoom(self, roomId):
        return self.Talk.client.leaveRoom(0, roomId)

    """TIMELINE"""

    def new_post(self, text):
        return self.channel.new_post(text)

    def like(self, mid, postid, likeType=1001):
        return self.channel.like(mid, postid, likeType)

    def comment(self, mid, postid, text):
        return self.channel.comment(mid, postid, text)

    def activity(self, limit=20):
        return self.channel.activity(limit)

    def getAlbum(self, gid):

        return self.channel.getAlbum(gid)

    def changeAlbumName(self, gid, name, albumId):
        return self.channel.changeAlbumName(gid, name, albumId)

    def deleteAlbum(self, gid, albumId):
        return self.channel.deleteAlbum(gid, albumId)

    def getNote(self, gid, commentLimit, likeLimit):
        return self.channel.getNote(gid, commentLimit, likeLimit)

    def getDetail(self, mid):
        return self.channel.getDetail(mid)

    def getHome(self, mid):
        return self.channel.getHome(mid)

    def createAlbum(self, gid, name):
        return self.channel.createAlbum(gid, name)

    def createAlbum2(self, gid, name, path):
        return self.channel.createAlbum(gid, name, path, oid)

    def __validate(self, mail, passwd, cert, token, qr):
        if mail is not None and passwd is not None and cert is None:
            return 1
        elif mail is not None and passwd is not None and cert is not None:
            return 2
        elif token is not None:
            return 3
        elif qr is True:
            return 4
        else:
            return 5

    def loginResult(self, callback=None):
        if callback is None:
            callback = def_callback

            prof = self.getProfile()

            print("Aked - Bot")
            print("Mid 		: " + prof.mid)
            print("Name 		: " + prof.displayName)
            print("AuthToken 	: " + self.authToken)
            print("Cert 		: " + self.cert if self.cert is not None else "")
Example #20
0
class LINE:

  mid = None
  authToken = None
  cert = None
  channel_access_token = None
  token = None
  obs_token = None
  refresh_token = None


  def __init__(self):
    self.Talk = Talk()
    self._session = requests.session()

  def login(self, mail=None, passwd=None, cert=None, token=None, qr=False, callback=None):
    if callback is None:
      callback = def_callback
    resp = self.__validate(mail,passwd,cert,token,qr)
    if resp == 1:
      self.Talk.login(mail, passwd, callback=callback)
    elif resp == 2:
      self.Talk.login(mail,passwd,cert, callback=callback)
    elif resp == 3:
      self.Talk.TokenLogin(token)
    elif resp == 4:
      self.Talk.qrLogin(callback)
    else:
      raise Exception("invalid arguments")

    self.authToken = self.Talk.authToken
    self._headers = {'X-Line-Application': 'CHROMEOS 2.0.0 Chrome_OS 1', 'X-Line-Access': self.authToken, 'User-Agent': 'Line/7.18.0'}
    self.cert = self.Talk.cert
    self._headers = {
              'X-Line-Application': 'CHROMEOS 2.0.0 Chrome_OS 1', 
              'X-Line-Access': self.authToken, 
              'User-Agent': 'Line/7.18.0'
   }
    self.Poll = Poll(self.authToken)
    #self.channel = channel.Channel(self.authToken)
    #self.channel.login()	
    #self.mid = self.channel.mid
    #self.channel_access_token = self.channel.channel_access_token
    #self.token = self.channel.token
    #self.obs_token = self.channel.obs_token
    #self.refresh_token = self.channel.refresh_token


  """User"""

  def getProfile(self):
    return self.Talk.client.getProfile()

  def getSettings(self):
    return self.Talk.client.getSettings()

  def getUserTicket(self):
    return self.Talk.client.getUserTicket()

  def updateProfile(self, profileObject):
    return self.Talk.client.updateProfile(0, profileObject)

  def updateSettings(self, settingObject):
    return self.Talk.client.updateSettings(0, settingObject)

  def updateSettings(self, settingObject):
    return self.Talk.client.updateSettings(0, settingObject)

  def CloneContactProfile(self, mid):
    contact = self.getContact(mid)
    profile = self.getProfile()
    profile.displayName = contact.displayName
    profile.statusMessage = contact.statusMessage
    profile.pictureStatus = contact.pictureStatus
    self.updateDisplayPicture(profile.pictureStatus)
    return self.updateProfile(profile)

  def updateDisplayPicture(self, hash_id):
    return self.Talk.client.updateProfileAttribute(0, 8, hash_id)

  """Operation"""

  def fetchOperation(self, revision, count):
        return self.Poll.client.fetchOperations(revision, count)

  def fetchOps(self, rev, count):
        return self.Poll.client.fetchOps(rev, count, 0, 0)

  def getLastOpRevision(self):
        return self.Talk.client.getLastOpRevision()

  def stream(self):
        return self.Poll.stream()

  """Message"""

  def sendMessage(self, messageObject):
        return self.Talk.client.sendMessage(0,messageObject)

  def removeAllMessages(self, lastMessageId):
        return self.Talk.client.removeAllMessages(0,lastMessageId)
  
  def sendText(self, Tomid, text):
        msg = Message()
        msg.to = Tomid
        msg.text = text

        return self.Talk.client.sendMessage(0, msg)
        
  def post_content(self, url, data=None, files=None):
        return self._session.post(url, headers=self._headers, data=data, files=files)

  def kedapkedip(self, tomid, text):
        M = Message()
        M.to = tomid
        t1 = "\xf4\x80\xb0\x82\xf4\x80\xb0\x82\xf4\x80\xb0\x82\xf4\x80\xb0\x82\xf4\x80\xa0\x81\xf4\x80\xa0\x81\xf4\x80\xa0\x81"
        t2 = "\xf4\x80\x82\xb3\xf4\x8f\xbf\xbf"
        rst = t1 + text + t2
        M.text = rst.replace("\n", " ")
        return self.Talk.client.sendMessage(0, M)  
        
  def sendMessageWithMention(self, to, text='', dataMid=[]):
      arr = []
      list_text=''
      if '[list]' in text.lower():
          i=0
          for l in dataMid:
              list_text+='\n@[list-'+str(i)+']'
              i=i+1
          text=text.replace('[list]', list_text)
      elif '[list-' in text.lower():
          text=text
      else:
          i=0
          for l in dataMid:
              list_text+=' @[list-'+str(i)+']'
              i=i+1
          text=text+list_text
      i=0
      for l in dataMid:
          mid=l
          name='@[list-'+str(i)+']'
          ln_text=text.replace('\n',' ')
          if ln_text.find(name):
              line_s=int( ln_text.index(name) )
              line_e=(int(line_s)+int( len(name) ))
          arrData={'S': str(line_s), 'E': str(line_e), 'M': mid}
          arr.append(arrData)
          i=i+1
      contentMetadata={'MENTION':str('{"MENTIONEES":' + json.dumps(arr).replace(' ','') + '}')}
      return self.sendMessage(to, text, contentMetadata)
  
  def sendImage(self, to_, path):
        M = Message(to=to_, text=None, contentType = 1)
        M.contentMetadata = None
        M.contentPreview = None
        M_id = self.Talk.client.sendMessage(0,M).id
        files = {
            'file': open(path, 'rb'),
        }
        params = {
            'name': 'media',
            'oid': M_id,
            'size': len(open(path, 'rb').read()),
            'type': 'image',
            'ver': '1.0',
        }
        data = {
            'params': json.dumps(params)            
        }       

        r = self.post_content('https://os.line.naver.jp/talk/m/upload.nhn', data=data, files=files)
        print r
        if r.status_code != 201:
            raise Exception('Upload image failure.')
        return True

  def sendImageWithURL(self, to_, url):
        """Send a image with given image url

        :param url: image url to send
        """
        path = 'tmp/pythonLine.data'

        r = requests.get(url, stream=True)
        if r.status_code == 200:
            with open(path, 'wb') as f:
                shutil.copyfileobj(r.raw, f)
        else:
            raise Exception('Download image failure.')

        try:
            self.sendImage(to_, path)
        except Exception as e:
            raise e
            
  def getCover(self,mid):
        h = self.getHome(mid)
        objId = h["result"]["homeInfo"]["objectId"]
        return "http://dl.profile.line-cdn.net/myhome/c/download.nhn?userid=" + mid + "&oid=" + objId
        
  def sendVideo(self, to_, path):
      M = Message(to=to_,contentType = 2)
      M.contentMetadata = {
           'VIDLEN' : '0',
           'DURATION' : '0'
       }
      M.contentPreview = None
      M_id = self.Talk.client.sendMessage(0,M).id
      files = {
         'file': open(path, 'rb'),
      }
      params = {
         'name': 'media',
         'oid': M_id,
         'size': len(open(path, 'rb').read()),
         'type': 'video',
         'ver': '1.0',
      }
      data = {
         'params': json.dumps(params)
      }
      r = self.post_content('https://os.line.naver.jp/talk/m/upload.nhn', data=data, files=files)
      if r.status_code != 201:
         raise Exception('Upload image failure.')
      return True
      
  def sendVideoWithURL(self, to_, url):
      path = 'pythonLines.data'
      r = requests.get(url, stream=True)
      if r.status_code == 200:
         with open(path, 'w') as f:
            shutil.copyfileobj(r.raw, f)
      else:
         raise Exception('Download Video failure.')
      try:
         self.sendVideo(to_, path)
      except Exception as e:
         raise e
      
  def sendAudio(self, to_, path):
        M = Message(to=to_, text=None, contentType = 3)
        M.contentMetadata = None
        M.contentPreview = None
        M2 = self.Talk.client.sendMessage(0,M)
        M_id = M2.id
        files = {
            'file': open(path, 'rb'),
        }
        params = {
            'name': 'media',
            'oid': M_id,
            'size': len(open(path, 'rb').read()),
            'type': 'audio',
            'ver': '1.0',
        }
        data = {
            'params': json.dumps(params)
        }
        r = self.post_content('https://obs-sg.line-apps.com/talk/m/upload.nhn', data=data, files=files)
        if r.status_code != 201:
            raise Exception('Upload audio failure.')
        return True

  def sendAudioWithURL(self, to_, url):
        path = '%s/pythonLine-%i.data' % (tempfile.gettempdir(), randint(0, 9))
        r = requests.get(url, stream=True)
        if r.status_code == 200:
            with open(path, 'wb') as f:
              r.raw.decode_content = True
              shutil.copyfileobj(r.raw, f)
        else:
            raise Exception('Download Audio failure.')
        try:
            self.sendAudio(to_, path)
        except Exception as e:
          print e
  
  def downloadFileURL(self, fileUrl):
      saveAs = '%s/linepython-%i.data' % (tempfile.gettempdir(), randint(0, 9))
      r = self.getContent(fileUrl, headers=self._headers)
      if r.status_code == 200:
          with open(saveAs, 'wb') as f:
              hutil.copyfileobj(r.raw, f)
          return saveAs
      else:
          raise Exception('Download file failure.')

  def downloadObjectMsgId(self, messageId):
        saveAs = '%s/%s-%i.bin' % (tempfile.gettempdir(), messageId, randint(0, 9))
        params = {'oid': messageId}
        url = self.server.urlEncode('https://obs.line-apps.com', '/talk/m/download.nhn', params)
        r = self.server.getContent(url)
        if r.status_code == 200:
            with open(saveAs, 'wb') as f:
				shutil.copyfileobj(r.raw, f)			
				return saveAs
        else:
            raise Exception('Download file failure.')
        
  def sendEvent(self, messageObject):
        return self._client.sendEvent(0, messageObject)

  def sendChatChecked(self, mid, lastMessageId):
        return self.Talk.client.sendChatChecked(0, mid, lastMessageId)

  def getMessageBoxCompactWrapUp(self, mid):
        return self.Talk.client.getMessageBoxCompactWrapUp(mid)

  def getMessageBoxCompactWrapUpList(self, start, messageBox):
        return self.Talk.client.getMessageBoxCompactWrapUpList(start, messageBox)

  def getRecentMessages(self, messageBox, count):
        return self.Talk.client.getRecentMessages(messageBox.id, count)

  def getMessageBox(self, channelId, messageboxId, lastMessagesCount):
        return self.Talk.client.getMessageBox(channelId, messageboxId, lastMessagesCount)

  def getMessageBoxList(self, channelId, lastMessagesCount):
        return self.Talk.client.getMessageBoxList(channelId, lastMessagesCount)

  def getMessageBoxListByStatus(self, channelId, lastMessagesCount, status):
        return self.Talk.client.getMessageBoxListByStatus(channelId, lastMessagesCount, status)

  def getMessageBoxWrapUp(self, mid):
        return self.Talk.client.getMessageBoxWrapUp(mid)

  def getMessageBoxWrapUpList(self, start, messageBoxCount):
        return self.Talk.client.getMessageBoxWrapUpList(start, messageBoxCount)

  """Contact"""


  def blockContact(self, mid):
        return self.Talk.client.blockContact(0, mid)


  def unblockContact(self, mid):
        return self.Talk.client.unblockContact(0, mid)


  def findAndAddContactsByMid(self, mid):
        return self.Talk.client.findAndAddContactsByMid(0, mid)


  def findAndAddContactsByMids(self, midlist):
        for i in midlist:
            self.Talk.client.findAndAddContactsByMid(0, i)

  def findAndAddContactsByUserid(self, userid):
        return self.Talk.client.findAndAddContactsByUserid(0, userid)

  def findContactsByUserid(self, userid):
        return self.Talk.client.findContactByUserid(userid)

  def findContactByTicket(self, ticketId):
        return self.Talk.client.findContactByUserTicket(ticketId)

  def getAllContactIds(self):
        return self.Talk.client.getAllContactIds()

  def getBlockedContactIds(self):
        return self.Talk.client.getBlockedContactIds()

  def getContact(self, mid):
        return self.Talk.client.getContact(mid)

  def getContacts(self, midlist):
        return self.Talk.client.getContacts(midlist)

  def getFavoriteMids(self):
        return self.Talk.client.getFavoriteMids()

  def getHiddenContactMids(self):
        return self.Talk.client.getHiddenContactMids()


  """Group"""

  def findGroupByTicket(self, ticketId):
        return self.Talk.client.findGroupByTicket(ticketId)

  def acceptGroupInvitation(self, groupId):
        return self.Talk.client.acceptGroupInvitation(0, groupId)

  def acceptGroupInvitationByTicket(self, groupId, ticketId):
        return self.Talk.client.acceptGroupInvitationByTicket(0, groupId, ticketId)

  def cancelGroupInvitation(self, groupId, contactIds):
        return self.Talk.client.cancelGroupInvitation(0, groupId, contactIds)

  def createGroup(self, name, midlist):
        return self.Talk.client.createGroup(0, name, midlist)

  def getGroup(self, groupId):
        return self.Talk.client.getGroup(groupId)

  def getGroups(self, groupIds):
        return self.Talk.client.getGroups(groupIds)

  def getGroupIdsInvited(self):
        return self.Talk.client.getGroupIdsInvited()

  def getGroupIdsJoined(self):
        return self.Talk.client.getGroupIdsJoined()

  def inviteIntoGroup(self, groupId, midlist):
        return self.Talk.client.inviteIntoGroup(0, groupId, midlist)

  def kickoutFromGroup(self, groupId, midlist):
        return self.Talk.client.kickoutFromGroup(0, groupId, midlist)

  def leaveGroup(self, groupId):
        return self.Talk.client.leaveGroup(0, groupId)

  def rejectGroupInvitation(self, groupId):
        return self.Talk.client.rejectGroupInvitation(0, groupId)

  def reissueGroupTicket(self, groupId):
        return self.Talk.client.reissueGroupTicket(groupId)

  def updateGroup(self, groupObject):
        return self.Talk.client.updateGroup(0, groupObject)
  def findGroupByTicket(self,ticketId):
        return self.Talk.client.findGroupByTicket(0,ticketId)

  """Room"""

  def createRoom(self, midlist):
    return self.Talk.client.createRoom(0, midlist)

  def getRoom(self, roomId):
    return self.Talk.client.getRoom(roomId)

  def inviteIntoRoom(self, roomId, midlist):
    return self.Talk.client.inviteIntoRoom(0, roomId, midlist)

  def leaveRoom(self, roomId):
    return self.Talk.client.leaveRoom(0, roomId)

  """TIMELINE"""

  def new_post(self, text):
    return self.channel.new_post(text)

  def like(self, mid, postid, likeType=1001):
    return self.channel.like(mid, postid, likeType)

  def comment(self, mid, postid, text):
    return self.channel.comment(mid, postid, text)

  def activity(self, limit=20):
    return self.channel.activity(limit)

  def getAlbum(self, gid):

      return self.channel.getAlbum(gid)
  def changeAlbumName(self, gid, name, albumId):
      return self.channel.changeAlbumName(gid, name, albumId)

  def deleteAlbum(self, gid, albumId):
      return self.channel.deleteAlbum(gid,albumId)

  def getNote(self,gid, commentLimit, likeLimit):
      return self.channel.getNote(gid, commentLimit, likeLimit)

  def getDetail(self,mid):
      return self.channel.getDetail(mid)

  def getHome(self,mid):
      return self.channel.getHome(mid)

  def createAlbum(self, gid, name):
      return self.channel.createAlbum(gid,name)

  def createAlbum2(self, gid, name, path):
      return self.channel.createAlbum(gid, name, path, oid)
      
  """Personalize"""
    
  def cloneContactProfile(self, mid):
      contact = self.getContact(mid)
      profile = self.getProfile()
      profile.displayName = contact.displayName
      profile.statusMessage = contact.statusMessage
      profile.pictureStatus = contact.pictureStatus
      self.updateDisplayPicture(profile.pictureStatus)
      return self.updateProfile(profile)
  
  def updateDisplayPicture(self, hash_id):
      return self.Talk.client.updateProfileAttribute(0, 8, hash_id)
            
  def __validate(self, mail, passwd, cert, token, qr):
    if mail is not None and passwd is not None and cert is None:
      return 1
    elif mail is not None and passwd is not None and cert is not None:
      return 2
    elif token is not None:
      return 3
    elif qr is True:
      return 4
    else:
      return 5

  def loginResult(self, callback=None):
    if callback is None:
      callback = def_callback

      prof = self.getProfile()

      print("==============[✟Ƥɾøтøтуρє✟一�:緑 BOT]==============")
      print("           Thanks for TCR and my friend")
      print("====================================================")
      print("MID : " + prof.mid)
      print("NAME : " + prof.displayName)
      print("authToken :  " + self.authToken)
      print("cert : " + self.cert if self.cert is not None else "")
Example #21
0
class LINE:

    mid = None
    authToken = None
    cert = None
    channel_access_token = None
    token = None
    obs_token = None
    refresh_token = None

    def __init__(self):
        self.Talk = Talk()
        self._session = requests.session()

    def login(self,
              mail=None,
              passwd=None,
              cert=None,
              token=None,
              qr=False,
              callback=None):
        if callback is None:
            callback = def_callback
        resp = self.__validate(mail, passwd, cert, token, qr)
        if resp == 1:
            self.Talk.login(mail, passwd, callback=callback)
        elif resp == 2:
            self.Talk.login(mail, passwd, cert, callback=callback)
        elif resp == 3:
            self.Talk.TokenLogin(token)
        elif resp == 4:
            self.Talk.qrLogin(callback)
        else:
            raise Exception("invalid arguments")

        self.authToken = self.Talk.authToken
        self.cert = self.Talk.cert

        self.Poll = Poll(self.authToken)
        self.channel = channel.Channel(self.authToken)
        self.channel.login()

        self.mid = self.channel.mid
        self.channel_access_token = self.channel.channel_access_token
        self.token = self.channel.token
        self.obs_token = self.channel.obs_token
        self.refresh_token = self.channel.refresh_token
        self._headers = {
            'X-Line-Application': 'IOSIPAD\t7.18.0\tiPhone OS\t11.12.1',
            'X-Line-Access': self.authToken,
            'User-Agent': 'Mozilla/5.0'
        }

    """User"""

    def getProfile(self):
        return self.Talk.client.getProfile()

    def getSettings(self):
        return self.Talk.client.getSettings()

    def getUserTicket(self):
        return self.Talk.client.getUserTicket()

    def updateProfile(self, profileObject):
        return self.Talk.client.updateProfile(0, profileObject)

    def updateSettings(self, settingObject):
        return self.Talk.client.updateSettings(0, settingObject)

    """Operation"""

    def fetchOperation(self, revision, count):
        return self.Poll.client.fetchOperations(revision, count)

    def fetchOps(self, rev, count):
        return self.Poll.client.fetchOps(rev, count, 0, 0)

    def getLastOpRevision(self):
        return self.Talk.client.getLastOpRevision()

    def stream(self):
        return self.Poll.stream()

    """Message"""

    def yt(query):
        with requests.session() as s:
            isi = []
            if query == "":
                query = "S1B tanysyz"
            s.headers['user-agent'] = 'Mozilla/5.0'
            url = 'http://www.youtube.com/results'
            params = {'search_query': query}
            r = s.get(url, params=params)
            soup = BeautifulSoup(r.content, 'html5lib')
            for a in soup.select('.yt-lockup-title > a[title]'):
                if '&list=' not in a['href']:
                    if 'watch?v' in a['href']:
                        b = a['href'].replace('watch?v=', '')
                        isi += ['youtu.be' + b]
            return isi

    def kedapkedip(self, tomid, text):
        M = Message()
        M.to = tomid
        t1 = "\xf4\x80\xb0\x82\xf4\x80\xb0\x82\xf4\x80\xb0\x82\xf4\x80\xb0\x82"
        t2 = "\xf4\x80\x82\xb3\xf4\x8f\xbf\xbf"
        rst = t1 + text + t2
        M.text = rst.replace("\n", " ")
        return self.Talk.client.sendMessage(0, M)

    def sendMessage(self, messageObject):
        return self.Talk.client.sendMessage(0, messageObject)

    def sendText(self, Tomid, text):
        msg = Message()
        msg.to = Tomid
        msg.text = text

        return self.Talk.client.sendMessage(0, msg)

    def post_content(self, url, data=None, files=None):
        return self._session.post(url,
                                  headers=self._headers,
                                  data=data,
                                  files=files)

    def sendImage(self, to_, path):
        M = Message(to=to_, text=None, contentType=1)
        M.contentMetadata = None
        M.contentPreview = None
        M_id = self.Talk.client.sendMessage(0, M).id
        files = {
            'file': open(path, 'rb'),
        }
        params = {
            'name': 'media',
            'oid': M_id,
            'size': len(open(path, 'rb').read()),
            'type': 'image',
            'ver': '1.0',
        }
        data = {'params': json.dumps(params)}
        r = self.post_content('https://os.line.naver.jp/talk/m/upload.nhn',
                              data=data,
                              files=files)
        print r
        if r.status_code != 201:
            raise Exception('Upload image failure.')
        return True

    def sendImageWithURL(self, to_, url):
        """Send a image with given image url
        :param url: image url to send
        """
        path = 'pythonLine.data'
        r = requests.get(url, stream=True)
        if r.status_code == 200:
            with open(path, 'w') as f:
                shutil.copyfileobj(r.raw, f)
        else:
            raise Exception('Download image failure.')
        try:
            self.sendImage(to_, path)
        except Exception as e:
            raise e

    def sendAudioWithURL(self, to_, url):
        path = 'pythonLiness.data'
        r = requests.get(url, stream=True)
        if r.status_code == 200:
            with open(path, 'w') as f:
                shutil.copyfileobj(r.raw, f)
        else:
            raise Exception('Download Audio failure.')
        try:
            self.sendAudio(to_, path)
        except Exception as e:
            raise e

    def sendAudio(self, to_, path):
        M = Message(to=to_, contentType=3)
        M.contentMetadata = None
        M.contentPreview = None
        M_id = self.Talk.client.sendMessage(0, M).id
        files = {
            'file': open(path, 'rb'),
        }
        params = {
            'name': 'media',
            'oid': M_id,
            'size': len(open(path, 'rb').read()),
            'type': 'audio',
            'ver': '1.0',
        }
        data = {'params': json.dumps(params)}
        r = self.post_content('https://os.line.naver.jp/talk/m/upload.nhn',
                              data=data,
                              files=files)
        if r.status_code != 201:
            raise Exception('Upload image failure.')
        return True

    def sendVideo(self, to_, path):
        M = Message(to=to_, contentType=2)
        M.contentMetadata = {'VIDLEN': '0', 'DURATION': '0'}
        M.contentPreview = None
        M_id = self.Talk.client.sendMessage(0, M).id
        files = {
            'file': open(path, 'rb'),
        }
        params = {
            'name': 'media',
            'oid': M_id,
            'size': len(open(path, 'rb').read()),
            'type': 'video',
            'ver': '1.0',
        }
        data = {'params': json.dumps(params)}
        r = self.post_content('https://os.line.naver.jp/talk/m/upload.nhn',
                              data=data,
                              files=files)
        if r.status_code != 201:
            raise Exception('Upload image failure.')
        return True

    def sendVideoWithURL(self, to_, url):
        path = 'pythonLines.data'
        r = requests.get(url, stream=True)
        if r.status_code == 200:
            with open(path, 'w') as f:
                shutil.copyfileobj(r.raw, f)
        else:
            raise Exception('Download Audio failure.')
        try:
            self.sendVideo(to_, path)
        except Exception as e:
            raise e

    def download_page(url):
        version = (3, 0)
        cur_version = sys.version_info
        if cur_version >= version:  #If the Current Version of Python is 3.0 or above
            import urllib, request  #urllib library for Extracting web pages
            try:
                headers = {}
                headers[
                    'User-Agent'] = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"
                req = urllib, request.Request(url, headers=headers)
                resp = urllib, request.urlopen(req)
                respData = str(resp.read())
                return respData
            except Exception as e:
                print(str(e))
        else:  #If the Current Version of Python is 2.x
            import urllib2
            try:
                headers = {}
                headers[
                    'User-Agent'] = "Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.27 Safari/537.17"
                req = urllib2.Request(url, headers=headers)
                response = urllib2.urlopen(req)
                page = response.read()
                return page
            except:
                return "Page Not found"

    def _images_get_next_item(s):
        start_line = s.find('rg_di')
        if start_line == -1:  #If no links are found then give an error!
            end_quote = 0
            link = "no_links"
            return link, end_quote
        else:
            start_line = s.find('"class="rg_meta"')
            start_content = s.find('"ou"', start_line + 90)
            end_content = s.find(',"ow"', start_content - 90)
            content_raw = str(s[start_content + 6:end_content - 1])
            return content_raw, end_content

    def _images_get_all_items(page):
        items = []
        while True:
            item, end_content = _images_get_next_item(page)
            if item == "no_links":
                break
            else:
                items.append(
                    item)  #Append all the links in the list named 'Links'
                time.sleep(
                    0.1
                )  #Timer could be used to slow down the request for image downloads
                page = page[end_content:]
        return items

    def sendEvent(self, messageObject):
        return self._client.sendEvent(0, messageObject)

    def sendChatChecked(self, mid, lastMessageId):
        return self.Talk.client.sendChatChecked(0, mid, lastMessageId)

    def getMessageBoxCompactWrapUp(self, mid):
        return self.Talk.client.getMessageBoxCompactWrapUp(mid)

    def getMessageBoxCompactWrapUpList(self, start, messageBox):
        return self.Talk.client.getMessageBoxCompactWrapUpList(
            start, messageBox)

    def getRecentMessages(self, messageBox, count):
        return self.Talk.client.getRecentMessages(messageBox.id, count)

    def getMessageBox(self, channelId, messageboxId, lastMessagesCount):
        return self.Talk.client.getMessageBox(channelId, messageboxId,
                                              lastMessagesCount)

    def getMessageBoxList(self, channelId, lastMessagesCount):
        return self.Talk.client.getMessageBoxList(channelId,
                                                  ntlastMessagesCount)

    def getMessageBoxListByStatus(self, channelId, lastMessagesCount, status):
        return self.Talk.client.getMessageBoxListByStatus(
            channelId, lastMessagesCount, status)

    def getMessageBoxWrapUp(self, mid):
        return self.Talk.client.getMessageBoxWrapUp(mid)

    def getMessageBoxWrapUpList(self, start, messageBoxCount):
        return self.Talk.client.getMessageBoxWrapUpList(start, messageBoxCount)

    def getCover(self, mid):
        h = self.getHome(mid)
        objId = h["result"]["homeInfo"]["objectId"]
        return "http://dl.profile.line-cdn.net/myhome/c/download.nhn?userid=" + mid + "&oid=" + objId

    """Contact"""

    def CloneContactProfile(self, mid):
        contact = self.getContact(mid)
        profile = self.getProfile()
        profile.displayName = contact.displayName
        profile.statusMessage = contact.statusMessage
        profile.pictureStatus = contact.pictureStatus
        self.updateProfilePicture(profile.pictureStatus)
        return self.updateProfile(profile)

    def updateDisplayPicture(self, hash_id):
        return self.Talk.client.updateProfileAttribute(0, 8, hash_id)

    def updateProfilePicture(self, hash_id):
        return self.Talk.client.updateProfileAttribute(0, 8, hash_id)

    def blockContact(self, mid):
        return self.Talk.client.blockContact(0, mid)

    def unblockContact(self, mid):
        return self.Talk.client.unblockContact(0, mid)

    def findAndAddContactsByMid(self, mid):
        return self.Talk.client.findAndAddContactsByMid(0, mid)

    def findAndAddContactsByMids(self, midlist):
        for i in midlist:
            self.Talk.client.findAndAddContactsByMid(0, i)

    def findAndAddContactsByUserid(self, userid):
        return self.Talk.client.findAndAddContactsByUserid(0, userid)

    def findContactsByUserid(self, userid):
        return self.Talk.client.findContactByUserid(userid)

    def findContactByTicket(self, ticketId):
        return self.Talk.client.findContactByUserTicket(ticketId)

    def getAllContactIds(self):
        return self.Talk.client.getAllContactIds()

    def getBlockedContactIds(self):
        return self.Talk.client.getBlockedContactIds()

    def getContact(self, mid):
        return self.Talk.client.getContact(mid)

    def getContacts(self, midlist):
        return self.Talk.client.getContacts(midlist)

    def getFavoriteMids(self):
        return self.Talk.client.getFavoriteMids()

    def getHiddenContactMids(self):
        return self.Talk.client.getHiddenContactMids()

    """Group"""

    def findGroupByTicket(self, ticketId):
        return self.Talk.client.findGroupByTicket(ticketId)

    def acceptGroupInvitation(self, groupId):
        return self.Talk.client.acceptGroupInvitation(0, groupId)

    def acceptGroupInvitationByTicket(self, groupId, ticketId):
        return self.Talk.client.acceptGroupInvitationByTicket(
            0, groupId, ticketId)

    def cancelGroupInvitation(self, groupId, contactIds):
        return self.Talk.client.cancelGroupInvitation(0, groupId, contactIds)

    def createGroup(self, name, midlist):
        return self.Talk.client.createGroup(0, name, midlist)

    def getGroup(self, groupId):
        return self.Talk.client.getGroup(groupId)

    def getGroups(self, groupIds):
        return self.Talk.client.getGroups(groupIds)

    def getGroupIdsInvited(self):
        return self.Talk.client.getGroupIdsInvited()

    def getGroupIdsJoined(self):
        return self.Talk.client.getGroupIdsJoined()

    def inviteIntoGroup(self, groupId, midlist):
        return self.Talk.client.inviteIntoGroup(0, groupId, midlist)

    def kickoutFromGroup(self, groupId, midlist):
        return self.Talk.client.kickoutFromGroup(0, groupId, midlist)

    def leaveGroup(self, groupId):
        return self.Talk.client.leaveGroup(0, groupId)

    def rejectGroupInvitation(self, groupId):
        return self.Talk.client.rejectGroupInvitation(0, groupId)

    def reissueGroupTicket(self, groupId):
        return self.Talk.client.reissueGroupTicket(groupId)

    def updateGroup(self, groupObject):
        return self.Talk.client.updateGroup(0, groupObject)

    def findGroupByTicket(self, ticketId):
        return self.Talk.client.findGroupByTicket(0, ticketId)

    """Room"""

    def createRoom(self, midlist):
        return self.Talk.client.createRoom(0, midlist)

    def getRoom(self, roomId):
        return self.Talk.client.getRoom(roomId)

    def inviteIntoRoom(self, roomId, midlist):
        return self.Talk.client.inviteIntoRoom(0, roomId, midlist)

    def leaveRoom(self, roomId):
        return self.Talk.client.leaveRoom(0, roomId)

    def kedapkedip(self, tomid, text):
        M = Message()
        M.to = tomid
        t1 = "\xf4\x80\xb0\x82\xf4\x80\xb0\x82\xf4\x80\xb0\x82\xf4\x80\xb0\x82\xf4\x80\xa0\x81\xf4\x80\xa0\x81\xf4\x80\xa0\x81"
        t2 = "\xf4\x80\x82\xb3\xf4\x8f\xbf\xbf"
        rst = t1 + text + t2
        M.text = rst.replace("\n", " ")
        return self.Talk.client.sendMessage(0, M)

    """TIMELINE"""

    def new_post(self, text):
        return self.channel.new_post(text)

    def like(self, mid, postid, likeType=1001):
        return self.channel.like(mid, postid, likeType)

    def comment(self, mid, postid, text):
        return self.channel.comment(mid, postid, text)

    def activity(self, limit=20):
        return self.channel.activity(limit)

    def getAlbum(self, gid):

        return self.channel.getAlbum(gid)

    def changeAlbumName(self, gid, name, albumId):
        return self.channel.changeAlbumName(gid, name, albumId)

    def deleteAlbum(self, gid, albumId):
        return self.channel.deleteAlbum(gid, albumId)

    def getNote(self, gid, commentLimit, likeLimit):
        return self.channel.getNote(gid, commentLimit, likeLimit)

    def getDetail(self, mid):
        return self.channel.getDetail(mid)

    def getHome(self, mid):
        return self.channel.getHome(mid)

    def createAlbum(self, gid, name):
        return self.channel.createAlbum(gid, name)

    def createAlbum2(self, gid, name, path):
        return self.channel.createAlbum(gid, name, path, oid)

    def __validate(self, mail, passwd, cert, token, qr):
        if mail is not None and passwd is not None and cert is None:
            return 1
        elif mail is not None and passwd is not None and cert is not None:
            return 2
        elif token is not None:
            return 3
        elif qr is True:
            return 4
        else:
            return 5

    def loginResult(self, callback=None):
        if callback is None:
            callback = def_callback

            prof = self.getProfile()

            print("==============[TEAM_LONGOR]==============")
            print("     Thanks for TCR and my friend")
            print("=====================================")
            print("mid -> " + prof.mid)
            print("name -> " + prof.displayName)
            print("authToken -> " + self.authToken)
            print("cert -> " + self.cert if self.cert is not None else "")
Example #22
0
class LINE:

  mid = None
  authToken = None
  cert = None
  channel_access_token = None
  token = None
  obs_token = None
  refresh_token = None


  def __init__(self):
    self.Talk = Talk()
    self._session = requests.session()
    self._headers = {'X-Line-Application': 'CHROMEOS\t1.4.17\tChrome_OS\t1', 'X-Line-Access': 'En0Kl8eQg3MYwWKB8DEc.skwgztg4SuqUu1exNpTcpa.vSCA046duToTEnhEGM8gpCCyFrPbRMMPOQlNu+orAa4=', 'User-Agent': 'Line/1.4.17 iPad4,1 9.0.2'}

  def login(self, mail=None, passwd=None, cert=None, token=None, qr=False, callback=None):
    if callback is None:
      callback = def_callback
    resp = self.__validate(mail,passwd,cert,token,qr)
    if resp == 1:
      self.Talk.login(mail, passwd, callback=callback)
    elif resp == 2:
      self.Talk.login(mail,passwd,cert, callback=callback)
    elif resp == 3:
      self.Talk.TokenLogin(token)
    elif resp == 4:
      self.Talk.qrLogin(callback)
    else:
      raise Exception("invalid arguments")

    self.authToken = self.Talk.authToken
    self.cert = self.Talk.cert
    self._headers = {
              'X-Line-Application': 'CHROMEOS\t1.4.17\tChrome_OS\t1',
              'X-Line-Access': self.authToken,
              'User-Agent': 'Line/1.4.17'
   }

    self.Poll = Poll(self.authToken)
    """self.channel = channel.Channel(self.authToken)
    self.channel.login()

    self.mid = self.channel.mid
    self.channel_access_token = self.channel.channel_access_token
    self.token = self.channel.token
    self.obs_token = self.channel.obs_token
    self.refresh_token = self.channel.refresh_token"""

  """User"""

  def getProfile(self):
    return self.Talk.client.getProfile()

  def getSettings(self):
    return self.Talk.client.getSettings()

  def getUserTicket(self):
    return self.Talk.client.getUserTicket()

  def updateProfile(self, profileObject):
    return self.Talk.client.updateProfile(0, profileObject)

  def updateSettings(self, settingObject):
    return self.Talk.client.updateSettings(0, settingObject)

  def CloneContactProfile(self, mid):
    contact = self.getContact(mid)
    profile = self.getProfile()
    profile.displayName = contact.displayName
    profile.statusMessage = contact.statusMessage
    profile.pictureStatus = contact.pictureStatus
    self.updateDisplayPicture(profile.pictureStatus)
    return self.updateProfile(profile)

  def updateDisplayPicture(self, hash_id):
    return self.Talk.client.updateProfileAttribute(0, 8, hash_id)

    """File"""

  def deleteFile(self, path):
        if os.path.exists(path):
            os.remove(path)
            return True
        else:
            return False

  def downloadFileURL(self, fileUrl, returnAs='path', saveAs=''):
        if returnAs not in ['path','bool','bin']:
            raise Exception('Invalid returnAs value')
        if saveAs == '':
            saveAs = self.genTempFile()
        r = self.server.getContent(fileUrl)
        if r.status_code == 200:
            with open(saveAs, 'wb') as f:
                shutil.copyfileobj(r.raw, f)
            if returnAs == 'path':
                return saveAs
            elif returnAs == 'bool':
                return True
            elif returnAs == 'bin':
                return r.raw
        else:
            raise Exception('Download file failure.')

  def genTempFile(self, returnAs='path'):
        try:
            if returnAs not in ['file','path']:
                raise Exception('Invalid returnAs value')
            fName, fPath = 'linepy-%s-%i.bin' % (int(time.time()), randint(0, 9)), tempfile.gettempdir()
            if returnAs == 'file':
                return fName
            elif returnAs == 'path':
                return '%s/%s' % (fPath, fName)
        except:
            raise Exception('tempfile is required')

  def genOBSParams(self, newList, returnAs='json'):
        oldList = {'name': self.genTempFile('file'),'ver': '1.0'}
        if returnAs not in ['json','b64','default']:
            raise Exception('Invalid parameter returnAs')
        oldList.update(newList)
        if 'range' in oldList:
            new_range='bytes 0-%s\/%s' % ( str(oldList['range']-1), str(oldList['range']) )
            oldList.update({'range': new_range})
        if returnAs == 'json':
            oldList=json.dumps(oldList)
            return oldList
        elif returnAs == 'b64':
            oldList=json.dumps(oldList)
            return base64.b64encode(oldList.encode('utf-8'))
        elif returnAs == 'default':
            return oldList


  """Personalize"""

  def updateProfilePicture(self, path, type='p'):
        files = {'file': open(path, 'rb')}
        params = {'oid': self.profile.mid,'type': 'image'}
        if type == 'vp':
            params.update({'ver': '2.0', 'cat': 'vp.mp4'})
        data = {'params': self.genOBSParams(params)}
        r = self.server.postContent(self.server.LINE_OBS_DOMAIN + '/talk/p/upload.nhn', data=data, files=files)
        if r.status_code != 201:
            raise Exception('Update profile picture failure.')
        return True

  def updateProfileVideoPicture(self, path):
        try:
            from ffmpy import FFmpeg
            files = {'file': open(path, 'rb')}
            data = {'params': self.genOBSParams({'oid': self.profile.mid,'ver': '2.0','type': 'video','cat': 'vp.mp4'})}
            r_vp = self.server.postContent(self.server.LINE_OBS_DOMAIN + '/talk/vp/upload.nhn', data=data, files=files)
            if r_vp.status_code != 201:
                raise Exception('Update profile video picture failure.')
            path_p = self.genTempFile('path')
            ff = FFmpeg(inputs={'%s' % path: None}, outputs={'%s' % path_p: ['-ss', '00:00:2', '-vframes', '1']})
            ff.run()
            self.updateProfilePicture(path_p, 'vp')
        except:
            raise Exception('You should install FFmpeg and ffmpy from pypi')

  """Object"""

  def downloadObjectMsg(self, messageId, returnAs='path', saveAs=''):
        if saveAs == '':
            saveAs = self.genTempFile('path')
        if returnAs not in ['path','bool','bin']:
            raise Exception('Invalid returnAs value')
        params = {'oid': messageId}
        url = self.server.urlEncode(self.server.LINE_OBS_DOMAIN, '/talk/m/download.nhn', params)
        r = self.server.getContent(url)
        if r.status_code == 200:
            with open(saveAs, 'wb') as f:
                shutil.copyfileobj(r.raw, f)
            if returnAs == 'path':
                return saveAs
            elif returnAs == 'bool':
                return True
            elif returnAs == 'bin':
                return r.raw
        else:
            raise Exception('Download object failure.')

  def forwardObjectMsg(self, to, msgId, contentType='image'):
        if contentType not in ['image','video','audio']:
            raise Exception('Type not valid.')
        data = self.genOBSParams({'oid': 'reqseq','reqseq': self.revision,'type': contentType,'copyFrom': '/talk/m/%s' % msgId},'default')
        r = self.server.postContent(self.server.LINE_OBS_DOMAIN + '/talk/m/copy.nhn', data=data)
        if r.status_code != 200:
            raise Exception('Forward object failure.')
        return True


  """Operation"""

  def fetchOperation(self, revision, count):
        return self.Poll.client.fetchOperations(revision, count)

  def fetchOps(self, rev, count):
        return self.Poll.client.fetchOps(rev, count, 0, 0)

  def getLastOpRevision(self):
        return self.Talk.client.getLastOpRevision()

  def stream(self):
        return self.Poll.stream()

  def downloadFileURL(self, fileUrl, returnAs='path', saveAs=''):
        if returnAs not in ['path','bool','bin']:
            raise Exception('Invalid returnAs value')
        if saveAs == '':
            saveAs = self.genTempFileName()
        r = self.server.getContent(fileUrl)
        if r.status_code == 200:
            with open(saveAs, 'wb') as f:
                shutil.copyfileobj(r.raw, f)
            if returnAs == 'path':
                return saveAs
            elif returnAs == 'bool':
                return True
            elif returnAs == 'bin':
                return r.raw
        else:
            raise Exception('Download file failure.')

  
  """Message"""

  def sendMessage(self, messageObject):
        return self.Talk.client.sendMessage(0,messageObject)

  def removeAllMessages(self, lastMessageId):
	return self.Talk.client.removeAllMessages(0,lastMessageId)

  def sendText(self, Tomid, text):
        msg = Message()
        msg.to = Tomid
        msg.text = text

        return self.Talk.client.sendMessage(0, msg)

  def kedapkedip(self, tomid, text):
        M = Message()
        M.to = tomid
        t1 = "\xf4\x80\xb0\x82\xf4\x80\xb0\x82\xf4\x80\xb0\x82\xf4\x80\xb0\x82\xf4\x80\xa0\x81\xf4\x80\xa0\x81\xf4\x80\xa0\x81"
        t2 = "\xf4\x80\x82\xb3\xf4\x8f\xbf\xbf"
        rst = t1 + text + t2
        M.text = rst.replace("\n", " ")
        return self.Talk.client.sendMessage(0, M)

  def zalgo(self, tomid, text):
        M = Message()
        M.to = tomid
        du = [' ̍',' ̎',' ̄',' ̅',' ̿',' ̑',' ̆',' ̐',' ͒',' ͗',' ͑',' ̇',' ̈',' ̊',' ͂',' ̓',' ̈́',' ͊',' ͋',' ͌',' ̃',' ̂',' ̌',' ͐',' ́',' ̋',' ̏',' ̽',' ̉',' ͣ',' ͤ',' ͥ',' ͦ',' ͧ',' ͨ',' ͩ',' ͪ',' ͫ',' ͬ',' ͭ',' ͮ',' ͯ',' ̾',' ͛',' ͆',' ̚',]
        dm = [' ̕',' ̛',' ̀',' ́',' ͘',' ̡',' ̢',' ̧',' ̨',' ̴',' ̵',' ̶',' ͜',' ͝',' ͞',' ͟',' ͠',' ͢',' ̸',' ̷',' ͡',]
        rst = du + text + dm
        M.text = rst.replace("\n", " ")
        return self.Talk.client.sendMessage(0, M)

  def post_content(self, url, data=None, files=None):
        return self._session.post(url, headers=self._headers, data=data, files=files)

  def sendImage(self, to_, path):
        M = Message(to=to_, text=None, contentType = 1)
        M.contentMetadata = None
        M.contentPreview = None
        M_id = self.Talk.client.sendMessage(0,M).id
        files = {
            'file': open(path, 'rb'),
        }
        params = {
            'name': 'media',
            'oid': M_id,
            'size': len(open(path, 'rb').read()),
            'type': 'image',
            'ver': '1.0',
        }
        data = {
            'params': json.dumps(params)            
        }       

        r = self.post_content('http://os.line.naver.jp/talk/m/upload.nhn', data=data, files=files)
        #print r
        if r.status_code != 201:
            raise Exception('Upload image failure.')
        return True

  def sendImageWithUrl(self, to_, url):
        path = '%s/pythonLine-%1.data' % (tempfile.gettempdir(), randint(0, 9))
        r = requests.get(url, stream=True, verify=False)
        if r.status_code == 200:
           with open(path, 'w') as f:
              shutil.copyfileobj(r.raw, f)
        else:
           raise Exception('Download image failure.')
        try:
            self.sendImage(to_, path)
        except Exception as e:
            raise e

  def sendAudio(self, to_, path):
        M = Message(to=to_, text=None, contentType = 3)
        M.contentMetadata = None
        M.contentPreview = None
        M_id = self.Talk.client.sendMessage(0,M).id
        files = {
            'file': open(path, 'rb'),
        }
        params = {
            'name': 'media',
            'oid': M_id,
            'size': len(open(path, 'rb').read()),
            'type': 'audio',
            'ver': '1.0',
        }
        data = {
            'params': json.dumps(params)
        }

        r = self.post_content('http://os.line.naver.jp/talk/m/upload.nhn', data=data, files=files)
	print r
        if r.status_code != 201:
            raise Exception('Upload audio failure.')
        return True

  def sendAudioWithUrl(self, to_, url):
        path = '%s/pythonLine-%1.data' % (tempfile.gettempdir(), randint(0, 9))
        r = requests.get(url, stream=True)
        if r.status_code == 200:
           with open(path, 'w') as f:
              shutil.copyfileobj(r.raw, f)
        else:
           raise Exception('Download audio failure.')
        try:
            self.sendAudio(to_, path)
        except Exception as e:
            raise e

  def sendVideo(self, to_, path):
      M = Message(to=to_,contentType = 2)
      M.contentMetadata = {
           'VIDLEN' : '0',
           'DURATION' : '0'
       }
      M.contentPreview = None
      M_id = self.Talk.client.sendMessage(0,M).id
      files = {
         'file': open(path, 'rb'),
      }
      params = {
         'name': 'media',
         'oid': M_id,
         'size': len(open(path, 'rb').read()),
         'type': 'video',
         'ver': '1.0',
      }
      data = {
         'params': json.dumps(params)
      }
      r = self.post_content('https://os.line.naver.jp/talk/m/upload.nhn', data=data, files=files)
      if r.status_code != 201:
         raise Exception('Upload image failure.')
      return True
      
  def sendVideoWithUrl(self, to_, url):
      path = 'pythonLines.data'
      r = requests.get(url, stream=True)
      if r.status_code == 200:
         with open(path, 'w') as f:
            shutil.copyfileobj(r.raw, f)
      else:
         raise Exception('Download Audio failure.')
      try:
         self.sendVideo(to_, path)
      except Exception as e:
         raise e


  def sendEvent(self, messageObject):
        return self._client.sendEvent(0, messageObject)

  def sendChatChecked(self, mid, lastMessageId):
        return self.Talk.client.sendChatChecked(0, mid, lastMessageId)

  def getMessageBoxCompactWrapUp(self, mid):
        return self.Talk.client.getMessageBoxCompactWrapUp(mid)

  def getMessageBoxCompactWrapUpList(self, start, messageBox):
        return self.Talk.client.getMessageBoxCompactWrapUpList(start, messageBox)

  def getRecentMessages(self, messageBox, count):
        return self.Talk.client.getRecentMessages(messageBox.id, count)

  def getMessageBox(self, channelId, messageboxId, lastMessagesCount):
        return self.Talk.client.getMessageBox(channelId, messageboxId, lastMessagesCount)

  def getMessageBoxList(self, channelId, lastMessagesCount):
        return self.Talk.client.getMessageBoxList(channelId, lastMessagesCount)

  def getMessageBoxListByStatus(self, channelId, lastMessagesCount, status):
        return self.Talk.client.getMessageBoxListByStatus(channelId, lastMessagesCount, status)

  def getMessageBoxWrapUp(self, mid):
        return self.Talk.client.getMessageBoxWrapUp(mid)

  def getMessageBoxWrapUpList(self, start, messageBoxCount):
        return self.Talk.client.getMessageBoxWrapUpList(start, messageBoxCount)

  """Contact"""


  def blockContact(self, mid):
        return self.Talk.client.blockContact(0, mid)


  def unblockContact(self, mid):
        return self.Talk.client.unblockContact(0, mid)


  def findAndAddContactsByMid(self, mid):
        return self.Talk.client.findAndAddContactsByMid(0, mid)


  def findAndAddContactsByMids(self, midlist):
        for i in midlist:
            self.Talk.client.findAndAddContactsByMid(0, i)

  def findAndAddContactsByUserid(self, userid):
        return self.Talk.client.findAndAddContactsByUserid(0, userid)

  def findContactsByUserid(self, userid):
        return self.Talk.client.findContactByUserid(userid)

  def findContactByTicket(self, ticketId):
        return self.Talk.client.findContactByUserTicket(ticketId)

  def getAllContactIds(self):
        return self.Talk.client.getAllContactIds()

  def getBlockedContactIds(self):
        return self.Talk.client.getBlockedContactIds()

  def getContact(self, mid):
        return self.Talk.client.getContact(mid)

  def getContacts(self, midlist):
        return self.Talk.client.getContacts(midlist)

  def getFavoriteMids(self):
        return self.Talk.client.getFavoriteMids()

  def getHiddenContactMids(self):
        return self.Talk.client.getHiddenContactMids()


  """Group"""

  def findGroupByTicket(self, ticketId):
        return self.Talk.client.findGroupByTicket(ticketId)

  def acceptGroupInvitation(self, groupId):
        return self.Talk.client.acceptGroupInvitation(0, groupId)

  def acceptGroupInvitationByTicket(self, groupId, ticketId):
        return self.Talk.client.acceptGroupInvitationByTicket(0, groupId, ticketId)

  def cancelGroupInvitation(self, groupId, contactIds):
        return self.Talk.client.cancelGroupInvitation(0, groupId, contactIds)

  def createGroup(self, name, midlist):
        return self.Talk.client.createGroup(0, name, midlist)

  def getGroup(self, groupId):
        return self.Talk.client.getGroup(groupId)

  def getGroups(self, groupIds):
        return self.Talk.client.getGroups(groupIds)

  def getGroupIdsInvited(self):
        return self.Talk.client.getGroupIdsInvited()

  def getGroupIdsJoined(self):
        return self.Talk.client.getGroupIdsJoined()

  def inviteIntoGroup(self, groupId, midlist):
        return self.Talk.client.inviteIntoGroup(0, groupId, midlist)

  def kickoutFromGroup(self, groupId, midlist):
        return self.Talk.client.kickoutFromGroup(0, groupId, midlist)

  def leaveGroup(self, groupId):
        return self.Talk.client.leaveGroup(0, groupId)

  def rejectGroupInvitation(self, groupId):
        return self.Talk.client.rejectGroupInvitation(0, groupId)

  def reissueGroupTicket(self, groupId):
        return self.Talk.client.reissueGroupTicket(groupId)

  def updateGroup(self, groupObject):
        return self.Talk.client.updateGroup(0, groupObject)
  def findGroupByTicket(self,ticketId):
        return self.Talk.client.findGroupByTicket(0,ticketId)

#  def acquireGroupCallRoute(self, groupId):
 #       return self.Talk.client.call.acquireGroupCallRoute(groupId)

  #def acquireGroupCallRoute(self, groupId):
#        return self.Talk.client.call.acquireGroupCallRoute(groupId)

#  def getGroupCall(self, ChatMid):
 #       return self.Talk.client.call.getGroupCall(ChatMid)

  #def inviteIntoGroupCall(self, chatId, contactIds=[]):
   #     return self.Talk.client.call.inviteIntoGroupCall(chatId, contactIds)

  def updateGroupPicture(self, groupId, path):
        files = {'file': open(path, 'rb')}
        data = {'params': self.genOBSParams({'oid': groupId,'type': 'image'})}
        r = self.server.postContent(self.server.LINE_OBS_DOMAIN + '/talk/g/upload.nhn', data=data, files=files)
        if r.status_code != 201:
            raise Exception('Update group picture failure.')
        return True

  """Room"""

  def createRoom(self, midlist):
    return self.Talk.client.createRoom(0, midlist)

  def getRoom(self, roomId):
    return self.Talk.client.getRoom(roomId)

  def inviteIntoRoom(self, roomId, midlist):
    return self.Talk.client.inviteIntoRoom(0, roomId, midlist)

  def leaveRoom(self, roomId):
    return self.Talk.client.leaveRoom(0, roomId)

  """TIMELINE"""

  def new_post(self, text):
    return self.channel.new_post(text)

  def like(self, mid, postid, likeType=1001):
    return self.channel.like(mid, postid, likeType)

  def comment(self, mid, postid, text):
    return self.channel.comment(mid, postid, text)

  def activity(self, limit=20):
    return self.channel.activity(limit)

  def getAlbum(self, gid):

      return self.channel.getAlbum(gid)
  def changeAlbumName(self, gid, name, albumId):
      return self.channel.changeAlbumName(gid, name, albumId)

  def deleteAlbum(self, gid, albumId):
      return self.channel.deleteAlbum(gid,albumId)

  def getNote(self,gid, commentLimit, likeLimit):
      return self.channel.getNote(gid, commentLimit, likeLimit)

  def getDetail(self,mid):
      return self.channel.getDetail(mid)

  def getHome(self,mid):
      return self.channel.getHome(mid)

  def createAlbum(self, gid, name):
      return self.channel.createAlbum(gid,name)

  def createAlbum2(self, gid, name, path):
      return self.channel.createAlbum(gid, name, path, oid)

  def __validate(self, mail, passwd, cert, token, qr):
    if mail is not None and passwd is not None and cert is None:
      return 1
    elif mail is not None and passwd is not None and cert is not None:
      return 2
    elif token is not None:
      return 3
    elif qr is True:
      return 4
    else:
      return 5

  def loginResult(self, callback=None):
    if callback is None:
      callback = def_callback

      prof = self.getProfile()

      print("Creator By:•─ ͜͡✫ѕєʟғвот[☆-❍ণហ ざণاعနัю❍ีざန-☆]κɪcκєʀ ͜͡✫─•")
      print("mid -> " + prof.mid)
      print("name -> " + prof.displayName)
      print("authToken -> " + self.authToken)
      print("cert -> " + self.cert if self.cert is not None else "")
Example #23
0
class LINE:

  mid = None
  authToken = None
  cert = None
  channel_access_token = None
  token = None
  obs_token = None
  refresh_token = None


  def __init__(self):
    self.Talk = Talk()
    self._session = requests.session()
    self._headers = {'X-Line-Application': 'WINPHONE.1.7.0.71.WindowsPhone.7.10.7720'': 'Emp1jl3qOjxCjXEhmaN5.QdLXoVPaKOU6WpvD80Sijq.NcwnmLOaI/dIyi3Y84WTCOxbNTN27m3ODDpkMLDPY64=', 'User-Agent': 'WindowsPhone 1.7.0.71'}

  def login(self, mail=None, passwd=None, cert=None, token=None, qr=False, callback=None):
    if callback is None:
      callback = def_callback
    resp = self.__validate(mail,passwd,cert,token,qr)
    if resp == 1:
      self.Talk.login(mail, passwd, callback=callback)
    elif resp == 2:
      self.Talk.login(mail,passwd,cert, callback=callback)
    elif resp == 3:
      self.Talk.TokenLogin(token)
    elif resp == 4:
      self.Talk.qrLogin(callback)
    else:
      raise Exception("invalid arguments")

    self.authToken = self.Talk.authToken
    self.cert = self.Talk.cert
    self._headers = {
              'X-Line-Application': 'WINPHONE.1.7.0.71.WindowsPhone.7.10.7720'', 
              'X-Line-Access': self.authToken, 
              'User-Agent': 'WindowsPhone 1.7.0.71'
   }
    self.Poll = Poll(self.authToken)
    #self.channel = channel.Channel(self.authToken)
    #self.channel.login()	
    #self.mid = self.channel.mid
    #self.channel_access_token = self.channel.channel_access_token
    #self.token = self.channel.token
    #self.obs_token = self.channel.obs_token
    #self.refresh_token = self.channel.refresh_token


  """User"""

  def getProfile(self):
    return self.Talk.client.getProfile()

  def getSettings(self):
    return self.Talk.client.getSettings()

  def getUserTicket(self):
    return self.Talk.client.getUserTicket()

  def updateProfile(self, profileObject):
    return self.Talk.client.updateProfile(0, profileObject)

  def updateSettings(self, settingObject):
    return self.Talk.client.updateSettings(0, settingObject)

  def CloneContactProfile(self, mid):
    contact = self.getContact(mid)
    profile = self.getProfile()
    profile.displayName = contact.displayName
    profile.statusMessage = contact.statusMessage
    profile.pictureStatus = contact.pictureStatus
    self.updateDisplayPicture(profile.pictureStatus)
    return self.updateProfile(profile)

  def updateDisplayPicture(self, hash_id):
    return self.Talk.client.updateProfileAttribute(0, 8, hash_id)

  def updateProfilePicture(self, path):
        file=open(path, 'rb')
        files = {
            'file': file
        }
        params = {
            'name': 'media',
            'type': 'image',
            'oid': self.profile.mid,
            'ver': '1.0',
        }
        data={
            'params': json.dumps(params)
        }
        r = self.server.postContent(self.server.LINE_OBS_DOMAIN + '/talk/p/upload.nhn', data=data, files=files)
        if r.status_code != 201:
            raise Exception('Update profile picture failure.')
        return True

  """Operation"""

  def fetchOperation(self, revision, count):
        return self.Poll.client.fetchOperations(revision, count)

  def fetchOps(self, rev, count):
        return self.Poll.client.fetchOps(rev, count, 0, 0)

  def getLastOpRevision(self):
        return self.Talk.client.getLastOpRevision()

  def stream(self):
        return self.Poll.stream()

  """Message"""

  def sendMessage(self, messageObject):
        return self.Talk.client.sendMessage(0,messageObject)

  def removeAllMessage(self, messageObject):
        return self.Talk.client.removeAllMessage(0,lastMessageId)

  def sendText(self, Tomid, text):
        msg = Message()
        msg.to = Tomid
        msg.text = text

        return self.Talk.client.sendMessage(0, msg)
  def post_content(self, url, data=None, files=None):
        return self._session.post(url, headers=self._headers, data=data, files=files)

  def sendImage(self, to_, path):
        M = Message(to=to_, text=None, contentType = 1)
        M.contentMetadata = None
        M.contentPreview = None
        M_id = self.Talk.client.sendMessage(0,M).id
        files = {
            'file': open(path, 'rb'),
        }
        params = {
            'name': 'media',
            'oid': M_id,
            'size': len(open(path, 'rb').read()),
            'type': 'image',
            'ver': '1.0',
        }
        data = {
            'params': json.dumps(params)            
        }       

        r = self.post_content('https://os.line.naver.jp/talk/m/upload.nhn', data=data, files=files)
        #print r
        if r.status_code != 201:
            raise Exception('Upload image failure.')
        return True

  def sendImageWithUrl(self, to_, url):
        """Send a image with given image url

        :param url: image url to send
        """
        path = '%s/pythonLine-%1.data' % (tempfile.gettempdir(), randint(0, 9))


        r = requests.get(url, stream=True)
        if r.status_code == 200:
            with open(path, 'w') as f:
                shutil.copyfileobj(r.raw, f)
        else:
            raise Exception('Download image failure.')

        try:
            self.sendImage(to_, path)
        except Exception as e:
            raise e

  def sendVideo(self, to_, path):
        M = Message(to=to_, text=None, contentType = 2)
        M.contentMetadata = None
        M.contentPreview = None
        M2 = self.Talk.client.sendMessage(0,M)
        M_id = M2.id
        files = {
            'file': open(path, 'rb'),
        }
        params = {
            'name': 'media',
            'oid': M_id,
            'size': len(open(path, 'rb').read()),
            'type': 'video',
            'ver': '1.0',
        }
        data = {
            'params': json.dumps(params)
        }
        r = self.post_content('https://os.line.naver.jp/talk/m/upload.nhn', data=data, files=files)
        #print r
        if r.status_code != 201:
            raise Exception('Upload video failure.')
        return True

  def sendVideoWithURL(self, to_, url):
        path = '%s/pythonLine-%i.data' % (tempfile.gettempdir(), randint(0, 9))

        r = requests.get(url, stream=True)
        if r.status_code == 200:
            with open(path, 'w') as f:
                shutil.copyfileobj(r.raw, f)
        else:
            raise Exception('Download video failure.')

        try:
            self.sendVideo(to_, path)
        except Exception as e:
            raise (e)

  def sendAudio(self, to_, path):
        M = Message(to=to_, text=None, contentType = 3)
        M.contentMetadata = None
        M.contentPreview = None
        M2 = self.Talk.client.sendMessage(0,M)
        M_id = M2.id
        files = {
            'file': open(path, 'rb'),
        }
        params = {
            'name': 'media',
            'oid': M_id,
            'size': len(open(path, 'rb').read()),
            'type': 'audio',
            'ver': '1.0',
        }
        data = {
            'params': json.dumps(params)
        }
        r = self.post_content('https://os.line.naver.jp/talk/m/upload.nhn', data=data, files=files)
        if r.status_code != 201:
            raise Exception('Upload audio failure.')
        return True

  def sendAudioWithUrl(self, to_, url):
        path = '%s/pythonLine-%1.data' % (tempfile.gettempdir(), randint(0, 9))

        r = requests.get(url, stream=True)
        if r.status_code == 200:
            with open(path, 'w') as f:
                shutil.copyfileobj(r.raw, f)
        else:
            raise Exception('Download audio failure.')

        try:
            self.sendAudio(to_, path)
        except Exception as e:
            raise (e)
            
  def upload_tempimage(client):
        config = {
          'album': album,
          'name':  'bot auto upload',
          'title': 'bot auto upload',
          'description': 'bot auto upload'
          }
        print("Uploading image... ")
        image = client.upload_from_path(image_path, config=config, anon=False)
        print("Done")
        print()
    
  def translate(to_translate, to_language="auto", language="auto"):
    base_link = "http://translate.google.com/m?hl=%s&sl=%s&q=%s"
    if (six.PY2):
        link = base_link % (to_language, language, urllib.pathname2url(to_translate))
        request = urllib2.Request(link, headers=agent)
        page = urllib2.urlopen(request).read()
    else:
        link = base_link % (to_language, language, urllib.parse.quote(to_translate))
        request = urllib.request.Request(link, headers=agent)
        page = urllib.request.urlopen(request).read().decode("utf-8")
    expr = r'class="t0">(.*?)<'
    result = re.findall(expr, page)
    if (len(result) == 0):
        return (result[0])
    return(result[0])
  
  def download_page(url):
    version = (3,0)
    cur_version = sys.version_info
    if cur_version >= version:     #If the Current Version of Python is 3.0 or above
        import urllib,request    #urllib library for Extracting web pages
        try:
            headers = {}
            headers['User-Agent'] = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"
            req = urllib,request.Request(url, headers = headers)
            resp = urllib,request.urlopen(req)
            respData = str(resp.read())
            return respData
        except Exception as e:
            print(str(e))
    else:                        #If the Current Version of Python is 2.x
        import urllib2
        try:
            headers = {}
            headers['User-Agent'] = "Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.27 Safari/537.17"
            req = urllib2.Request(url, headers = headers)
            response = urllib2.urlopen(req)
            page = response.read()
            return page
        except:
            return"Page Not found"
  
  def removeAllMessages(self, lastMessageId):
	return self.Talk.client.removeAllMessages(0, lastMessageId)

  def sendEvent(self, messageObject):
        return self._client.sendEvent(0, messageObject)

  def sendChatChecked(self, mid, lastMessageId):
        return self.Talk.client.sendChatChecked(0, mid, lastMessageId)

  def getMessageBoxCompactWrapUp(self, mid):
        return self.Talk.client.getMessageBoxCompactWrapUp(mid)

  def getMessageBoxCompactWrapUpList(self, start, messageBox):
        return self.Talk.client.getMessageBoxCompactWrapUpList(start, messageBox)

  def getRecentMessages(self, messageBox, count):
        return self.Talk.client.getRecentMessages(messageBox.id, count)

  def getMessageBox(self, channelId, messageboxId, lastMessagesCount):
        return self.Talk.client.getMessageBox(channelId, messageboxId, lastMessagesCount)

  def getMessageBoxList(self, channelId, lastMessagesCount):
        return self.Talk.client.getMessageBoxList(channelId, lastMessagesCount)

  def getMessageBoxListByStatus(self, channelId, lastMessagesCount, status):
        return self.Talk.client.getMessageBoxListByStatus(channelId, lastMessagesCount, status)

  def getMessageBoxWrapUp(self, mid):
        return self.Talk.client.getMessageBoxWrapUp(mid)

  def getMessageBoxWrapUpList(self, start, messageBoxCount):
        return self.Talk.client.getMessageBoxWrapUpList(start, messageBoxCount)

  """Contact"""


  def blockContact(self, mid):
        return self.Talk.client.blockContact(0, mid)


  def unblockContact(self, mid):
        return self.Talk.client.unblockContact(0, mid)


  def findAndAddContactsByMid(self, mid):
        return self.Talk.client.findAndAddContactsByMid(0, mid)


  def findAndAddContactsByMids(self, midlist):
        for i in midlist:
            self.Talk.client.findAndAddContactsByMid(0, i)

  def findAndAddContactsByUserid(self, userid):
        return self.Talk.client.findAndAddContactsByUserid(0, userid)

  def findContactsByUserid(self, userid):
        return self.Talk.client.findContactByUserid(userid)

  def findContactByTicket(self, ticketId):
        return self.Talk.client.findContactByUserTicket(ticketId)

  def getAllContactIds(self):
        return self.Talk.client.getAllContactIds()

  def getBlockedContactIds(self):
        return self.Talk.client.getBlockedContactIds()

  def getContact(self, mid):
        return self.Talk.client.getContact(mid)

  def getContacts(self, midlist):
        return self.Talk.client.getContacts(midlist)

  def getFavoriteMids(self):
        return self.Talk.client.getFavoriteMids()

  def getHiddenContactMids(self):
        return self.Talk.client.getHiddenContactMids()


  """Group"""

  def findGroupByTicket(self, ticketId):
        return self.Talk.client.findGroupByTicket(ticketId)

  def acceptGroupInvitation(self, groupId):
        return self.Talk.client.acceptGroupInvitation(0, groupId)

  def acceptGroupInvitationByTicket(self, groupId, ticketId):
        return self.Talk.client.acceptGroupInvitationByTicket(0, groupId, ticketId)

  def cancelGroupInvitation(self, groupId, contactIds):
        return self.Talk.client.cancelGroupInvitation(0, groupId, contactIds)

  def createGroup(self, name, midlist):
        return self.Talk.client.createGroup(0, name, midlist)

  def getGroup(self, groupId):
        return self.Talk.client.getGroup(groupId)

  def getGroups(self, groupIds):
        return self.Talk.client.getGroups(groupIds)

  def getGroupIdsInvited(self):
        return self.Talk.client.getGroupIdsInvited()

  def getGroupIdsJoined(self):
        return self.Talk.client.getGroupIdsJoined()

  def inviteIntoGroup(self, groupId, midlist):
        return self.Talk.client.inviteIntoGroup(0, groupId, midlist)

  def kickoutFromGroup(self, groupId, midlist):
        return self.Talk.client.kickoutFromGroup(0, groupId, midlist)

  def leaveGroup(self, groupId):
        return self.Talk.client.leaveGroup(0, groupId)

  def rejectGroupInvitation(self, groupId):
        return self.Talk.client.rejectGroupInvitation(0, groupId)

  def reissueGroupTicket(self, groupId):
        return self.Talk.client.reissueGroupTicket(groupId)

  def updateGroup(self, groupObject):
        return self.Talk.client.updateGroup(0, groupObject)
  def findGroupByTicket(self,ticketId):
        return self.Talk.client.findGroupByTicket(0,ticketId)

  """Room"""

  def createRoom(self, midlist):
    return self.Talk.client.createRoom(0, midlist)

  def getRoom(self, roomId):
    return self.Talk.client.getRoom(roomId)

  def inviteIntoRoom(self, roomId, midlist):
    return self.Talk.client.inviteIntoRoom(0, roomId, midlist)

  def leaveRoom(self, roomId):
    return self.Talk.client.leaveRoom(0, roomId)

  """TIMELINE"""

  def new_post(self, text):
    return self.channel.new_post(text)

  def like(self, mid, postid, likeType=1001):
    return self.channel.like(mid, postid, likeType)

  def comment(self, mid, postid, text):
    return self.channel.comment(mid, postid, text)

  def activity(self, limit=20):
    return self.channel.activity(limit)

  def getAlbum(self, gid):

      return self.channel.getAlbum(gid)
  def changeAlbumName(self, gid, name, albumId):
      return self.channel.changeAlbumName(gid, name, albumId)

  def deleteAlbum(self, gid, albumId):
      return self.channel.deleteAlbum(gid,albumId)

  def getNote(self,gid, commentLimit, likeLimit):
      return self.channel.getNote(gid, commentLimit, likeLimit)

  def getDetail(self,mid):
      return self.channel.getDetail(mid)

  def getHome(self,mid):
      return self.channel.getHome(mid)

  def createAlbum(self, gid, name):
      return self.channel.createAlbum(gid,name)

  def createAlbum2(self, gid, name, path):
      return self.channel.createAlbum(gid, name, path, oid)


  def __validate(self, mail, passwd, cert, token, qr):
    if mail is not None and passwd is not None and cert is None:
      return 1
    elif mail is not None and passwd is not None and cert is not None:
      return 2
    elif token is not None:
      return 3
    elif qr is True:
      return 4
    else:
      return 5

  def loginResult(self, callback=None):
    if callback is None:
      callback = def_callback

      prof = self.getProfile()

      print("124D15T1 T34M B0T")
      print("mid -> " + prof.mid)
      print("Nama -> " + prof.displayName)
      print("Token -> " + self.authToken)
      print("cert -> " + self.cert if self.cert is not None else "")
Example #24
0
class LINE:

    mid = None
    authToken = None
    cert = None
    channel_access_token = None
    token = None
    obs_token = None
    refresh_token = None

    def __init__(self):
        self.Talk = Talk()

    def login(self,
              mail=None,
              passwd=None,
              cert=None,
              token=None,
              qr=False,
              callback=None):
        if callback is None:
            callback = def_callback
        resp = self.__validate(mail, passwd, cert, token, qr)
        if resp == 1:
            self.Talk.login(mail, passwd, callback=callback)
        elif resp == 2:
            self.Talk.login(mail, passwd, cert, callback=callback)
        elif resp == 3:
            self.Talk.TokenLogin(token)
        elif resp == 4:
            self.Talk.qrLogin(callback)
        else:
            raise Exception("invalid arguments")

        self.authToken = self.Talk.authToken
        self.cert = self.Talk.cert

        self.Poll = Poll(self.authToken)
        self.channel = channel.Channel(self.authToken)
        self.channel.login()

        self.mid = self.channel.mid
        self.channel_access_token = self.channel.channel_access_token
        self.token = self.channel.token
        self.obs_token = self.channel.obs_token
        self.refresh_token = self.channel.refresh_token

    """User"""

    def getProfile(self):
        return self.Talk.client.getProfile()

    def getSettings(self):
        return self.Talk.client.getSettings()

    def getUserTicket(self):
        return self.Talk.client.getUserTicket()

    def updateProfile(self, profileObject):
        return self.Talk.client.updateProfile(0, profileObject)

    def updateSettings(self, settingObject):
        return self.Talk.client.updateSettings(0, settingObject)

    """Operation"""

    def fetchOperation(self, revision, count):
        return self.Poll.client.fetchOperations(revision, count)

    def fetchOps(self, rev, count):
        return self.Poll.client.fetchOps(rev, count, 0, 0)

    def getLastOpRevision(self):
        return self.Talk.client.getLastOpRevision()

    def stream(self):
        return self.Poll.stream()

    """Message"""

    def sendMessage(self, messageObject):
        return self.Talk.client.sendMessage(0, messageObject)

    def sendText(self, tomid, text):
        msg = Message()
        msg.to = tomid
        msg.text = text

        return self.Talk.client.sendMessage(0, msg)

    def sendChatChecked(self, mid, lastMessageId):
        return self.Talk.client.sendChatChecked(0, mid, lastMessageId)

    def getMessageBoxCompactWrapUp(self, mid):
        return self.Talk.client.getMessageBoxCompactWrapUp(mid)

    def getMessageBoxCompactWrapUpList(self, start, messageBox):
        return self.Talk.client.getMessageBoxCompactWrapUpList(
            start, messageBox)

    def getRecentMessages(self, messageBox, count):
        return self.Talk.client.getRecentMessages(messageBox.id, count)

    def getMessageBox(self, channelId, messageboxId, lastMessagesCount):
        return self.Talk.client.getMessageBox(channelId, messageboxId,
                                              lastMessagesCount)

    def getMessageBoxList(self, channelId, lastMessagesCount):
        return self.Talk.client.getMessageBoxList(channelId, lastMessagesCount)

    def getMessageBoxListByStatus(self, channelId, lastMessagesCount, status):
        return self.Talk.client.getMessageBoxListByStatus(
            channelId, lastMessagesCount, status)

    def getMessageBoxWrapUp(self, mid):
        return self.Talk.client.getMessageBoxWrapUp(mid)

    def getMessageBoxWrapUpList(self, start, messageBoxCount):
        return self.Talk.client.getMessageBoxWrapUpList(start, messageBoxCount)

    """Contact"""

    def blockContact(self, mid):
        return self.Talk.client.blockContact(0, mid)

    def unblockContact(self, mid):
        return self.Talk.client.unblockContact(0, mid)

    def findAndAddContactsByMid(self, mid):
        return self.Talk.client.findAndAddContactsByMid(0, mid)

    def findAndAddContactsByMids(self, midlist):
        for i in midlist:
            self.Talk.client.findAndAddContactsByMid(0, i)

    def findAndAddContactsByUserid(self, userid):
        return self.Talk.client.findAndAddContactsByUserid(0, userid)

    def findContactsByUserid(self, userid):
        return self.Talk.client.findContactByUserid(userid)

    def findContactByTicket(self, ticketId):
        return self.Talk.client.findContactByUserTicket(ticketId)

    def getAllContactIds(self):
        return self.Talk.client.getAllContactIds()

    def getBlockedContactIds(self):
        return self.Talk.client.getBlockedContactIds()

    def getContact(self, mid):
        return self.Talk.client.getContact(mid)

    def getContacts(self, midlist):
        return self.Talk.client.getContacts(midlist)

    def getFavoriteMids(self):
        return self.Talk.client.getFavoriteMids()

    def getHiddenContactMids(self):
        return self.Talk.client.getHiddenContactMids()

    """Group"""

    def acceptGroupInvitation(self, groupId):
        return self.Talk.client.acceptGroupInvitation(0, groupId)

    def acceptGroupInvitationByTicket(self, groupId, ticketId):
        return self.Talk.client.acceptGroupInvitationByTicket(
            0, groupId, ticketId)

    def cancelGroupInvitation(self, groupId, contactIds):
        return self.Talk.client.cancelGroupInvitation(0, groupId, contactIds)

    def createGroup(self, name, midlist):
        return self.Talk.client.createGroup(0, name, midlist)

    def getGroup(self, groupId):
        return self.Talk.client.getGroup(groupId)

    def getGroups(self, groupIds):
        return self.Talk.client.getGroups(groupIds)

    def getGroupIdsInvited(self):
        return self.Talk.client.getGroupIdsInvited()

    def getGroupIdsJoined(self):
        return self.Talk.client.getGroupIdsJoined()

    def inviteIntoGroup(self, groupId, midlist):
        return self.Talk.client.inviteIntoGroup(0, groupId, midlist)

    def kickoutFromGroup(self, groupId, midlist):
        return self.Talk.client.kickoutFromGroup(0, groupId, midlist)

    def leaveGroup(self, groupId):
        return self.Talk.client.leaveGroup(0, groupId)

    def rejectGroupInvitation(self, groupId):
        return self.Talk.client.rejectGroupInvitation(0, groupId)

    def reissueGroupTicket(self, groupId):
        return self.Talk.client.reissueGroupTicket(groupId)

    def updateGroup(self, groupObject):
        return self.Talk.client.updateGroup(0, groupObject)

    """Room"""

    def createRoom(self, midlist):
        return self.Talk.client.createRoom(0, midlist)

    def getRoom(self, roomId):
        return self.Talk.client.getRoom(roomId)

    def inviteIntoRoom(self, roomId, midlist):
        return self.Talk.client.inviteIntoRoom(0, roomId, midlist)

    def leaveRoom(self, roomId):
        return self.Talk.client.leaveRoom(0, roomId)

    """TIMELINE"""

    def new_post(self, text):
        return self.channel.new_post(text)

    def new_note(self, gid, text):
        return self.channel.new_note(gid, text)

    def like(self, mid, postid, likeType=1001):
        return self.channel.like(mid, postid, likeType)

    def comment(self, mid, postid, text):
        return self.channel.comment(mid, postid, text)

    def activity(self, limit=20):
        return self.channel.activity(limit)

    def getAlbum(self, gid):
        return self.channel.getAlbum(gid)

    def changeAlbumName(self, gid, name, albumId):
        return self.channel.changeAlbumName(gid, name, albumId)

    def deleteAlbum(self, gid, albumId):
        return self.channel.deleteAlbum(gid, albumId)

    def getNote(self, gid, commentLimit, likeLimit):
        return self.channel.getNote(gid, commentLimit, likeLimit)

    def getDetail(self, mid):
        return self.channel.getDetail(mid)

    def getHome(self, mid):
        return self.channel.getHome(mid)

    def createAlbum(self, gid, name):
        return self.channel.createAlbum(gid, name)

    def createAlbum2(self, gid, name, path):
        return self.channel.createAlbum(gid, name, path, oid)

    def __validate(self, mail, passwd, cert, token, qr):
        if mail is not None and passwd is not None and cert is None:
            return 1
        elif mail is not None and passwd is not None and cert is not None:
            return 2
        elif token is not None:
            return 3
        elif qr is True:
            return 4
        else:
            return 5

    def loginResult(self, callback=None):
        if callback is None:
            callback = def_callback

            prof = self.getProfile()

            print("---HelloSeyu---\n")
            print("[Mid] -> " + prof.mid)
            print("[Name] -> " + prof.displayName)
            print("[AuthToken] -> " + self.authToken)
            print("[Cert] -> " + self.cert if self.cert is not None else "")
            print("---------------------\n")
Example #25
0
class LINE:

  mid = None
  authToken = None
  cert = None
  channel_access_token = None
  token = None
  obs_token = None
  refresh_token = None


  def __init__(self):
    self.Talk = Talk()

  def login(self, mail=None, passwd=None, cert=None, token=None, qr=False, callback=None):
    if callback is None:
      callback = def_callback
    resp = self.__validate(mail,passwd,cert,token,qr)
    if resp == 1:
      self.Talk.login(mail, passwd, callback=callback)
    elif resp == 2:
      self.Talk.login(mail,passwd,cert, callback=callback)
    elif resp == 3:
      self.Talk.TokenLogin(token)
    elif resp == 4:
      self.Talk.qrLogin(callback)
    else:
      raise Exception("invalid arguments")

    self.authToken = self.Talk.authToken
    self.cert = self.Talk.cert

    self.Poll = Poll(self.authToken)
    self.channel = channel.Channel(self.authToken)
    self.channel.login()

    self.mid = self.channel.mid
    self.channel_access_token = self.channel.channel_access_token
    self.token = self.channel.token
    self.obs_token = self.channel.obs_token
    self.refresh_token = self.channel.refresh_token


  """User"""

  def getProfile(self):
    return self.Talk.client.getProfile()

  def getSettings(self):
    return self.Talk.client.getSettings()

  def getUserTicket(self):
    return self.Talk.client.getUserTicket()

  def updateProfile(self, profileObject):
    return self.Talk.client.updateProfile(0, profileObject)

  def updateSettings(self, settingObject):
    return self.Talk.client.updateSettings(0, settingObject)


  """Operation"""

  def fetchOperation(self, revision, count):
        return self.Poll.client.fetchOperations(revision, count)

  def fetchOps(self, rev, count):
        return self.Poll.client.fetchOps(rev, count, 0, 0)

  def getLastOpRevision(self):
        return self.Talk.client.getLastOpRevision()

  def stream(self):
        return self.Poll.stream()

  """Message"""

  def sendMessage(self, messageObject):
        return self.Talk.client.sendMessage(0,messageObject)

  def sendText(self, Tomid, text):
        msg = Message()
        msg.to = Tomid
        msg.text = text

        return self.Talk.client.sendMessage(0, msg)
  def sendImage(self, to_, path):
        M = Message(to=to_,contentType = 1)
        M.contentMetadata = None
        M.contentPreview = None
        M_id = self._client.sendMessage(M).id
        files = {
            'file': open(path, 'rb'),
        }
        params = {
            'name': 'media',
            'oid': M_id,
            'size': len(open(path, 'rb').read()),
            'type': 'image',
            'ver': '1.0',
        }
        data = {
            'params': json.dumps(params)
        }
        r = self._client.post_content('https://os.line.naver.jp/talk/m/upload.nhn', data=data, files=files)
        if r.status_code != 201:
            raise Exception('Upload image failure.')
        #r.content
        return True
  def sendEvent(self, messageObject):
        return self._client.sendEvent(0, messageObject)

  def sendChatChecked(self, mid, lastMessageId):
        return self.Talk.client.sendChatChecked(0, mid, lastMessageId)

  def getMessageBoxCompactWrapUp(self, mid):
        return self.Talk.client.getMessageBoxCompactWrapUp(mid)

  def getMessageBoxCompactWrapUpList(self, start, messageBox):
        return self.Talk.client.getMessageBoxCompactWrapUpList(start, messageBox)

  def getRecentMessages(self, messageBox, count):
        return self.Talk.client.getRecentMessages(messageBox.id, count)

  def getMessageBox(self, channelId, messageboxId, lastMessagesCount):
        return self.Talk.client.getMessageBox(channelId, messageboxId, lastMessagesCount)

  def getMessageBoxList(self, channelId, lastMessagesCount):
        return self.Talk.client.getMessageBoxList(channelId, lastMessagesCount)

  def getMessageBoxListByStatus(self, channelId, lastMessagesCount, status):
        return self.Talk.client.getMessageBoxListByStatus(channelId, lastMessagesCount, status)

  def getMessageBoxWrapUp(self, mid):
        return self.Talk.client.getMessageBoxWrapUp(mid)

  def getMessageBoxWrapUpList(self, start, messageBoxCount):
        return self.Talk.client.getMessageBoxWrapUpList(start, messageBoxCount)

  """Contact"""


  def blockContact(self, mid):
        return self.Talk.client.blockContact(0, mid)


  def unblockContact(self, mid):
        return self.Talk.client.unblockContact(0, mid)


  def findAndAddContactsByMid(self, mid):
        return self.Talk.client.findAndAddContactsByMid(0, mid)


  def findAndAddContactsByMids(self, midlist):
        for i in midlist:
            self.Talk.client.findAndAddContactsByMid(0, i)

  def findAndAddContactsByUserid(self, userid):
        return self.Talk.client.findAndAddContactsByUserid(0, userid)

  def findContactsByUserid(self, userid):
        return self.Talk.client.findContactByUserid(userid)

  def findContactByTicket(self, ticketId):
        return self.Talk.client.findContactByUserTicket(ticketId)

  def getAllContactIds(self):
        return self.Talk.client.getAllContactIds()

  def getBlockedContactIds(self):
        return self.Talk.client.getBlockedContactIds()

  def getContact(self, mid):
        return self.Talk.client.getContact(mid)

  def getContacts(self, midlist):
        return self.Talk.client.getContacts(midlist)

  def getFavoriteMids(self):
        return self.Talk.client.getFavoriteMids()

  def getHiddenContactMids(self):
        return self.Talk.client.getHiddenContactMids()


  """Group"""

  def findGroupByTicket(self, ticketId):
        return self.Talk.client.findGroupByTicket(ticketId)

  def acceptGroupInvitation(self, groupId):
        return self.Talk.client.acceptGroupInvitation(0, groupId)

  def acceptGroupInvitationByTicket(self, groupId, ticketId):
        return self.Talk.client.acceptGroupInvitationByTicket(0, groupId, ticketId)

  def cancelGroupInvitation(self, groupId, contactIds):
        return self.Talk.client.cancelGroupInvitation(0, groupId, contactIds)

  def createGroup(self, name, midlist):
        return self.Talk.client.createGroup(0, name, midlist)

  def getGroup(self, groupId):
        return self.Talk.client.getGroup(groupId)

  def getGroups(self, groupIds):
        return self.Talk.client.getGroups(groupIds)

  def getGroupIdsInvited(self):
        return self.Talk.client.getGroupIdsInvited()

  def getGroupIdsJoined(self):
        return self.Talk.client.getGroupIdsJoined()

  def inviteIntoGroup(self, groupId, midlist):
        return self.Talk.client.inviteIntoGroup(0, groupId, midlist)

  def kickoutFromGroup(self, groupId, midlist):
        return self.Talk.client.kickoutFromGroup(0, groupId, midlist)

  def leaveGroup(self, groupId):
        return self.Talk.client.leaveGroup(0, groupId)

  def rejectGroupInvitation(self, groupId):
        return self.Talk.client.rejectGroupInvitation(0, groupId)

  def reissueGroupTicket(self, groupId):
        return self.Talk.client.reissueGroupTicket(groupId)

  def updateGroup(self, groupObject):
        return self.Talk.client.updateGroup(0, groupObject)
  def findGroupByTicket(self,ticketId):
        return self.Talk.client.findGroupByTicket(0,ticketId)

  """Room"""

  def createRoom(self, midlist):
    return self.Talk.client.createRoom(0, midlist)

  def getRoom(self, roomId):
    return self.Talk.client.getRoom(roomId)

  def inviteIntoRoom(self, roomId, midlist):
    return self.Talk.client.inviteIntoRoom(0, roomId, midlist)

  def leaveRoom(self, roomId):
    return self.Talk.client.leaveRoom(0, roomId)

  """TIMELINE"""

  def new_post(self, text):
    return self.channel.new_post(text)

  def like(self, mid, postid, likeType=1001):
    return self.channel.like(mid, postid, likeType)

  def comment(self, mid, postid, text):
    return self.channel.comment(mid, postid, text)

  def activity(self, limit=20):
    return self.channel.activity(limit)

  def getAlbum(self, gid):

      return self.channel.getAlbum(gid)
  def changeAlbumName(self, gid, name, albumId):
      return self.channel.changeAlbumName(gid, name, albumId)

  def deleteAlbum(self, gid, albumId):
      return self.channel.deleteAlbum(gid,albumId)

  def getNote(self,gid, commentLimit, likeLimit):
      return self.channel.getNote(gid, commentLimit, likeLimit)

  def getDetail(self,mid):
      return self.channel.getDetail(mid)

  def getHome(self,mid):
      return self.channel.getHome(mid)

  def createAlbum(self, gid, name):
      return self.channel.createAlbum(gid,name)

  def createAlbum2(self, gid, name, path):
      return self.channel.createAlbum(gid, name, path, oid)


  def __validate(self, mail, passwd, cert, token, qr):
    if mail is not None and passwd is not None and cert is None:
      return 1
    elif mail is not None and passwd is not None and cert is not None:
      return 2
    elif token is not None:
      return 3
    elif qr is True:
      return 4
    else:
      return 5

  def loginResult(self, callback=None):
    if callback is None:
      callback = def_callback

      prof = self.getProfile()

      print("R.A-BOT")
      print("mid -> " + prof.mid)
      print("name -> " + prof.displayName)
      print("authToken -> " + self.authToken)
      print("cert -> " + self.cert if self.cert is not None else "")
Example #26
0
class LINE:

    mid = None
    authToken = None
    cert = None
    channel_access_token = None
    token = None
    obs_token = None
    refresh_token = None

    def __init__(self):
        self.Talk = Talk()
        self._session = requests.session()
        self.headers = Talk.Headers
        self.Talk.set_Headers('User-Agent', Talk.UA)
        self.Talk.set_Headers('X-Line-Application', Talk.LA)
        self.Talk.set_Headers('X-Line-Access', self.authToken)

    def login(self,
              mail=None,
              passwd=None,
              cert=None,
              token=None,
              qr=False,
              callback=None):
        if callback is None:
            callback = def_callback
        resp = self.__validate(mail, passwd, cert, token, qr)
        if resp == 1:
            self.Talk.login(mail, passwd, callback=callback)
        elif resp == 2:
            self.Talk.login(mail, passwd, cert, callback=callback)
        elif resp == 3:
            self.Talk.TokenLogin(token)
        elif resp == 4:
            self.Talk.qrLogin(callback)
        else:
            raise Exception("invalid arguments")

        self.authToken = self.Talk.authToken
        self.cert = self.Talk.cert
        self._headers = {
            'X-Line-Application':
            'CHROMEOS 1.4.17 Chrome_OS 1',
            'X-Line-Access':
            'EnqjZDxSQl7i2XELddyd.NuMlRurpLHL+gcbv0NPZpq.kwUHvDxMcbNbRLnTlPwZpCJqPlOVL0bKKXIZpwPDOuY=',
            'User-Agent':
            'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.108 Safari/537.36'
        }

        self.Poll = Poll(self.authToken)
        #self.channel = channel.Channel(self.authToken)

    # self.channel.login()

    #self.mid = self.channel.mid
    #self.channel_access_token = self.channel.channel_access_token
    # self.token = self.channel.token
    # self.obs_token = self.channel.obs_token
    # self.refresh_token = self.channel.refresh_token
    """User"""

    def getProfile(self):
        return self.Talk.client.getProfile()

    def getSettings(self):
        return self.Talk.client.getSettings()

    def getUserTicket(self):
        return self.Talk.client.getUserTicket()

    def updateProfile(self, profileObject):
        return self.Talk.client.updateProfile(0, profileObject)

    def updateSettings(self, settingObject):
        return self.Talk.client.updateSettings(0, settingObject)

    def updateProfilePicture(self, mid):
        return self.Talk.client.updateProfileAttribute(0, 8, mid)

    def cloneContactProfile(self, mid):
        contact = self.getContact(mid)
        profile = self.getProfile()
        profile.displayName = contact.displayName
        profile.statusMessage = contact.statusMessage
        profile.pictureStatus = contact.pictureStatus
        self.updateDisplayPicture(profile.pictureStatus)
        return self.updateProfile(profile)

    """Operation"""

    def fetchOperation(self, revision, count):
        return self.Poll.client.fetchOperations(revision, count)

    def fetchOps(self, rev, count):
        return self.Poll.client.fetchOps(rev, count, 0, 0)

    def getLastOpRevision(self):
        return self.Talk.client.getLastOpRevision()

    def stream(self):
        return self.Poll.stream()

    """Message"""

    def sendMessage(self, messageObject):
        return self.Talk.client.sendMessage(0, messageObject)

    def sendText(self, Tomid, text):
        msg = Message()
        msg.to = Tomid
        msg.text = text

        return self.Talk.client.sendMessage(0, msg)

    def post_content(self, url, data=None, files=None):
        return self._session.post(url,
                                  headers=self.headers,
                                  data=data,
                                  files=files)

    def sendImage(self, to_, path):
        M = Message(to=to_, text=None, contentType=1)
        M.contentMetadata = None
        M.contentPreview = None
        M2 = self.Talk.client.sendMessage(0, M)
        M_id = M2.id
        files = {
            'file': open(path, 'rb'),
        }
        params = {
            'name': 'media',
            'oid': M_id,
            'size': len(open(path, 'rb').read()),
            'type': 'image',
            'ver': '1.0',
        }
        data = {'params': json.dumps(params)}
        r = self.post_content('https://os.line.naver.jp/talk/m/upload.nhn',
                              data=data,
                              files=files)
        if r.status_code != 201:
            raise Exception('Upload image failure.')
        #r.content
        return True

    def sendImageWithURL(self, to_, url):
        path = '%s/pythonLine-%i.data' % (tempfile.gettempdir(),
                                          random.randint(0, 9))

        r = requests.get(url, stream=True)
        if r.status_code == 200:
            with open(path, 'w') as f:
                shutil.copyfileobj(r.raw, f)
        else:
            raise Exception('Download image failure.')
        try:
            self.sendImage(to_, path)
        except Exception as e:
            raise e

    def SendMessageWithMention(self, to_, text, data=[]):
        arr = []
        if '[list]' in text.lower():
            list_text = '\n@'
            list_text = list_text.join(str(l[1]) for i in data)
            text = text.replace('[list]', list_text)
        elif '@' in text:
            text = text
        else:
            list_text = ' @'
            list_text += list_text.join(str(l[1]) for i in data)
            text = text + list_text
        for l in data:
            mid = 1 [0]
            name = '@%s' % l[1]
            ln_text = text.replace('\n', ' ')
            length_n = len(name)
            if ln_text.find(name):
                line_s = ln_text.index(name)
                line_e = (int(line_s) + int(length_n))
            arrData = {'S': str(line_s), 'E': str(line_e), 'M': mid}
            arr.append(arrData)
        contentMetadata = {
            'MENTION':
            str('{"MENTIONEES":' + json.dumps(arr).replace(' ', '') + '}')
        }
        return self.sendMessage(to, text, contentMetadata)

    def sendAudioWithURL(self, to_, url):
        path = '/pythonLine.data'
        r = requests.get(url, stream=True)
        if r.status_code == 200:
            with open(path, 'w') as f:
                shutil.copyfileobj(r.raw, f)
        else:
            raise Exception('Download Audio failure.')
        try:
            self.sendAudio(to_, path)
        except Exception as e:
            raise e

    def sendAudio(self, to_, path):
        M = Message(to=to_, contentType=3)
        M.contentMetadata = None
        M.contentPreview = None
        M_id = self.Talk.client.sendMessage(0, M).id
        files = {
            'file': open(path, 'rb'),
        }
        params = {
            'name': 'media',
            'oid': M_id,
            'size': len(open(path, 'rb').read()),
            'type': 'audio',
            'ver': '1.0',
        }
        data = {'params': json.dumps(params)}
        r = self.post_content('https://os.line.naver.jp/talk/m/upload.nhn',
                              data=data,
                              files=files)
        if r.status_code != 201:
            raise Exception('Upload image failure.')
        return True

    def sendVideo(self, to_, path):
        M = Message(to=to_, contentType=2)
        M.contentMetadata = {'VIDLEN': '0', 'DURATION': '0'}
        M.contentPreview = None
        M_id = self.Talk.client.sendMessage(0, M).id
        files = {
            'file': open(path, 'rb'),
        }
        params = {
            'name': 'media',
            'oid': M_id,
            'size': len(open(path, 'rb').read()),
            'type': 'video',
            'ver': '1.0',
        }
        data = {'params': json.dumps(params)}
        r = self.post_content('https://os.line.naver.jp/talk/m/upload.nhn',
                              data=data,
                              files=files)
        if r.status_code != 201:
            raise Exception('Upload image failure.')
        return True

    def sendVideoWithURL(self, to_, url):
        path = '/pythonLine.data'
        r = requests.get(url, stream=True)
        if r.status_code == 200:
            with open(path, 'w') as f:
                shutil.copyfileobj(r.raw, f)
        else:
            raise Exception('Download Audio failure.')
        try:
            self.sendVideo(to_, path)
        except Exception as e:
            raise e


#  def sendGif(self, to_, path):
#     M = Message(to=to_,contentType = 1)
#    M.contentMetadata = {
#        'VIDLEN' : '0',
#       'DURATION' : '0'
#  }
#      M.contentPreview = None
#     M_id = self.Talk.client.sendMessage(0,M).id
#    files = {
#      'file': open(path, 'rb'),
#  }
#      params = {
#        'name': 'media',
#       'oid': M_id,
#      'size': len(open(path, 'rb').read()),
#     'type': 'image',
#    'ver': '1.0',
#}
#      data = {
#        'params': json.dumps(params)
#    }
#   r = self.post_content('https://os.line.naver.jp/talk/m/upload.nhn', data=data, files=files)
#  if r.status_code != 201:
#    raise Exception('Upload Gif failure.')
#return True
#  def sendGifWithURL(self, to_, url):
#     path = '/pythonLine.data'
#    r = requests.get(url, stream=True)
#   if r.status_code == 200:
#     with open(path, 'w') as f:
#       shutil.copyfileobj(r.raw, f)
#else:
#  raise Exception('Download Gif failure.')
#      try:
#        self.sendGif(to_, path)
#    except Exception as e:
#      raise e

    def download_page(url):
        version = (3, 0)
        cur_version = sys.version_info
        if cur_version >= version:  #If the Current Version of Python is 3.0 or above
            import urllib.request  #urllib library for Extracting web pages
            try:
                headers = {}
                headers[
                    'User-Agent'] = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"
                req = urllib.request.Request(url, headers=headers)
                resp = urllib.request.urlopen(req)
                respData = str(resp.read())
                return respData
            except Exception as e:
                print(str(e))
        else:  #If the Current Version of Python is 2.x
            import urllib2
            try:
                headers = {}
                headers[
                    'User-Agent'] = "Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.27 Safari/537.17"
                req = urllib2.Request(url, headers=headers)
                response = urllib2.urlopen(req)
                page = response.read()
                return page
            except:
                return "Page Not found"

    #Finding 'Next Image' from the given raw page
    def _images_get_next_item(s):
        start_line = s.find('rg_di')
        if start_line == -1:  #If no links are found then give an error!
            end_quote = 0
            link = "no_links"
            return link, end_quote
        else:
            start_line = s.find('"class="rg_meta"')
            start_content = s.find('"ou"', start_line + 70)
            end_content = s.find(',"ow"', start_content - 70)
            content_raw = str(s[start_content + 6:end_content - 1])
            return content_raw, end_content

    #Getting all links with the help of '_images_get_next_image'
    def _images_get_all_items(page):
        items = []
        while True:
            item, end_content = _images_get_next_item(page)
            if item == "no_links":
                break
            else:
                items.append(
                    item)  #Append all the links in the list named 'Links'
                page = page[end_content:]
        return items

    def sendEvent(self, messageObject):
        return self._client.sendEvent(0, messageObject)

    def sendChatChecked(self, mid, lastMessageId):
        return self.Talk.client.sendChatChecked(0, mid, lastMessageId)

    def getMessageBoxCompactWrapUp(self, mid):
        return self.Talk.client.getMessageBoxCompactWrapUp(mid)

    def getMessageBoxCompactWrapUpList(self, start, messageBox):
        return self.Talk.client.getMessageBoxCompactWrapUpList(
            start, messageBox)

    def getRecentMessages(self, messageBox, count):
        return self.Talk.client.getRecentMessages(messageBox.id, count)

    def getMessageBox(self, channelId, messageboxId, lastMessagesCount):
        return self.Talk.client.getMessageBox(channelId, messageboxId,
                                              lastMessagesCount)

    def getMessageBoxList(self, channelId, lastMessagesCount):
        return self.Talk.client.getMessageBoxList(channelId, lastMessagesCount)

    def getMessageBoxListByStatus(self, channelId, lastMessagesCount, status):
        return self.Talk.client.getMessageBoxListByStatus(
            channelId, lastMessagesCount, status)

    def getMessageBoxWrapUp(self, mid):
        return self.Talk.client.getMessageBoxWrapUp(mid)

    def getMessageBoxWrapUpList(self, start, messageBoxCount):
        return self.Talk.client.getMessageBoxWrapUpList(start, messageBoxCount)

    def removeAllMessages(self, lastMessageId):
        return self.Talk.client.removeAllMessages(0, lastMessageId)

    """Contact"""

    def blockContact(self, mid):
        return self.Talk.client.blockContact(0, mid)

    def unblockContact(self, mid):
        return self.Talk.client.unblockContact(0, mid)

    def findAndAddContactsByMid(self, mid):
        return self.Talk.client.findAndAddContactsByMid(0, mid)

    def findAndAddContactsByMids(self, midlist):
        for i in midlist:
            self.Talk.client.findAndAddContactsByMid(0, i)

    def findAndAddContactsByUserid(self, userid):
        return self.Talk.client.findAndAddContactsByUserid(0, userid)

    def findContactsByUserid(self, userid):
        return self.Talk.client.findContactByUserid(userid)

    def findContactByTicket(self, ticketId):
        return self.Talk.client.findContactByUserTicket(ticketId)

    def getAllContactIds(self):
        return self.Talk.client.getAllContactIds()

    def getBlockedContactIds(self):
        return self.Talk.client.getBlockedContactIds()

    def getContact(self, mid):
        return self.Talk.client.getContact(mid)

    def getContacts(self, midlist):
        return self.Talk.client.getContacts(midlist)

    def getFavoriteMids(self):
        return self.Talk.client.getFavoriteMids()

    def getHiddenContactMids(self):
        return self.Talk.client.getHiddenContactMids()

    """Group"""

    def acceptGroupInvitation(self, groupId):
        return self.Talk.client.acceptGroupInvitation(0, groupId)

    def acceptGroupInvitationByTicket(self, groupId, ticketId):
        return self.Talk.client.acceptGroupInvitationByTicket(
            0, groupId, ticketId)

    def cancelGroupInvitation(self, groupId, contactIds):
        return self.Talk.client.cancelGroupInvitation(0, groupId, contactIds)

    def createGroup(self, name, midlist):
        return self.Talk.client.createGroup(0, name, midlist)

    def getGroup(self, groupId):
        return self.Talk.client.getGroup(groupId)

    def getGroups(self, groupIds):
        return self.Talk.client.getGroups(groupIds)

    def getGroupIdsInvited(self):
        return self.Talk.client.getGroupIdsInvited()

    def getGroupIdsJoined(self):
        return self.Talk.client.getGroupIdsJoined()

    def inviteIntoGroup(self, groupId, midlist):
        return self.Talk.client.inviteIntoGroup(0, groupId, midlist)

    def kickoutFromGroup(self, groupId, midlist):
        return self.Talk.client.kickoutFromGroup(0, groupId, midlist)

    def leaveGroup(self, groupId):
        return self.Talk.client.leaveGroup(0, groupId)

    def rejectGroupInvitation(self, groupId):
        return self.Talk.client.rejectGroupInvitation(0, groupId)

    def reissueGroupTicket(self, groupId):
        return self.Talk.client.reissueGroupTicket(groupId)

    def updateGroup(self, groupObject):
        return self.Talk.client.updateGroup(0, groupObject)

    def findGroupByTicket(self, ticketId):
        return self.Talk.client.findGroupByTicket(ticketId)

    """Room"""

    def createRoom(self, midlist):
        return self.Talk.client.createRoom(0, midlist)

    def getRoom(self, roomId):
        return self.Talk.client.getRoom(roomId)

    def inviteIntoRoom(self, roomId, midlist):
        return self.Talk.client.inviteIntoRoom(0, roomId, midlist)

    def leaveRoom(self, roomId):
        return self.Talk.client.leaveRoom(0, roomId)

    """TIMELINE"""

    def new_post(self, text):
        return self.channel.new_post(text)

    def like(self, mid, postid, likeType=1001):
        return self.channel.like(mid, postid, likeType)

    def comment(self, mid, postid, text):
        return self.channel.comment(mid, postid, text)

    def activity(self, limit=20):
        return self.channel.activity(limit)

    def getAlbum(self, gid):

        return self.channel.getAlbum(gid)

    def changeAlbumName(self, gid, name, albumId):
        return self.channel.changeAlbumName(gid, name, albumId)

    def deleteAlbum(self, gid, albumId):
        return self.channel.deleteAlbum(gid, albumId)

    def getNote(self, gid, commentLimit, likeLimit):
        return self.channel.getNote(gid, commentLimit, likeLimit)

    def getDetail(self, mid):
        return self.channel.getDetail(mid)

    def getHome(self, mid):
        return self.channel.getHome(mid)

    def createAlbum(self, gid, name):
        return self.channel.createAlbum(gid, name)

    def createAlbum2(self, gid, name, path):
        return self.channel.createAlbum(gid, name, path, oid)

    def __validate(self, mail, passwd, cert, token, qr):
        if mail is not None and passwd is not None and cert is None:
            return 1
        elif mail is not None and passwd is not None and cert is not None:
            return 2
        elif token is not None:
            return 3
        elif qr is True:
            return 4
        else:
            return 5

    def loginResult(self, callback=None):
        if callback is None:
            callback = def_callback

            prof = self.getProfile()

            print("One Piece Offical BOT")
            print("mid -> " + prof.mid)
            print("name -> " + prof.displayName)
            print("authToken -> " + self.authToken)
            print("cert -> " + self.cert if self.cert is not None else "")