Exemplo n.º 1
0
def BasicHandlerMaster(client: pyrogram.Client, msg: pyrogram.Message):
    global last_user
    if msg.reply_to_message:
        if msg.reply_to_message.forward_from:
            last_user = msg.reply_to_message.forward_from
        elif msg.reply_to_message.text.find("(#user") != -1:
            last_user = client.get_chat(
                chat_id=int(msg.reply_to_message.
                            text[msg.reply_to_message.text.find("(#user") +
                                 6:msg.reply_to_message.text.find(")")]))
    if last_user:
        try:
            msg.forward(chat_id=last_user.id, disable_notification=False)
            client.send_chat_action(chat_id=utils.config["master"],
                                    action="typing")
        except pyrogram.errors.UserIsBlocked:
            msg.reply_text(text=f"{last_user.id} blocked me.\n",
                           disable_notification=False)
        except pyrogram.errors.PeerIdInvalid:
            msg.reply_text(
                text=f"Cannot write to {last_user.id}, never encountered.\n",
                disable_notification=False,
            )
        except Exception as ex:
            msg.reply_text(text=str(ex), disable_notification=False)
    else:
        msg.reply_text(
            text=
            "Need to have last_user OR to reply to a forwarded message OR to reply to a message with the #user hashtag!",
            disable_notification=False,
        )
Exemplo n.º 2
0
def getList(c, m):
    global name
    try:
        acc_name = m.command[2]
        gp_link = m.command[1]
    except KeyError:
        m.reply_text("یادت نره اول لینک گپ بعدش اسم اکانت رو وارد کنی.")
        return

    accunt = Client(accs[acc_name][2], accs[acc_name][0], accs[acc_name][1])
    accunt.start()
    try:
        gpe = accunt.join_chat("{}".format(gp_link))
        gpe = accunt.get_chat("{}".format(gp_link))
        gp_id = gpe.id
    except errors.UserAlreadyParticipant:
        gpe = accunt.get_chat("{}".format(gp_link))
    except errors.InviteHashExpired:
        m.reply_text('بن بودم نشد')
    except errors.Flood:
        m.reply_text('فلاد خوردم')
        return
    accunt.send_sticker(m.chat.id, "CAADBAADGggAArhpKVBYg-r8Rxp36hYE")
    members = accunt.iter_chat_members(gpe.id, limit=1000)
    number = 0
    LiNum = 1
    MesG = f"List{LiNum} - {gpe.title}"
    for member in members:
        user_name = member.user.username
        user_bot = member.user.is_bot
        user_status = member.user.status
        if user_name != None and user_bot is False and user_status != (
                "long_time_ago" or "within_month" or "within_week"
                or None) and member.user.is_self is False:
            number += 1
            MesG += f"{number} - @{user_name}\n"
            if number == 45:
                LiNum += 1
                accunt.send_message(m.chat.id, MesG)
                MesG = f"List{LiNum} - {gpe.title}\n"
                number = 0
    accunt.send_message(m.chat.id, MesG)
Exemplo n.º 3
0
def get_chat(client: Client, cid: Union[int, str]) -> Union[Chat, ChatPreview, None]:
    # Get a chat
    result = None

    try:
        result = client.get_chat(chat_id=cid)
    except FloodWait as e:
        raise e
    except (ChannelInvalid, ChannelPrivate, PeerIdInvalid):
        return None
    except Exception as e:
        logger.warning(f"Get chat {cid} error: {e}", exc_info=True)

    return result
