Exemple #1
0
def send_chat_list(client: Client, user: User, update: Union[Message,
                                                             CallbackQuery]):
    chats = AllowedChat.objects.filter(creator=user, status='activated')
    clean_chats = []
    for chat in chats:
        try:
            client.resolve_peer(chat.chat_id)
            clean_chats.append(chat)
        except ChannelInvalid as exc:
            logger.info(f'### Error {chat}: {type(exc)}: {exc}')

    if not clean_chats:
        text = user.choice_localized(text_name='msg-owner-empty')
        button_text = user.choice_localized(text_name='btn-owner-add-bot')
        bot = client.get_me()
        client.send_message(user.id,
                            text,
                            reply_markup=markup_add_to_chat(
                                bot.username, button_text))
        return

    text = user.choice_localized(text_name='msg-owner')
    if isinstance(update, Message):
        update.reply_text(text, reply_markup=markup_chat_list(clean_chats))
    if isinstance(update, CallbackQuery):
        update.message.edit_text(text,
                                 reply_markup=markup_chat_list(clean_chats))
Exemple #2
0
 def __init__(self, peer_id: int, message_id: int, parts: int,
              app: pyrogram.Client, file_name: str):
     self.app = app
     message_data = app.send(
         GetMessages(channel=(app.resolve_peer(peer_id=peer_id)),
                     id=[InputMessageID(id=message_id)]))
     self.document_data = InputDocumentFileLocation(
         id=message_data["messages"][0]["media"]["document"]["id"],
         file_reference=message_data["messages"][0]["media"]["document"]
         ["file_reference"],
         access_hash=message_data["messages"][0]["media"]["document"]
         ["access_hash"],
         thumb_size="")
     self.size = message_data["messages"][0]["media"]["document"]["size"]
     for attribute in message_data["messages"][0]["media"]["document"][
             "attributes"]:
         if type(attribute
                 ) == document_attribute_filename.DocumentAttributeFilename:
             self.file_name = attribute["file_name"]
             break
     else:
         self.file_name = file_name
     self.apple = self.change_dc(
         message_data["messages"][0]["media"]["document"]["dc_id"])
     self.parts = parts
     self.temp_folder = f"{os.getcwd()}/downloads/"
     self.check_if_temp_folder_exists()
     self.mb = self.size // (1024 * 1024)
     self.part_size_in_mbs = self.mb // parts
     self.part_size_in_bytes = self.part_size_in_mbs * (1024 * 1024)
     self.part_data = {}
     self.limit_prefix = 1048576
     self.b4 = datetime.now()
     self.done = 0
     self.calculate()
Exemple #3
0
def resolve_peer(client: Client, pid: Union[int, str]) -> Union[bool, InputPeerChannel, InputPeerUser, None]:
    # Get an input peer by id
    result = None

    try:
        result = client.resolve_peer(pid)
    except FloodWait as e:
        raise e
    except (PeerIdInvalid, UsernameInvalid, UsernameNotOccupied):
        return False
    except Exception as e:
        logger.warning(f"Resolve peer {pid} error: {e}", exc_info=True)

    return result
def resolve_peer(
        client: Client,
        pid: Union[int,
                   str]) -> Optional[Union[InputPeerChannel, InputPeerUser]]:
    # Get an input peer by id
    result = None
    try:
        flood_wait = True
        while flood_wait:
            flood_wait = False
            try:
                result = client.resolve_peer(pid)
            except FloodWait as e:
                flood_wait = True
                wait_flood(e)
    except Exception as e:
        logger.warning(f"Resolve peer {pid} error: {e}", exc_info=True)

    return result
Exemple #5
0
def get_user(app: Client, member: ChatMember, get_bio=False):
    joined_date = None
    if member.joined_date:
        joined_date = datetime \
            .fromtimestamp(member.joined_date) \
            .astimezone() \
            .isoformat()
    bio = None
    if get_bio:
        fully: UserFull = app.send(
            GetFullUser(id=app.resolve_peer(member.user.id)))
        bio = fully.about
    return {
        "User ID": str(member.user.id),
        "Joined Date": joined_date,
        "Status": member.status,
        "Photo": None if member.user.photo else "Unset",
        "First name": member.user.first_name,
        "Last name": member.user.last_name,
        "Username": member.user.username,
        "Bio": bio,
    }
