示例#1
0
文件: tg.py 项目: dmig/xpostr
async def _get_photo(client: TelegramClient, entity: Union[types.User, types.Channel, types.Chat]):
    if not entity.photo or isinstance(
            entity.photo, (types.UserProfilePhotoEmpty, types.ChatPhotoEmpty)):
        return None

    photo = entity.photo.photo_small\
        if isinstance(entity.photo, (types.ChatPhoto, types.UserProfilePhoto))\
        else entity.photo

    filename = '{0}.{1}.jpg'.format(
        entity.id,
        md5('{e.dc_id}.{e.volume_id}.{e.local_id}.{e.secret}'.format(e=photo).encode('utf-8'))
        .hexdigest()
    )
    filepath = os.path.join(config.get('paths', 'avatars'), filename)

    if not os.path.exists(filepath):
        # if file was updated, remove old one
        for f in glob(os.path.join(config.get('paths', 'avatars'), str(entity.id) + '*.jpg')):
            os.unlink(f)

        asyncio.ensure_future(
            client.download_profile_photo(entity, file=filepath, download_big=False)
        ).add_done_callback(catch_task_exception)

    return filename
class telegram_API:
    def __init__(self):
        self.api_id = YOUR_API_ID
        self.api_hash = 'YOUR_API_HASH'

    def teleg_ch_infos(self, username):
        #chanel info
        self.client = TelegramClient('session', self.api_id,
                                     self.api_hash).start()
        entity = self.client.get_entity(username)
        ch_info = {
            'id': entity.id,
            'title': entity.title,
            'username': entity.username,
            'created_date': entity.date
        }
        return ch_info

    def teleg_ch_photo(self, username):
        #chanel image
        self.client = TelegramClient('session', self.api_id,
                                     self.api_hash).start()
        path = self.client.download_profile_photo(username)
        print(path)

    def teleg_ch_posts(self, username):
        #posts info
        self.client = TelegramClient('session', self.api_id,
                                     self.api_hash).start()
        chats = self.client.get_messages(username, 100)
        message_id = []
        message = []
        sender = []
        reply_to = []
        time = []
        if len(chats):
            for chat in chats:
                message_id.append(chat.id)
                message.append(chat.message)
                sender.append(chat.from_id)
                reply_to.append(chat.reply_to_msg_id)
                time.append(chat.date)
        data = {
            'message_id': message_id,
            'message': message,
            'sender_ID': sender,
            'reply_to_msg_id': reply_to,
            'time': time
        }
        pd.DataFrame(data).to_csv('farsna_messages.csv')
        return data