def send_telegram(Ldest, itemType, get_graph, key):
    # Telegram settings | Configuracao do Telegram #########################################################################
    api_id0 = PropertiesReaderX(
        path.format('configScripts.properties')).getValue(
            'PathSectionTelegram', 'api.id')
    api_hash0 = PropertiesReaderX(
        path.format('configScripts.properties')).getValue(
            'PathSectionTelegram', 'api.hash')

    try:
        api_id = int(decrypt(key, api_id0))
    except:
        api_id = api_id0

    try:
        api_hash = str(decrypt(key, api_hash0))
    except:
        api_hash = api_hash0

    app = Client("SendGraph", api_id=api_id, api_hash=api_hash)

    msg = body.replace("\\n", "")
    saudacao = salutation
    Saudacao = PropertiesReaderX(
        path.format('configScripts.properties')).getValue(
            'PathSectionTelegram', 'salutation.telegram')

    if re.search("(sim|s|yes|y)", str(Saudacao).lower()):
        if saudacao:
            saudacao = salutation + " {0} \n\n"
    else:
        saudacao = ""

    with app:
        for dest in Ldest:
            dest = dest.lower()
            if re.search("user#|chat#|\'|\"", dest):
                if "#" in dest:
                    dest = dest.split("#")[1]

                elif dest.startswith("\"") or dest.startswith("\'"):
                    dest = dest.replace("\"", "").replace("\'", "")

            elif dest.startswith("@"):
                dest = dest[1:]

            flag = True
            while flag:
                try:
                    Contatos = app.get_contacts()
                    for contato in Contatos:
                        Id = f"{contato.id}"
                        nome = f"{contato.first_name}"
                        if contato.last_name:
                            nome += f" {contato.last_name}"

                        username = contato.username.lower()
                        if username:
                            if username in dest or dest in Id or dest in nome.lower(
                            ):
                                dest = nome
                                flag = False
                                break
                        else:
                            if dest in Id or dest in nome.lower():
                                dest = nome
                                flag = False
                                break
                except:
                    pass

                try:
                    if flag:
                        Dialogos = app.iter_dialogs()
                        for dialogo in Dialogos:
                            Id = f"{dialogo.chat.id}"
                            if dialogo.chat.title:
                                nome = f"{dialogo.chat.title}"
                            else:
                                nome = f"{dialogo.chat.first_name}"
                                if dialogo.chat.last_name:
                                    nome += f" {dialogo.chat.last_name}"

                            username = dialogo.chat.username
                            if username:
                                if username in dest or dest in Id or dest in nome.lower(
                                ):
                                    dest = nome
                                    flag = False
                                    break
                            else:
                                if dest in Id or dest in nome.lower():
                                    dest = nome
                                    flag = False
                                    break
                except:
                    flag = False
                    try:
                        if re.match("^([0-9-]+)$", dest):
                            dest = int(dest)
                        chat = app.get_chat(dest)
                        Id = "{}".format(chat.id)

                        if chat.title:
                            dest = f"{chat.title}"
                        else:
                            dest = f"{chat.first_name}"
                            if chat.last_name:
                                dest += f" {chat.last_name}"

                    except Exception as msg:
                        # print(msg.args[0])
                        log.writelog(f'{msg.args[0]}', arqLog, "ERROR")
                        exit()

            Id = int(Id)
            sendMsg = """{}{}\n{}""".format(saudacao.format(dest), sys.argv[2],
                                            msg)
            if re.search("(0|3)", itemType):
                try:
                    graph = '{0}/{1}.png'.format(graph_path, itemid)
                    with open(graph, 'wb') as png:
                        png.write(get_graph.content)
                except BaseException as e:
                    log.writelog(
                        '{1} >> An error occurred at save graph file in {0} | Ocorreu um erro ao salvar o grafico no diretório {0}'
                        .format(graph_path, str(e)), arqLog, "WARNING")
                    logout_api()
                    exit()

                try:
                    app.send_photo(Id,
                                   graph,
                                   caption=sendMsg,
                                   parse_mode="html")
                    # print('Telegram sent photo message successfully | Telegram com gráfico enviado com sucesso ({0})'.format(dest))
                    log.writelog(
                        'Telegram sent photo message successfully | Telegram com gráfico enviado com sucesso ({0})'
                        .format(dest), arqLog, "INFO")
                except Exception as e:
                    # print('Telegram FAIL at sending photo message | FALHA ao enviar mensagem com gráfico pelo telegram\n%s' % e)
                    log.writelog(
                        '{0} >> Telegram FAIL at sending photo message | FALHA ao enviar mensagem com gráfico pelo telegram ({1})'
                        .format(e, dest), arqLog, "ERROR")
                    logout_api()
                    exit()

                try:
                    os.remove(graph)
                except Exception as e:
                    # print(e)
                    log.writelog('{0}'.format(str(e)), arqLog, "ERROR")

            else:
                try:
                    app.send_message(Id, sendMsg, parse_mode="html")
                    # print('Telegram sent successfully | Telegram enviado com sucesso ({0})'.format(dest))
                    log.writelog(
                        'Telegram sent successfully | Telegram enviado com sucesso ({0})'
                        .format(dest), arqLog, "INFO")
                except Exception as e:
                    # print('Telegram FAIL at sending photo message | FALHA ao enviar a mensagem com gráfico pelo telegram\n%s' % e)
                    log.writelog(
                        '{0} >> Telegram FAIL at sending message | FALHA ao enviar a mensagem pelo telegram ({1})'
                        .format(e, dest), arqLog, "ERROR")
                    logout_api()
                    exit()

            if re.search("(sim|s|yes|y)", str(Ack).lower()):
                if nograph not in argvs:
                    ack(dest, "Telegram enviado com sucesso ({0})")