Exemple #6
0
from pyrogram.api import functions, types
from pyrogram.api.errors import FloodWait

client = Client("example")
client.start()

target = "username"  # Target channel/supergroup
users = []  # List that will contain all the users of the target chat
limit = 200  # Amount of users to retrieve for each API call
offset = 0  # Offset starts at 0

while True:
    try:
        participants = client.send(
            functions.channels.GetParticipants(
                channel=client.resolve_peer(target),
                filter=types.ChannelParticipantsSearch(
                    ""),  # Filter by empty string (search for all)
                offset=offset,
                limit=limit,
                hash=0))
    except FloodWait as e:
        # Very large channels will trigger FloodWait.
        # When happens, wait X seconds before continuing
        time.sleep(e.x)
        continue

    if not participants.participants:
        break  # No more participants left

    users.extend(participants.users)
from pyrogram import Client, errors
from pyrogram.api import functions, types

app = Client("my_account")

with app:
    for dialog in app.iter_dialogs():
        if dialog.chat.type == "group":
            if dialog.message.migrate_to_chat_id:
                app.send(
                    functions.messages.DeleteHistory(
                        peer=app.resolve_peer(peer_id=dialog.chat.id),
                        max_id=0,
                        just_clear=False,
                        revoke=False,
                    )
                )
Exemple #8
0
def main():
    client = Client('session', api_key=(API_ID, API_HASH))
    client.start()

    def _get_dialog_name(type_, id_, client):
        try:
            ip = client.resolve_peer(id_)
        except Exception as e:
            print(type_, id_, e)

        if type_ == PT_CHANNEL:
            chats = client.send(functions.channels.GetChannels([
                ip,
            ]))
            channel = chats.chats[0]
            name = channel.title
        elif type_ == PT_CHAT:
            chats = client.send(functions.messages.GetChats([id_]))
            chat = chats.chats[0]
            name = chat.title
        elif type_ == PT_USER:
            fu = client.send(functions.users.GetFullUser(ip))
            name = fu.user.first_name
        else:
            TypeError(f'undefined type {type_}')

        return name

    def _extract_dialogs_data(dialogs):
        data = []
        for d in dialogs:
            type_, id_ = get_dialog_type_id(d)
            name = _get_dialog_name(type_, id_, client)
            data.append((type_, id_, name, d.write()))
        return data

    # def _get_offset_date(dslice):
    #     for m in reversed(dslice.messages):
    #         if isinstance(m, types.MessageEmpty):
    #             continue
    #
    #         return m.date
    #
    #     return 0

    # offset_date, limit = 0, 20
    # saved = 0
    # while True:
    # dslice = client.send(functions.messages.GetDialogs(0, 0, types.InputPeerEmpty(), 100))
    # if not dslice.dialogs:
    #     break
    # dialogs = _extract_dialogs_data(dslice.dialogs)
    # Dialog.insert_many(dialogs, fields=(Dialog.type, Dialog.dialog_id, Dialog.name, Dialog.bin_data))\
    #       .execute()

    # saved += len(dslice.dialogs)
    # offset_date = _get_offset_date(dslice)
    # logger.info(f'saved {saved} messages')

    show_dialogs()
    id_ = input('id: ')
    offset, limit = 0, 100
    saved = 0
    try:
        peer = client.resolve_peer(int(id_))
    except PeerIdInvalid:
        peer = types.InputPeerChat(int(id_))

    while True:
        hist = client.send(
            functions.messages.GetHistory(
                peer,
                0,
                0,
                offset,
                limit,
                0,
                0,
                0,
            ))
        if not hist.messages:
            break
        save_history(hist.messages, id_)
        saved += len(hist.messages)
        offset += limit
    logger.info(f'saved {saved} messages')
    client.stop()
Exemple #9
0
from pyrogram import Client
from pyrogram.api import functions

import psycopg2

client = Client("example")
client.start()

full_channel = client.send(
    functions.channels.GetFullChannel(
        channel=client.resolve_peer("IoTexGroup")))

num_mems = full_channel.full_chat.participants_count