示例#3
0
class Main:
    def __init__(self):
        print("init")

        version = "20"
        if not os.path.exists(data_dir + "/version"):
            print("Writing new database")
            open(data_dir + "/version", "w").write("0")
        checkversion = str(open(data_dir + "/version", "r").readlines()[0])
        if not version == checkversion:
            print(
                "Database version is incompatible with new version, recreating it"
            )
            if os.path.exists(data_dir + "/data.db"):
                os.remove(data_dir + "/data.db")
            open(data_dir + "/version", "w").write(version)

        ldb.connect()

        try:
            ldb.create_tables([Info])
        except:
            print("Info table exists in ldb")
        try:
            ldb.create_tables([Dialogs])
        except:
            print("Dialogs table exists in ldb")
        try:
            ldb.create_tables([Chats])
        except:
            print("Chats table exists in ldb")
        try:
            ldb.create_tables([Uploads])
        except:
            print("Uploads table exists in ldb")

        ldb.close()

        self.isConnected = False
        self.ChatPartner = ""
        self.ChatPartnerID = ""
        self.ChatForceReload = False
        self.LastChatList = ""
        self.LastDialogList = ""

        self.threadTryConnect = threading.Thread(name="Connect",
                                                 target=self.Connect,
                                                 args=())

        self.getDialogs()

        self.tryConnect()

    def tryConnect(self):
        print("tryConnect")
        print(threading.enumerate())
        if not self.threadTryConnect.isAlive():
            print("starting Thread Connect")
            self.threadTryConnect.start()
        else:
            print("Waiting for Connection, Thread Connect is Already running")

    def Connect(self):
        print("Connect")

        api_id = 291651
        api_hash = '0f734eda64f8fa7dea8ed9558fd447e9'

        self.client = TelegramClient(data_dir + "/telepygram.db", api_id,
                                     api_hash)

        self.phoneNumber = ""

        print("Connect to Telegram")
        try:
            isConnected = self.client.connect()
        except:
            isConnected = False

        if isConnected:
            pyotherside.send("onlineStatus", True)

            isAuthorized = self.client.is_user_authorized()
            print("Authorized: " + str(isAuthorized))

            if not isAuthorized:
                pyotherside.send("changeFrame", "Phone")
                print("pyotherside.send(changeFrame, Phone)")

            return True
        else:
            pyotherside.send("onlineStatus", False)
            return False

    def SetChatPartner(self, name, id):
        print("SetChatPartner(name: " + str(name) + ", " + str(id) + ")")
        self.ChatPartner = name
        self.ChatPartnerID = id
        self.ChatForceReload = True
        self.getChat()

    def setPhoneNumber(self, phoneNumber):
        self.phoneNumber = phoneNumber
        print("setPhoneNumber(" + str(phoneNumber) + ")")
        self.client.send_code_request(phoneNumber)
        pyotherside.send("changeFrame", "Code")
        print("pyotherside.send(changeFrame, Code)")

    def setPhoneCode(self, phoneCode):
        print("setPhoneCode(" + str(phoneCode) + ")")
        self.client.sign_in(self.phoneNumber, phoneCode)
        pyotherside.send("changeFrame", "Dialogs")
        print("pyotherside.send(changeFrame, Dialogs)")
        self.getDialogs()

    def getDialogs(self):
        print("getDialogs function in Main.py")

        Dialoge = []
        try:
            ldb.connect()
        except:
            True
        AllDialogs = Dialogs.select()
        ldb.close()

        if not AllDialogs.exists():
            Dialoge.append({
                "name": "LOADING\nPLEASE WAIT",
                "chat_identification": "",
                "status": "",
                "timestamp": "",
                "data_dir": data_dir
            })
        else:
            for dialog in AllDialogs:
                user_status = dialog.status
                #UserStatusOffline(was_online=datetime.utcfromtimestamp(1525351401))
                if "UserStatusOnline" in user_status:  #Online
                    user_status = "green"
                    lastonlinetime = ""
                else:
                    if user_status == "UserStatusRecently()":  # Was online Recently
                        user_status = "orange"
                        lastonlinetime = ""
                    else:
                        print("User Status is " + str(user_status))
                        user_status = "red"
                        lastonlinetime = ""
                        if "UserStatusOffline" in dialog.status:
                            lastonlinetime = modules.BlueFunc.ElapsedTime(
                                dialog.status.split(
                                    "UserStatusOffline(was_online=datetime.utcfromtimestamp("
                                )[-1].replace("))", ""))

                Dialoge.append({
                    "name": dialog.name,
                    "chat_identification": dialog.identification,
                    "status": user_status,
                    "timestamp": lastonlinetime,
                    "data_dir": data_dir
                })

        #print("pyotherside.send(antwortGetDialogs, " + str(Dialoge) + ")")
        pyotherside.send("antwortGetDialogs", Dialoge)

    def reloadDialogs(self):
        print("reloadDialogs function in Main.py")

        try:
            Dialoge = []
            for dialog in self.client.get_dialogs():
                dialog_name = utils.get_display_name(dialog.entity)
                dialog_identification = dialog.entity.id
                try:
                    dialog_status = dialog.entity.status
                except:
                    dialog_status = "0"

                #print(" ")
                #print(dialog_name)
                #print(dialog.entity)
                #print(" ")

                Dialoge.append({"name": dialog_name, "status": dialog_status})
                try:
                    ldb.connect()
                except:
                    True
                query = Dialogs.select().where(
                    (Dialogs.identification == str(dialog_identification)))
                ldb.close()
                if not query.exists():
                    print("create Dialog entry " + dialog_name)
                    threading.Thread(target=self.downloadProfilePhoto,
                                     args=[dialog.entity])
                    NewDialog = Dialogs.create(
                        name=dialog_name,
                        identification=dialog_identification,
                        status=dialog_status,
                        dialog=str(dialog))
                    NewDialog.save()
                else:
                    # ToDO Test if changes

                    #print("Dialog Changed " + dialog_name)
                    ChangedDialog = Dialogs(
                        name=dialog_name,
                        identification=dialog_identification,
                        status=dialog_status,
                        dialog=str(dialog))
                    ChangedDialog.save()

                    # if no Picture
                    if not os.path.exists(data_dir + "/Pictures/Profiles/" +
                                          str(dialog_identification) + ".jpg"):
                        threading.Thread(target=self.downloadProfilePhoto,
                                         args=[dialog.entity]).start()

            #print("Dialoge: " + str(Dialoge))
            if not self.LastDialogList == Dialoge:
                self.LastDialogList = Dialoge
                self.getDialogs()

        except:
            print("getDialogs failed, no connection ?")
            self.tryConnect()

    def deleteProfilePhoto(self, id):
        print("deleteProfilePhoto(" + str(id) + ")")
        if os.path.exists(data_dir + "/Pictures/Profiles/" + str(id) + ".jpg"):
            os.remove(data_dir + "/Pictures/Profiles/" + str(id) + ".jpg")

    def downloadProfilePhoto(self, Entity):
        print("Start downloadProfilePhoto")
        print(" ")
        print(Entity)

        try:
            Image = self.client.download_profile_photo(
                Entity,
                file=data_dir + "/Pictures/Profiles/" + str(Entity.id),
                download_big=True)
            #if str(Image) == "None": self.deleteProfilePhoto(Entity.id)
            print("Image: " + str(Image))
        except:
            print("downloadProfilePhoto failed no connection ?")
            self.tryConnect()

    def sendChat(self, message):
        try:
            ldb.connect()
        except:
            True
        MessageToSend = Uploads.create(text=message,
                                       chat_id=self.ChatPartnerID)
        MessageToSend.save()
        ldb.close()
        self.getChat()

    def trySending(self):
        try:
            try:
                ldb.connect()
            except:
                True
            query = Uploads.select()
            for messages in query:
                print("Sending (" + str(messages.id) + "): " +
                      str(messages.text))
                try:
                    self.client.send_message(int(messages.chat_id),
                                             messages.text)
                    messages.delete().execute()
                except:
                    print("Error Sending")
            ldb.close()
        except:
            print("trySending failed, no connection ?")
            self.tryConnect()

    def getChat(self):
        print("getChat")
        ChatList = []
        try:
            ldb.connect()
        except:
            True
        AllChats = Chats.select().where(
            Chats.chat_id == self.ChatPartnerID).order_by(Chats.identification)

        if not AllChats.exists():
            ChatList.append({
                "chattext": "LOADING\nPLEASE WAIT",
                "out": True,
                "sender": "Telepygram",
                "read": False,
                "media": "",
                "with_media": False
            })
        else:
            for message in AllChats:
                if message.media == "":
                    with_media = False
                    media_is_video = False
                    media_is_image = False
                else:
                    with_media = True
                    medianame = str(message.media).split("/")[-1]
                    mediaformat = medianame.split(".")[-1]

                    know_videos = ["ogv", "3gp"]
                    if mediaformat in know_videos:
                        media_is_video = True
                        media_is_image = False
                    else:
                        media_is_video = False
                        media_is_image = True

                ChatList.append({
                    "media_is_video": media_is_video,
                    "media_is_image": media_is_image,
                    "chattext": message.text,
                    "out": message.out,
                    "sender": message.user_name,
                    "read": False,
                    "media": message.media,
                    "with_media": with_media
                })

        query = Uploads.select().where(
            Uploads.chat_id == self.ChatPartnerID).order_by(Uploads.id)
        ldb.close()

        for MessageToUpload in query:
            ChatList.append({
                "chattext": MessageToUpload.text,
                "out": True,
                "sender": "SENDING",
                "read": True,
                "media": ""
            })

        if not self.LastChatList == ChatList or self.ChatForceReload:
            pyotherside.send("antwortGetChat", ChatList, self.ChatPartner)
            self.LastChatList = ChatList
            self.ChatForceReload = False
        else:
            print("LastChatList = ChatList")

    def reloadChat(self, LoadNewMessages):
        print("reloadChat")
        if True:  #try:
            Dialog = GetFullUserRequest(
                self.client.get_entity(int(self.ChatPartnerID)))
            print("This Dialog " + str(Dialog))

            print("LoadNewMessages: " + str(LoadNewMessages))
            if LoadNewMessages:
                Messages = self.client.iter_messages(self.ChatPartner,
                                                     limit=10)
            else:
                try:
                    ldb.connect()
                except:
                    True

                AllSavedMessages = Chats.select().where(
                    Chats.chat_id == self.ChatPartnerID)
                SavedMessagesList = []
                for msg in AllSavedMessages:
                    SavedMessagesList.append(msg.identification)

                ldb.close()

                LastMessageLoaded = int(min(SavedMessagesList))
                print("LastMessageLoaded: " + str(LastMessageLoaded))
                Messages = self.client.iter_messages(
                    self.ChatPartner, offset_id=LastMessageLoaded, limit=10)

            for message in Messages:
                try:
                    ldb.connect()
                except:
                    True
                print("message.id " + str(message.id))
                query = Chats.select().where(
                    Chats.identification == str(message.id))
                ldb.close()
                if not query.exists():
                    print(message)
                    print(" ")

                    #print("User Name :" + str(self.client.get_entity(message.from_id)))
                    names = []
                    try:
                        user_firstname = str(
                            self.client.get_entity(message.from_id).first_name)
                    except:
                        user_firstname = self.ChatPartner
                    try:
                        user_lastname = str(
                            self.client.get_entity(message.from_id).last_name)
                    except:
                        user_lastname = "None"
                    if not user_firstname == "None":
                        names.append(user_firstname)
                    if not user_lastname == "None": names.append(user_lastname)
                    username = "******".join(names)

                    message_text = message.message
                    if message_text == None:
                        message_text = ""
                        print("action " + str(message.action))
                        if "MessageActionChatJoinedByLink" in str(
                                message.action):
                            message_text = "joined by invite link"
                        if "MessageActionChatAddUser" in str(message.action):
                            message_text = "joined"

                    username_id = str(message.from_id)
                    #print("username_id: " + username_id)

                    try:
                        message_media = str(message.media)
                    except:
                        message_media = "None"
                    if not str(message_media) == "None":
                        print("message_media: " + str(message_media))
                        file = data_dir + "/Media/" + str(message.id)
                        try:
                            file = self.client.download_media(
                                message.media,
                                file=file,
                                progress_callback=None)
                            message_media = file
                        except:
                            print("Error in Downlaod")

                    else:
                        message_media = ""

                    NewChat = Chats.create(identification=message.id,
                                           chat_id=self.ChatPartnerID,
                                           user_name=username,
                                           user_id=username_id,
                                           text=message_text,
                                           out=message.out,
                                           media=str(message_media),
                                           total_message=message)
                    NewChat.save()

                    self.getChat()