Exemplo n.º 5
0
print(" ")
print(" - Starting delete routine")

for target in config.targets:

    print(" ")
    print(" - Deleting messages older than " + str(target.delete_before_days) +
          " days")
    delete_before = int(time.time() -
                        (target.delete_before_days * 24 * 60 * 60))

    for chat in target.chatlist:

        # Get target's chat ID and title
        try:
            chatobj = app.get_chat(chat)
        except (PeerIdInvalid, UsernameInvalid, ValueError):
            print(" ")
            print(" ! Given value leads to invalid chat " + str(chat))
            continue
        except (InviteHashExpired):
            print(" ")
            print(" ! Given chat invite has expired " + str(chat))
            continue

        print(" ")
        print(" - Deleting from chat " + str(chat))
        print("   -- Chat ID: " + str(chatobj.id))
        print("   -- Chat name: " + chatobj.title)

        # Check that we have delete perms
Exemplo n.º 6
0
    dict(login="******"),
    dict(link="AAAAAErpUE2JD_l8FpW8Hg"),
    dict(link="AAAAAEOzOEPpWs_SjppyzQ")
]

with open("_speed_stats.txt", "w") as file:
    file.write("")

with app:
    a = time()
    for channel_code in CHANNELS:
        channel_code = channel_code["login"] if channel_code.get(
            "login") else channel_code["link"]
        try:
            finded_chat = app.join_chat(channel_code)
            chat = app.get_chat(finded_chat.id)
            with open("{}.txt".format(chat.title), "w") as file:
                file.write("{title} @{username}\n".format(
                    title=chat.title if chat.title else "NoTitle",
                    username=chat.username if chat.username else "NoLogin"))
            chat_messages = app.iter_history(chat_id=chat.id)
            messages_count = 0
            for message in chat_messages:
                messages_count += 1
                # if messages_count > 500:
                #     break
                sleep(random() / 77.7)
                with open("{}.txt".format(chat.title), "a") as file:
                    if message.text:
                        file.write("<message views='{}'>\t{}\n".format(
                            message.views,
Exemplo n.º 7
0
app = Client(
    session_name=session_name,
    phone_number=phone_number,
    password=password,
    force_sms=force_sms,
)

with app:
    dialogs = app.get_dialogs()
    chats = []

    for dialog in dialogs:
        if dialog.chat.type not in ("channel", "group", "supergroup"):
            continue
        chats.append((dialog.chat.title, dialog.chat.id))
    if len(chats) == 0:
        print("No chats")
        exit(0)
    questions = [
        inquirer.List(
            "chat",
            message="Select a chat to get info about",
            choices=chats,
        ),
    ]
    answers = inquirer.prompt(questions)
    chat_id = answers["chat"]

    chat = app.get_chat(chat_id)
    print(chat)
Exemplo n.º 8
0
#app.join_chat('t.me/joinchat/Hl0rgBG-KSsumYlURb9uWQ')
#app.get_messages
#app.leave_chat('t.me/joinchat/Hl0rgBG-KSsumYlURb9uWQ',False)
#
x = str(app.send(functions.messages.CheckChatInvite('Hl0rgBG-KSsumYlURb9uWQ')))
#print(x)
s = str.split(x, 'id": ')
print(s[1])
#app.send(1351754478,x)
b = 0

while b < 3:

    #_____sendmessage_______
    smsuser = input("username/1351754478: ")
    if smsuser == 'me':
        smguser = '******'
    if smsuser[:1] == '@':
        smguser = smsuser[1:]
    else:
        smguser = int(smsuser)
    print(app.get_history(smguser, 0, 1))
    print(app.get_chat(smguser))
    print(smguser)
    smgtext = input("message: ")
    print(smgtext)
    app.send_message(smguser, smgtext)
    b = int(input("b не больше 3="))
#__________________________

#app.leave_chat(1351754478,False)
Exemplo n.º 9
0
def main(file_name, handlers: List[Tuple[Handler]]):
    """
    .format for archive :
    ID: [ID]
    HASH: [HASH]
        ***OPTIONALLY**
    NAME: [NAME] (DEFAULT WOULD BE "Account API")
    PHONE: [PHONE_NUMBER] (YOUR PHONE NUMBER (PREFIX INCLUDED) TO AVOID ENTERING IT MANUALLY)
    It can contain any other order, but be sure to follow that .format
    """

    id_hash = open(file_name, "r")
    id, hash, phone_number, session_name = -1, "", "", "Account API"

    for line in (id_hash):
        if (line.count("ID: ") == 1):
            line = line.split('ID: ')[-1].replace('\n', '')
            try:
                id = int(line)
            except:
                pass

        elif (line.count("HASH: ") == 1):
            line = line.split('HASH: ')[-1].replace('\n', '')
            try:
                hash = str(line)
            except:
                pass

        elif (line.count("NAME: ") == 1):
            line = line.split('NAME: ')[-1].replace('\n', '')
            try:
                session_name = str(line)
            except:
                pass

        elif (line.count("PHONE: ") == 1):
            line = line.split('PHONE: ')[-1].replace('\n', '')
            try:
                phone_number = str(line)
            except:
                pass

        else:
            continue

    if (id == -1 or hash == ""):
        print("Missing credentials")

    else:
        global __app
        if (phone_number != ""):
            __app = Client(session_name=session_name,
                           api_id=id,
                           api_hash=hash,
                           phone_number=phone_number)
        else:
            __app = Client(session_name=session_name, api_id=id, api_hash=hash)

    for handler, group in (handlers):
        add_handler(handler, group)

    with __app as __app:
        user = __app.get_me()
        p_name = ""
        p_name += ("verified " if user.is_verified else "un-verified ")
        p_name += ("bot " if user.is_bot else "user ")
        opt = "Y"
        while (opt.lower() == "y"):
            try:
                clear()

                print("Welcome {name}! @{user.username}".format(
                    name=p_name + user.first_name + ' ' + user.last_name,
                    **locals()))
                print("0 Send message")
                print("1 Send sticker")
                print("2 Join Chat")
                print("3 Print iter dialiogs")
                choice = input("Choice? ")

                if (choice == "0"):
                    """Send message"""
                    message = input("Enter message: ")
                    try:
                        chat_id = input(
                            "Chat id (Unique_identifier/username/phone number): "
                        )
                        chat_id = int(chat_id)
                    except:
                        pass
                    if (send_message(chat_id=chat_id, message=message)):
                        print("Successfully sent message '{}'".format(message))
                    else:
                        raise TypeError

                elif (choice == "1"):
                    """Send sticker"""
                    try:
                        chat_id = input(
                            "Chat id (Unique_identifier/username/phone number): "
                        )
                        chat_id = int(chat_id)
                    except:
                        pass
                    # I'll figure a way for BinaryIO, might be casting
                    stickers = [
                        "CAACAgEAAxkBAAECJONgafOJ_Thz6r8CHd51MwtFwuDnZgACPQoAAr-MkATw-kKsJZetrh4E",
                        "CAACAgEAAxkBAAECJONgafOJ_Thz6r8CHd51MwtFwuDnZgACPQoAAr-MkATw-kKsJZetrh4E",
                        "CAACAgIAAxkBAAECJOdgaf0vuvbOr13UmDY6l9JriQwF5gACDwEAAiteUwtmHUnnGkg7RB4E",
                        "CAACAgIAAxkBAAECJOVgaf0c5eaesQKUwU5B1FT0Vm5hVwACEwEAAiteUwuoZCFUWCiWHh4E",
                        "CAACAgIAAxkBAAECJO1gaf2d1gG1eNpH8MVychBhQV6OdgACewADwZxgDNsaH7YdVDaIHgQ"
                    ]
                    sticker = random_choice(stickers)
                    if (send_sticker(chat_id=chat_id, sticker=sticker)):
                        print("Successfully sent sticker '{}'".format(sticker))
                    else:
                        raise TypeError

                elif (choice == "2"):
                    """Join chat"""
                    try:
                        chat_id = input(
                            "Chat id (Unique_identifier/username/link/): ")
                        linked_chat = bool(input("Linked chat? (1/0) "))
                        if (linked_chat):
                            linked_chat = __app.get_chat(
                                chat_id).linked_chat_id
                    except:
                        pass
                    if (join_chat(chat_id=chat_id)):
                        print("Successfully joined chat '{}'".format(chat_id))
                    else:
                        raise TypeError

                elif (choice == "3"):
                    """Print dialogs"""
                    try:
                        print_iter_dialogs()
                    except:
                        raise TypeError

            except:
                print("-___(^*^)___-")

            opt = input("Again? (Y/N)")
Exemplo n.º 10
0
from pyrogram import Client, Message, Filters, InputMediaPhoto
from pyrogram.errors import FloodWait

from channels import get_data

from config import api_id, api_hash

app = Client(session_name='rep', api_id=api_id, api_hash=api_hash)
last_media_group_ids = []

app.start()
while True:
    try:
        print('Started')
        from_ids = [app.get_chat(i['from']).id for i in get_data()]
        from_to_ids = []
        for data in get_data():
            from_id = app.get_chat(data['from']).id
            to_id = app.get_chat(data['to']).id
            from_to_ids.append({'from_id': from_id, 'to_id': to_id})
            print(
                f'Check   from: {data["from"]} [{from_id}]    to: {data["to"]} [{to_id}]'
            )
        print('Check is done.\n\nBot has been STARTED')
        break
    except FloodWait as e:
        print("Sleeping for {}s".format(e.x))
        time.sleep(e.x)
app.stop()
Exemplo n.º 11
0
    TELEMNML = 'https://t.me/joinchat/AAAAAFHj_Wd9Y6WVRXD4EA'
    GENRE_LIST = [MINIMAL, ELECTRO, BANDCAMP]
    MINIMAL_FILE = '../data/minimal.json'
    ELECTRO_FILE = '../data/electro.json'
    BANDCAMP_FILE = '../data/bandcamp.json'
    TELEMNML_FILE = '../data/telemnml.json'
    FILE_LIST = [MINIMAL_FILE, ELECTRO_FILE, BANDCAMP_FILE]
    EP_REGEX = '(\(([0-9]{4},)*.*(Vinyl|CD|File)\))*( \| Edições.*\|*)*( \| Discogs)*( - YYDistribution)*(\([0-9]\))*((\.wav|\.mp3|\.flac|\.zip|\.m3u8).*)*'
    FILE_REGEX = '([0-9]{2}\.)*(\[[A-Z]+[0-9]{2,3}\])*(\.wav|\.mp3|\.flac|\.aiff|\.zip)*((\(|\[)(Master|Vinyl|Web|Digital).*(\]|\)))*'


    for genre, filee in zip(GENRE_LIST, FILE_LIST):
        ep = ''
        counter_ep = 0
        counter_song = 0
        chat = app.get_chat(genre)
        with open(filee) as f:
            data = json.load(f)

        for message in app.iter_history(chat.id, reverse=True):
            if message.caption:
                text = message.caption
            else:
                text = message.text
            try:
                if text:
                    # I link di WeTransfer sono messi due linee sotto il resto
                    split_link = re.split('\n\n', text)
                    text = split_link[0]
                    if len(split_link) > 1:
                        wetransfer_link = split_link[1]
Exemplo n.º 12
0
delete_before_time = 3 * 24
# int() is to delete decimals
delete_before = int(time.time() - (delete_before_time * 60 * 60))

#print(delete_before)

for target in targets:

    app = Client("my_account")
    messages = []  # List that will contain all the messages of the target chat
    offset_id = 0  # ID of the last message of the chunk

    app.start()

    chat_id = app.get_chat(target).id

    while True:
        try:
            m = app.get_history(chat_id, offset_id=offset_id)
        except FloodWait as e:
            # For very large chats the method call can raise a FloodWait
            print("waiting {}".format(e.x))
            time.sleep(e.x)  # Sleep X seconds before continuing
            continue

        if not m.messages:
            break

        messages += m.messages
        offset_id = m.messages[-1].message_id