print(full_channel.full_chat.participants_count)
client.stop()
conn = psycopg2.connect(
    host="ec2-54-197-250-121.compute-1.amazonaws.com",
    database="dfgsrc4s6pvsg1",
    user="******",
    password="******"
)

print("Opened database successfully")

cur = conn.cursor()

# commented out code was used to make the initial db entry
# cur.execute('''CREATE TABLE TELEGRAM_NUM_MEMS
#       (NUM_MEMS INT PRIMARY KEY     NOT NULL);''')
# print("Table created successfully")
Exemple #10
0
from pyrogram import Client
from pyrogram.api import functions
from pyrogram.api.errors import FloodWait

client = Client("example")
client.start()

target = "me"  # "me" refers to your own chat (Saved Messages)
history = []  # List that will contain all the messages of the target chat
limit = 100  # Amount of messages to retrieve for each API call
offset = 0  # Offset starts at 0

while True:
    try:
        messages = client.send(
            functions.messages.GetHistory(client.resolve_peer(target), 0, 0,
                                          offset, limit, 0, 0, 0))
    except FloodWait as e:
        # For very large chats the method call can raise a FloodWait
        time.sleep(e.x)  # Sleep X seconds before continuing
        continue

    if not messages.messages:
        break  # No more messages left

    history.extend(messages.messages)
    offset += limit

client.stop()