示例#4
0
    client = TelegramClient('tg', api_id, api_hash)
    client.start()

    # Initialize Google Cloud Storage
    os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "./serviceAccountKey.json"
    storage_client = storage.Client()
    bucket = storage_client.get_bucket('telerank-e9b37.appspot.com')

    # Get username from arguments
    username = sys.argv[1]

    # Get information from Telegram
    result = client(functions.channels.GetFullChannelRequest(channel=username))

    # Download photo
    client.download_profile_photo(username)
    imagePath = "./" + username + ".jpg"

    # Optimize photo
    img = Image.open(imagePath)
    new_width = 425
    new_height = 425
    resized = img.resize((new_width, new_height), Image.ANTIALIAS)
    resized.save(imagePath, optimize=True, quality=10)

    # Upload photo to google storage
    imageBlob = bucket.blob(username + ".jpg")
    imageBlob.upload_from_filename(imagePath)
    os.remove(imagePath)

    # Send result
示例#5
0
    'USERNAME',
    'FLOODSTORM \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n @username // @spam'
)
sleep(3)
client.send_message(
    'USERNAME',
    'FLOODSTORM \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n @username // @spam'
)
sleep(3)
client.send_message(
    'USERNAME',
    'FLOODSTORM \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n @username // @spam'
)
sleep(3)
client.send_message(
    'USERNAME',
    'FLOODSTORM \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n @username // @spam'
)
sleep(3)
client.send_message(
    'USERNAME',
    'FLOODSTORM \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n @username // @spam'
)
sleep(3)
'''INFORMATION:
MORE LINES = MORE MESSAGES'''
print("Messages sent!")

client.download_profile_photo(me)
messages = client.get_message_history('leavemeblank')
client.download_media(messages[0])