# Now the "history" list contains all the messages sorted by date in
class TelegramBot():
    def __init__(self):

        self.client = Client("Listener")

        self.client.add_handler(RawUpdateHandler(self.processUpdate))

    def run(self):

        self.config = configparser.ConfigParser()
        try:
            self.config.read("config.ini")
        except:
            self.logError("Error while loading the config file, exiting", True)

        self.setupDBConnection()

        print("\nStarting Telegram API connection\n")
        self.client.start()
        print("API connection started")

        self.listening = False
        self.chats = self.getChats()
        self.monitoredChats = self.loadMonitoredChatsTable()

        self.menu()

        self.client.idle()

    def menu(self):

        help = '''
- COMMANDS -

all - show a list of joined chats/channels/groups in the account
listening - show a list of joined chats/channels/groups we are listening to for updates
add - add hats/channels/groups to the listening list, pass comma-separated list of usernames or ids
remove - remove chats/channels/groups from the listening list, pass comma-separated list of usernames or ids

start - start listening for updates
'''
        print(help)

        while (True):

            userInput = input("\nPlease enter command: ")
            try:
                inputSplit = userInput.split(" ", 1)
                command = inputSplit[0].strip()

                if (command == "start"):
                    print("\nStarted listening for updates\n")
                    self.listening = True
                    return

                elif (command == "all"):
                    print("\nTITLE - USERNAME - ID")
                    for chatID in self.chats:
                        chat = self.chats[chatID]
                        print(chat[0] + " - " + chat[1] + " - " + str(chatID))

                elif (command == "listening"):
                    if len(self.monitoredChats) > 0:
                        print("TITLE - USERNAME - ID")
                        for chatID in self.monitoredChats:
                            chat = self.monitoredChats[chatID]
                            print(chat[0] + " - " + chat[1] + " - " +
                                  str(chatID))
                    else:
                        print(
                            "We're not listening to any chats/channels/groups yet"
                        )

                elif (command == "add"):
                    if len(inputSplit) == 1:
                        print("No arguments provided")
                        continue
                    items = inputSplit[1].split(",")
                    items = [i.strip() for i in items if i.strip() != ""]
                    self.addChats(items)

                elif (command == "remove"):
                    if len(inputSplit) == 1:
                        print("No arguments provided")
                        continue
                    items = inputSplit[1].split(",")
                    items = [i.strip() for i in items if i.strip() != ""]
                    self.removeChats(items)

                else:
                    print("Sorry, the command was not recognized")

            except:
                self.logError("Sorry, we've encountered an error")
                continue

    def setupDBConnection(self):

        host = self.config["database"]["host"]
        user = self.config["database"]["user"]
        password = self.config["database"]["password"]
        db = self.config["database"]["db"]
        charset = self.config["database"]["charset"]
        dbsettings = {
            "host": host,
            "user": user,
            "password": password,
            "db": db,
            "charset": charset
        }
        try:
            self.pool = pymysql_pool.ConnectionPool(size=1,
                                                    name='pool',
                                                    **dbsettings)
        except:
            self.logError(
                "Error while attempting to connect to database, exiting\n",
                True)
        print("Database connection established")

        self.checkTables()

    def checkTables(self):

        self.chatTable = self.config["database"]["chat_table"]
        self.messageTable = self.config["database"]["message_table"]

        tables = {}
        tables["chat"] = {
            "name":
            self.chatTable,
            "statement":
            "(ID int unsigned not null, Title varchar(255), Username varchar(255), PRIMARY KEY (ID))"
        }
        tables["message"] = {
            "name":
            self.messageTable,
            "statement":
            "(ID int unsigned not null auto_increment, Time datetime, Type varchar(255), Chat int unsigned not null, Sender varchar(255), Message text, PRIMARY KEY(ID), FOREIGN KEY (Chat) REFERENCES "
            + self.chatTable + "(ID))"
        }

        connection = self.pool.get_connection()
        c = connection.cursor()

        for tableType in tables:

            table = tables[tableType]

            try:
                c.execute("SHOW TABLES LIKE '" + table["name"] + "'")
                result = c.fetchone()
            except:
                self.logError(
                    "Error while looking for " + tableType + " table (" +
                    table["name"] + ") in database\n", True)

            if result:
                print("Found " + tableType + " table (" + table["name"] + ")")
            else:
                print("Creating " + tableType + " table (" + table["name"] +
                      ")")
                try:
                    c.execute("CREATE TABLE " + table["name"] + " " +
                              table["statement"])
                    connection.commit()
                except:
                    self.logError(
                        "Error while creating " + tableType + " table (" +
                        table["name"] + ")\n", True)

        connection.close()

    def loadMonitoredChatsTable(self):
        try:
            connection = self.pool.get_connection()
            c = connection.cursor()
            c.execute("SELECT * FROM " + self.chatTable)
            chats = list(c)
            self.monitoredChats = {
                chat[0]: [chat[1], chat[2]]
                for chat in chats
            }
            connection.close()
        except:
            self.logError(
                "Error while getting list of monitored chats/channels/groups from database"
            )

        self.cleanUpMonitored()

        return self.monitoredChats

    def cleanUpMonitored(self):
        delete = []
        for monitored in self.monitoredChats:
            if monitored not in self.chats:
                delete.append(monitored)
        if len(delete) > 0:
            try:
                connection = self.pool.get_connection()
                c = connection.cursor()
                for id in delete:
                    c.execute("DELETE FROM " + self.chatTable + " WHERE ID=" +
                              str(id))
                    del self.monitoredChats[id]
                connection.commit()
                connection.close()
            except:
                self.logError(
                    "Error while clearing a monitored chat we no longer are a member of"
                )

    def getChats(self):
        chats = self.client.send(functions.messages.GetAllChats([]))
        self.chats = chats.chats
        self.supergroupIDs = [
            chat.id for chat in self.chats
            if isinstance(chat, types.Channel) and chat.megagroup == True
        ]
        self.chats = {
            chat.id: [
                str(chat.title),
                ("@" if hasattr(chat, "username") and chat.username else "") +
                (str(chat.username) if hasattr(chat, "username") else "None")
            ]
            for chat in self.chats
        }
        return self.chats

    def addChats(self, items):
        new = []
        for item in items:
            print("Adding to monitored: " + item)
            if (item[0] == "@"):
                item = next(
                    (key
                     for key, value in self.chats.items() if value[1] == item),
                    None)
            elif not item.isdigit():
                print("Invalid format for: " + item)
                continue
            item = int(item)
            if not item or not item in self.chats:
                print("You haven't joined this channel yet")
                continue
            if item in self.monitoredChats:
                print("You've already added this to listening list")
                continue
            new.append(item)
        if len(new) > 0:
            self.updateMonitoredChatsList(new, "add")

    def removeChats(self, items):
        removed = []
        for item in items:
            print("Removing from monitored: " + item)
            if (item[0] == "@"):
                item = next(
                    (key
                     for key, value in self.chats.items() if value[1] == item),
                    None)
                if not item:
                    print(
                        "You haven't even joined this channel , check for typing errors"
                    )
                    continue
            elif item.isdigit():
                if not int(item) in self.chats:
                    print(
                        "You haven't even joined this channel, check for typing errors"
                    )
                    continue
                item = int(item)
            else:
                print("Invalid format for: " + item)
                continue
            if not item in self.monitoredChats:
                print("Already not monitored")
                continue
            removed.append(item)
        if len(removed) > 0:
            self.updateMonitoredChatsList(removed, "remove")

    def updateMonitoredChatsList(self, modified, action):
        try:
            connection = self.pool.get_connection()
            c = connection.cursor()
            for id in modified:
                chat = self.chats[id]
                if action == "add":
                    c.execute(
                        "INSERT INTO " + self.chatTable +
                        "(ID, Title, Username) VALUES (%s, %s, %s)",
                        (id, chat[0], chat[1]))
                elif action == "remove":
                    sql = "DELETE FROM " + self.chatTable + " WHERE ID=" + str(
                        id)
                    c.execute(sql)
            connection.commit()
            connection.close()
            for id in modified:
                if action == "remove":
                    del self.monitoredChats[id]
                elif action == "add":
                    self.monitoredChats[id] = self.chats[id]
        except:
            self.logError("Error while updating monitored list in database")

    def getAdmins(self):

        self.admins = {}

        for group in self.supergroupIDs:

            print("Getting admins for: " + str(group))

            groupAdmins = []
            limit = 200
            offset = 0
            filter = types.ChannelParticipantsAdmins()

            while True:
                try:
                    participants = self.client.send(
                        functions.channels.GetParticipants(
                            channel=self.client.resolve_peer(group),
                            filter=filter,
                            offset=offset,
                            limit=limit,
                            hash=0))
                except FloodWait as e:
                    time.sleep(e.x)
                    continue

                if isinstance(participants,
                              types.channels.ChannelParticipantsNotModified):
                    print("No admin changes")
                    pass

                if not participants.participants:
                    break

                groupAdmins.extend(participants.participants)
                offset += limit

            self.admins[group] = [admin.user_id for admin in groupAdmins]

        for group in self.admins:
            print(" - " + str(group) + " - ")
            for admin in self.admins[group]:
                print(admin)
            print()

        return self.admins

    def updateAdmins(self):
        while True:
            time.sleep(20)
            print("Admin list refresh")
            self.admins = self.getAdmins()

    def checkIfAdmin(self, channelID, senderID):
        admins = self.admins[channelID]
        if senderID in admins:
            return True
        else:
            return False

    def checkIfChannelAdmin(self, channelID, senderID):
        participant = self.client.send(
            functions.channels.GetParticipant(
                channel=self.client.resolve_peer(channelID),
                user_id=self.client.resolve_peer(senderID)))
        sender = participant.participant
        if isinstance(sender, types.ChannelParticipantCreator) or isinstance(
                sender, types.ChannelParticipantAdmin):
            return True
        else:
            return False

    def checkIfGroupAdmin(self, groupID, senderID):
        chat = self.client.send(functions.messages.GetFullChat(groupID))
        participants = chat.full_chat.participants.participants
        for participant in participants:
            if participant.user_id == senderID:
                if isinstance(participant,
                              types.ChatParticipantCreator) or isinstance(
                                  participant, types.ChatParticipantAdmin):
                    return True
                else:
                    return False

    def processUpdate(self, client, update, users, chats):

        if self.listening:

            if isinstance(update, types.UpdateNewChannelMessage):

                if isinstance(update.message, types.MessageService):
                    return

                chat = chats[update.message.to_id.channel_id]
                chatInfo = self.extractChatInfo(chat)
                if int(chatInfo["id"]) not in self.monitoredChats:
                    return
                sender = update.message.from_id
                if sender:
                    sender = users[sender]
                    senderInfo = self.extractSenderInfo(sender)
                else:
                    senderInfo = None
                if chat.megagroup == True:
                    if self.checkIfChannelAdmin(chatInfo["id"],
                                                senderInfo["id"]):
                        timestamp = update.message.date
                        message = update.message.message
                        print("Supergroup admin message - " +
                              chatInfo["string"] +
                              (" - Sender: " +
                               senderInfo["string"] if sender else "") + ": " +
                              message)
                        self.recordToDatabase(timestamp, "admin", chatInfo,
                                              senderInfo, message)
                        self.sendNotification("admin", chatInfo, senderInfo,
                                              message)
                    else:
                        print("Supergroup message not from admin - " +
                              chatInfo["string"] +
                              (" - Sender: " +
                               senderInfo["string"] if sender else "") + ": " +
                              update.message.message)
                else:
                    timestamp = update.message.date
                    message = update.message.message
                    print("Channel message - " + chatInfo["string"] +
                          (" - Sender: " +
                           senderInfo["string"] if sender else "") + ": " +
                          message)
                    self.recordToDatabase(timestamp, "channel", chatInfo,
                                          senderInfo, message)
                    self.sendNotification("channel", chatInfo, "", message)

            elif isinstance(update, types.UpdateChannelPinnedMessage):

                if update.id != 0:
                    chat = chats[update.channel_id]
                    chatInfo = self.extractChatInfo(chat)
                    if int(chatInfo["id"]) not in self.monitoredChats:
                        return
                    messageInfo = client.get_messages(update.channel_id,
                                                      update.id)
                    sender = messageInfo.from_user
                    if sender:
                        senderInfo = self.extractSenderInfo(sender)
                    else:
                        senderInfo = None
                    timestamp = messageInfo.date
                    message = messageInfo.text
                    print("New pinned message - " + chatInfo["string"] +
                          (" - Sender: " +
                           senderInfo["string"] if sender else "") + ": " +
                          message)
                    self.recordToDatabase(timestamp, "pinned", chatInfo,
                                          senderInfo, message)
                    self.sendNotification("pinned", chatInfo,
                                          senderInfo if sender else "",
                                          message)

            elif isinstance(update, types.UpdateNewMessage):
                if isinstance(update.message, types.MessageService):
                    return
                chat = chats[update.message.to_id.chat_id]
                chatInfo = self.extractChatInfo(chat)
                if int(chatInfo["id"]) not in self.monitoredChats:
                    return
                sender = users[update.message.from_id]
                senderInfo = self.extractSenderInfo(sender)
                timestamp = update.message.date
                message = update.message.message
                if self.checkIfGroupAdmin(chatInfo["id"], senderInfo["id"]):
                    print("Group admin message - " + chatInfo["string"] +
                          (" - Sender: " +
                           senderInfo["string"] if sender else "") + ": " +
                          message)
                    self.recordToDatabase(timestamp, "admin", chatInfo,
                                          senderInfo, message)
                    self.sendNotification("admin", chatInfo, senderInfo,
                                          message)
                else:
                    print("Group message not from admin - " +
                          chatInfo["string"] +
                          (" - Sender: " +
                           senderInfo["string"] if sender else "") + ": " +
                          message)

        elif isinstance(update, types.UpdateChannel):
            #print("Channel list changed")
            self.chats = self.getChats()
            self.cleanUpMonitored()

    def extractChatInfo(self, chat):
        chatInfo = {}
        chatInfo["title"] = chat.title
        chatInfo["id"] = chat.id
        if hasattr(chat, "username"):
            chatInfo["username"] = ("@" if chat.username else "") + str(
                chat.username)
        else:
            chatInfo["username"] = "******"
        chatInfo[
            "string"] = chatInfo["title"] + "(" + chatInfo["username"] + ")"
        return chatInfo

    def extractSenderInfo(self, sender):
        senderInfo = {}
        senderInfo["id"] = sender.id
        senderInfo["name"] = sender.first_name + (" " + str(sender.last_name)
                                                  if sender.last_name else "")
        if hasattr(sender, "username"):
            senderInfo["username"] = ("@" if sender.username else "") + str(
                sender.username)
        else:
            senderInfo["username"] = "******"
        senderInfo[
            "string"] = senderInfo["name"] + "(" + senderInfo["username"] + ")"
        return senderInfo

    def recordToDatabase(self, timestamp, type, chat, sender, message):
        time = datetime.fromtimestamp(timestamp).strftime("%Y-%m-%d %H:%M:%S")
        chat = chat["id"]
        if sender:
            sender = sender["string"]
        else:
            sender = ""
        try:
            connection = self.pool.get_connection()
            c = connection.cursor()
            c.execute(
                "INSERT INTO " + self.messageTable +
                "(Time, Type, Chat, Sender, Message) VALUES (%s, %s, %s, %s, %s)",
                (time, type, chat, sender, message))
            connection.commit()
            connection.close()
        except:
            self.logError("Error while writing update to the database")

    def sendNotification(self, type, chat, sender, message):
        URL = self.config["IFTTT"]["URL"]
        if URL != "":
            text = "New " + type + " message in " + chat["string"] + (
                " from " +
                sender["string"] if sender else "") + "\n\n" + message
            #print(text)
            data = {"value1": text}
            try:
                response = requests.post(URL, data=data)
                print(response.text)
            except:
                self.logError("Error while sending notification to phone")

    def logError(self, message, fatal=False):

        print(message)
        error = str(sys.exc_info()[0]) + "\n\n" + str(sys.exc_info()[1])
        print(error)
        with open("errors.log", 'a') as logfile:
            logfile.write("\n" + datetime.now().strftime("%Y-%m-%d %H:%M:%S") +
                          " - " + error + "\n\n" +
                          str(traceback.format_exc()) + "\n")
            logfile.write(
                "---------------------------------------------------------------"
            )
        if (fatal):
            #sprint ("\n" + str(traceback.format_exc()))
            raise SystemExit
from collections import namedtuple

USER = namedtuple('User', ['username', 'name', 'about'])
app = Client("account")
target = input('username чата без "@": ')  # Target channel/supergroup
users = []  # List that will contain all the users of the target chat
limit = 200  # Amount of users to retrieve for each API call
offset = 0  # Offset starts at 0

app.start()

while True:
    try:
        participants = app.send(
            functions.channels.GetParticipants(
                channel=app.resolve_peer(target),
                filter=types.ChannelParticipantsSearch(
                    ""),  # Filter by empty string (search for all)
                offset=offset,
                limit=limit,
                hash=0))
    except FloodWait as e:
        # Very large channels will trigger FloodWait.
        # When happens, wait X seconds before continuing
        time.sleep(e.x)
        continue

    if not participants.participants:
        break  # No more participants left

    for i in participants.users:
Exemple #13
0
from pyrogram import Client
from pyrogram.api import functions, types
from pyrogram.api.errors import (
    BadRequest, Flood, InternalServerError,
    SeeOther, Unauthorized, UnknownError
)
app = Client(
    "my_account",
    api_id=428227,
    api_hash='18c9cd90e3b44de1f7f323d8af49ec6b'
)
app.start()
try:
    app.send(
        functions.channels.InviteToChannel(
            channel=app.resolve_peer('Try group'),  # ID or Username
            users=[
                app.resolve_peer('@GindemoAnton')
                # app.resolve_peer('@BobbyReggieB'),
                # app.resolve_peer('@IevgeniiaKobets'),
            ]
        )
    )
    print('end')
except BadRequest as err:
    print(err)
except Flood as err:
    print(err)
except InternalServerError as err:
    print(err)
except SeeOther as err:
Exemple #14
0
from pyrogram import Client
from pyrogram.api import functions
from pyrogram.api.errors import FloodWait

app = Client("my_account")
app.start()

target = "me"  # "me" refers to your own chat (Saved Messages)
history = []  # List that will contain all the messages of the target chat
limit = 100  # Amount of messages to retrieve for each API call
offset = 0  # Offset starts at 0

while True:
    try:
        messages = app.send(
            functions.messages.GetHistory(app.resolve_peer(target), 0, 0,
                                          offset, limit, 0, 0, 0))
    except FloodWait as e:
        # For very large chats the method call can raise a FloodWait
        time.sleep(e.x)  # Sleep X seconds before continuing
        continue

    if not messages.messages:
        break  # No more messages left

    history.extend(messages.messages)
    offset += limit

app.stop()

# Now the "history" list contains all the messages sorted by date in
Exemple #15
0
# Get the full "Recent Actions" Admin log from the specified chat.
# In case you deleted a message and can't ".eval" the UserID of a spammer anymore.

from pyrogram import Client
from pyrogram.raw import functions

chat = "pyrogramlounge"
app = Client("my_account")

with app:
    full_log = app.send(
        functions.channels.GetAdminLog(
            channel=app.resolve_peer(chat),
            q="",
            max_id=0,
            min_id=0,
            limit=0,
        )
    )
with open(f"recent_actions_{chat}.txt", "w", encoding="utf8") as log_file:
    log_file.write(str(full_log))
Exemple #16
0
"""

app = Client(session_name="my_account", api_id=API_ID, api_hash="API_HASH")

app.start()

target = "CHANNEL"  # Target channel/supergroup
users = []  # List that will contain all the users of the target chat
limit = 200  # Amount of users to retrieve for each API call
offset = 0  # Offset starts at 0

while True:
    try:
        participants = app.send(
            functions.channels.GetParticipants(
                channel=app.resolve_peer(target),
                filter=types.ChannelParticipantsSearch(
                    ""),  # Filter by empty string (search for all)
                offset=offset,
                limit=limit,
                hash=0))
    except FloodWait as e:
        # Very large channels will trigger FloodWait.
        # When happens, wait X seconds before continuing
        time.sleep(e.x)
        continue

    if not participants.participants:
        break  # No more participants left

    users.extend(participants.users)
Exemple #17
0
    def handle_incoming(self, client: Client, msg: Message):
        client.send(
            api.functions.channels.ReadHistory(
                client.resolve_peer(msg.chat.id), msg.message_id))
        if msg.text == '/auth' and msg.reply_to_message:
            return self.func_auth_process(client, msg)
        if not auth_system.check_ex(msg.from_user.id): return
        if msg.text and re.match(
                r'^\/(bot (on|off)|del|getn?|fw|ban( (([1-9]\d*)(s|m|h|d)|f))?|kick( confirm| -?\d+)?|status|b?o(n|ff)|join|p(romote( \d+)?)?|set [a-zA-Z])$',
                msg.text):
            return self.process_imcoming_command(client, msg)
        if msg.text and msg.text.startswith('/') and re.match(
                r'^\/\w+(@\w*)?$', msg.text):
            return
        if auth_system.check_muted(msg.from_user.id) or (
                msg.text and msg.text.startswith('//')) or (
                    msg.caption and msg.caption.startswith('//')):
            return

        if msg.forward_from or msg.forward_from_chat:
            if msg.forward_from:
                if msg.forward_from.is_self: return
                elif auth_system.check_ex(msg.forward_from.id):
                    return self.cross_group_forward_request(msg)
            self.conn.insert_ex(
                self.botapp.forward_messages(self.target_group,
                                             self.fudu_group,
                                             msg.message_id).message_id,
                msg.message_id)
        elif msg.text and (not msg.edit_date or
                           (msg.edit_date and
                            self.conn.get_id(msg.message_id, True) is None)):
            self.conn.insert_ex(
                self.botapp.send_message(
                    self.target_group,
                    build_html_parse(msg).split_offset(),
                    'html',
                    True,
                    reply_to_message_id=self.conn.get_reply_id_Reverse(msg),
                ).message_id, msg.message_id)
        elif msg.photo:
            self.media_sender.Locker.acquire()
            msg.download('tmp.jpg')
            self.media_sender.put((self.botapp.send_photo, msg,
                                   media_path('downloads/tmp.jpg'), True),
                                  True)
        elif msg.video:
            self.media_sender.put(
                (self.botapp.send_video, msg, msg.video, True), True)
        elif msg.document:
            self.media_sender.put(
                (self.botapp.send_document, msg, msg.document, True), True)
        elif msg.edit_date:
            try:
                (self.botapp.edit_message_text
                 if msg.text else self.botapp.edit_message_caption)(
                     self.target_group,
                     self.conn.get_id(msg.message_id, True),
                     build_html_parse(msg).split_offset(),
                     parse_mode='html',
                     disable_web_page_preview=True)
            except:
                traceback.print_exc()
        elif msg.sticker:
            self.media_sender.put(
                (self.botapp.send_sticker, msg, msg.sticker, True), True)