예제 #1
0
from telethon.sync import TelegramClient
from telethon.tl.functions.messages import GetDialogsRequest
from telethon.tl.types import InputPeerEmpty
import csv

api_id = 856985
api_hash = 'd5e0bf9653a8eae24241fe89bc682605'
phone = '+85255360441'
client = TelegramClient(phone, api_id, api_hash)

client.connect()
if not client.is_user_authorized():
    client.send_code_request(phone)
    client.sign_in(
        phone,
        input(
            'Enter the code - ask gareth for code if you are still using my number above: '
        ))

chats = []
last_date = None
chunk_size = 200
groups = []

result = client(
    GetDialogsRequest(offset_date=last_date,
                      offset_id=0,
                      offset_peer=InputPeerEmpty(),
                      limit=chunk_size,
                      hash=0))
chats.extend(result.chats)
예제 #2
0
    def send_sms():
        try:
            cpass = configparser.RawConfigParser()
            cpass.read('config.data')
            api_id = cpass['cred']['id']
            api_hash = cpass['cred']['hash']
            phone = cpass['cred']['phone']
        except KeyError:
            os.system('clear')
            main.banner()
            print(re + "[!] run python3 setup.py first !!\n")
            sys.exit(1)

        client = TelegramClient(phone, api_id, api_hash)

        client.connect()
        if not client.is_user_authorized():
            client.send_code_request(phone)
            os.system('clear')
            main.banner()
            client.sign_in(phone, input(gr + '[+] Enter the code: ' + re))

        os.system('clear')
        main.banner()
        input_file = sys.argv[1]
        users = []
        with open(input_file, encoding='UTF-8') as f:
            rows = csv.reader(f, delimiter=",", lineterminator="\n")
            next(rows, None)
            for row in rows:
                user = {}
                user['username'] = row[0]
                user['id'] = int(row[1])
                user['access_hash'] = int(row[2])
                user['name'] = row[3]
                users.append(user)
        print(gr + "[1] send sms by user ID\n[2] send sms by username ")
        mode = int(input(gr + "Input : " + re))

        message = input(gr + "[+] Enter Your Message : " + re)

        for user in users:
            if mode == 2:
                if user['username'] == "":
                    continue
                receiver = client.get_input_entity(user['username'])
            elif mode == 1:
                receiver = InputPeerUser(user['id'], user['access_hash'])
            else:
                print(re + "[!] Invalid Mode. Exiting.")
                client.disconnect()
                sys.exit()
            try:
                print(gr + "[+] Sending Message to:", user['name'])
                client.send_message(receiver, message.format(user['name']))
                print(gr + "[+] Waiting {} seconds".format(SLEEP_TIME))
                time.sleep(SLEEP_TIME)
            except PeerFloodError:
                print(
                    re +
                    "[!] Getting Flood Error from telegram. \n[!] Script is stopping now. \n[!] Please try again after some time."
                )
                client.disconnect()
                sys.exit()
            except Exception as e:
                print(re + "[!] Error:", e)
                print(re + "[!] Trying to continue...")
                continue
        client.disconnect()
        print("Done. Message sent to all users.")
예제 #3
0
from telethon.tl.functions.channels import InviteToChannelRequest
import sys
import csv
import traceback
import time
import random

api_id = 557896
api_hash = ''
phone = '+919962892900'
client = TelegramClient(phone, api_id, api_hash)

client.connect()
if not client.is_user_authorized():
	client.send_code_request(phone)
	client.sign_in(phone, input('Enter the code: '))

input_file = sys.argv[1]
users = []
with open(input_file, encoding='UTF-8') as f:
	rows = csv.reader(f,delimiter=",",lineterminator="\n")
	next(rows, None)
	for row in rows:
		user = {}
		user['username'] = row[0]
		user['id'] = int(row[1])
		user['access_hash'] = int(row[2])
		user['name'] = row[3]
		users.append(user)

chats = []
예제 #4
0
        await client.send_message('me', 'Hello !!!!!')

except KeyError:
    os.system('clear')
    banner()
    print(re + "[!] run python3 Scraper.py first !!\n")
    sys.exit(1)

SLEEP_TIME_1 = 100
SLEEP_TIME_2 = 100
with client:
    client.loop.run_until_complete(main())
client.connect()
if not client.is_user_authorized():
    client.send_code_request(phone)
    client.sign_in(phone, input('Enter Code'))

users = []
with open(r"members.csv", encoding='UTF-8') as f:  #Enter your file name
    rows = csv.reader(f, delimiter=",", lineterminator="\n")
    next(rows, None)
    for row in rows:
        user = {}
        user['username'] = row[0]
        user['id'] = int(row[1])
        user['access_hash'] = int(row[2])
        user['name'] = row[3]
        users.append(user)

chats = []
last_date = None
예제 #5
0
client = TelegramClient(phone, api_id, api_hash)


async def main():
    # Now you can use all client methods listed below, like for example...
    await client.send_message('me', 'Hello !!!!!')


SLEEP_TIME_1 = 100
SLEEP_TIME_2 = 100
with client:
    client.loop.run_until_complete(main())
client.connect()
if not client.is_user_authorized():
    client.send_code_request(phone)
    client.sign_in(phone, input('40779'))

users = []
with open(r"Scrapped.csv", encoding='UTF-8') as f:  #Enter your file name
    rows = csv.reader(f, delimiter=",", lineterminator="\n")
    next(rows, None)
    for row in rows:
        user = {}
        user['username'] = row[0]
        user['id'] = int(row[1])
        user['access_hash'] = int(row[2])
        user['name'] = row[3]
        users.append(user)

chats = []
last_date = None
예제 #6
0
def AddMemberInGroup():
    Name_banner()
    cpass = configparser.RawConfigParser()
    cpass.read('configAddData.data')

    try:
        api_id = cpass['cred']['id']
        api_hash = cpass['cred']['hash']
        phone = cpass['cred']['phone']
        client = TelegramClient(phone, api_id, api_hash)

        async def main():
            # Now you can use all client methods listed below, like for example...
            await client.send_message('me', 'Hello !!!!!')

    except KeyError:
        os.system('clear')
        Name_banner()
        print(
            re +
            "[!] Goto Menu and first setup your Account for adding dara  !!\n")
        sys.exit(1)

    SLEEP_TIME_1 = 100
    SLEEP_TIME_2 = 100
    with client:
        client.loop.run_until_complete(main())
    client.connect()
    if not client.is_user_authorized():
        client.send_code_request(phone)
        client.sign_in(phone, input('40779'))

    users = []
    with open(r"members.csv", encoding='UTF-8') as f:  #Enter your file name
        rows = csv.reader(f, delimiter=",", lineterminator="\n")
        next(rows, None)
        for row in rows:
            user = {}
            user['username'] = row[0]
            user['id'] = int(row[1])
            user['access_hash'] = int(row[2])
            user['name'] = row[3]
            users.append(user)

    chats = []
    last_date = None
    chunk_size = 1000
    groups = []

    result = client(
        GetDialogsRequest(offset_date=last_date,
                          offset_id=0,
                          offset_peer=InputPeerEmpty(),
                          limit=chunk_size,
                          hash=0))
    chats.extend(result.chats)

    for chat in chats:
        try:
            if chat.megagroup == True:
                groups.append(chat)
        except:
            continue

    print('Choose a group to add members:')
    i = 0
    for group in groups:
        print(str(i) + '- ' + group.title)
        i += 1

    g_index = input("Enter a Number: ")
    target_group = groups[int(g_index)]

    target_group_entity = InputPeerChannel(target_group.id,
                                           target_group.access_hash)
    mode = int(input("Enter 1 to add by username or 2 to add by ID: "))
    n = 0
    for user in users:
        n += 1
        if n % 80 == 0:
            time.sleep(60)
        try:
            print("Adding {}".format(user['id']))
            if mode == 1:
                if user['username'] == "":
                    continue
                user_to_add = client.get_input_entity(user['username'])
            elif mode == 2:
                user_to_add = InputPeerUser(user['id'], user['access_hash'])
            else:
                sys.exit("Invalid Mode Selected. Please Try Again.")
            client(InviteToChannelRequest(target_group_entity, [user_to_add]))
            print("Waiting for 60-180 Seconds...")
            time.sleep(random.randrange(0, 5))
        except PeerFloodError:
            print(
                "Some Technical Issu Found.Please Wait Second ..... Solving..."
            )
            print("Waiting {} seconds".format(SLEEP_TIME_2))
            time.sleep(SLEEP_TIME_2)
        except UserPrivacyRestrictedError:
            print(
                "The user's privacy settings do not allow you to do this. Skipping."
            )
            print("Waiting for 5 Seconds...")
            time.sleep(random.randrange(0, 5))
        except:
            traceback.print_exc()
            print("Unexpected Error")
            continue

    menu()
예제 #7
0
def kaydet():
    nya = c.RawConfigParser()  #Grup keylerini oku
    nya.read('degerler.veri')
    cfg = nya['veri']['config_no']
    satno = nya['veri']['satir_no']
    kissay = nya['veri']['kisi_sayisi']
    group_username = nya['veri']['kanal_grup_adi']
    ags = nya['veri']['aktif_gun_sayisi']
    bsk = nya['veri']['beklenicek_sure_kucuk']
    bsb = nya['veri']['beklenicek_sure_buyuk']
    intsatno = int(satno)
    intkissay = int(kissay)
    intags = int(ags)
    intbsk = int(bsk)
    intbsb = int(bsb)
    cpass = c.RawConfigParser()
    cpass.read(cfg)
    try:
        api_id = cpass['cred']['id']
        api_hash = cpass['cred']['hash']
        phone = cpass['cred']['phone']
        client = TelegramClient(phone, api_id, api_hash)
    except KeyError:
        os.system('cls')
        print("[!] Gereklilikler yuklu degil. !!\n")
        sys.exit(1)
    client.connect()
    if not client.is_user_authorized():
        client.send_code_request(phone)
        client.sign_in(phone, input('[+] Telegramdan gelen kodu gir : '))
    client(JoinChannelRequest(channel=group_username))
    chats = []
    last_date = None
    chunk_size = 200
    groups = []
    result = client(
        GetDialogsRequest(offset_date=last_date,
                          offset_id=0,
                          offset_peer=InputPeerEmpty(),
                          limit=chunk_size,
                          hash=0))
    chats.extend(result.chats)
    for chat in chats:
        try:
            check = client.get_entity(group_username)
            if check.id == chat.id:
                groups.append(chat)
        except:
            continue
    i = 0
    for group in groups:
        print('[' + str(i) + ']' '-' + group.title)
        i += 1
    g_index = 0
    aktif_gun_sayisi = intags
    target_group = groups[int(g_index)]
    all_participants = []
    all_participants = client.get_participants(target_group, aggressive=True)
    with open("grup_uyeleri.csv", "w", encoding='UTF-8') as f:
        writer = csv.writer(f, delimiter=",", lineterminator="\n")
        writer.writerow([
            'username', 'user id', 'access hash', 'name', 'group', 'group id'
        ])
        for user in all_participants:
            accept = True
            try:
                lastDate = user.status.was_online
                ay_kontrolu = (datetime.now().month - lastDate.month)
                gun_kontrolu = (datetime.now().day - lastDate.day)
                if (ay_kontrolu > 0 or gun_kontrolu > aktif_gun_sayisi
                        or datetime.now().year != lastDate.year):
                    accept = False
            except:
                continue
            if (accept):
                if user.username:
                    username = user.username
                else:
                    username = ""
                if user.first_name:
                    first_name = user.first_name
                else:
                    first_name = ""
                if user.last_name:
                    last_name = user.last_name
                else:
                    last_name = ""
                name = (first_name + ' ' + last_name).strip()
                writer.writerow([
                    username, user.id, user.access_hash, name,
                    target_group.title, target_group.id
                ])
    client(LeaveChannelRequest(channel=group_username))
    os._exit(1)
예제 #8
0
    pg.scroll(-7000)
    time.sleep(2)
    ClickIfVisible('logout.PNG')
    time.sleep(2)
    ClickIfVisible('disconnect.PNG')


if __name__ == '__main__':
    sim_cards = CreateSimList()
    for sim in sim_cards:
        client = TelegramClient('sessions\\' + sim.phone, sim.ID,
                                sim.access_hash)
        client.connect()
        if not client.is_user_authorized():
            client.send_code_request(sim.phone)
            CopyMessageToClipboard()
            time.sleep(1)
            PasteMessageInFile()
            code = GetCodeFromFile()
            client.sign_in(phone=sim.phone, code=code)
            print(Fore.GREEN +
                  f"Created {sim.name} session file! Logging out..")
            LogOut()
            client.disconnect()
            DeleteMessageFromFile()
        else:
            print(Fore.RED + f"{sim.name} already exist! skipping")
            client.disconnect()

    print(f"\nSuccesfully created {len(sim_cards)} SESSION files! exiting..")
예제 #9
0
class TELEGRAM_CLIENT:
    def __init__(self, id: int, hash: str, session_name: str, phone_number: str, proxy = None):
        self.api_id = id
        self.api_hash = hash
        self.session_name = session_name
        self.phone_number = phone_number

        self.client = TelegramClient(self.session_name,
                                     self.api_id,
                                     self.api_hash,
                                     proxy = proxy)

        self.client.connect()

        if not self.client.is_user_authorized():
            try:
                self.client.send_code_request(self.phone_number)
                print('Code sent to ' + self.phone_number)
                self.code_sent = 1
            except:
                self.code_sent = 0

    def close_connection(self):
        try:
            self.client.disconnect()
            return {'response': 1}
        except:
            return {'response': False}

    def is_auth(self):
        if not self.client.is_user_authorized():
            return {'response': False}
        else:
            return {'response': 1}

    def enter_code(self, code, reg_data: list = ['Ivan', 'Ivanov']):
        try:
            self.me = self.client.sign_up(code=code,
                                          first_name=reg_data[0],
                                          last_name=reg_data[1])
            if not self.client.is_user_authorized():
                return {'response': False}
            else:
                return {'response': 1}
        except telethon.errors.rpcerrorlist.PhoneNumberOccupiedError:
            self.me = self.client.sign_in(self.phone_number, code)
            if not self.client.is_user_authorized():
                return {'response': False}
            else:
                return {'response': 1}

    def edit_2FA(self, new_password: str, current_password = None):
        try:
            if not current_password:
                self.client.edit_2fa(new_password=new_password)
            else:
                self.client.edit_2fa(current_password=current_password,
                                     new_password=new_password)
            return {'response': 1}
        except:
            return {'response': False}

    def clear_2FA(self, current_password: str):
        try:
            self.client.edit_2fa(current_password=current_password,
                                 new_password=None)
            return {'response': 1}
        except:
            return {'response': False}

    def get_me(self):
        try:
            client_me = self.client.get_me().stringify()
            return {'response': 1,
                    'client_me': client_me}
        except:
            return {'response': False, 'ban': 1}

    def change_username(self, username: str):
        try:
            result = self.client(functions.account.UpdateUsernameRequest(
                    username=username
                    ))
            return {'response': 1,
                    'result': result.stringify()}
        except:
            return {'response': False}
예제 #10
0
from telethon.sync import TelegramClient
from telethon.tl.functions.messages import GetDialogsRequest
from telethon.tl.types import InputPeerEmpty
import csv

# área de conexão com o API do Telegram
api_id = input('Entre com o API_id: ')
api_hash = input('Entre com o API_hash: ')
phone = input('Entre com o telefone no formato +551191234567: ')
client = TelegramClient(phone, api_id, api_hash)

# checagem de segurança - onde será dado entrada do código enviado por mensagem para o seu Telegram
client.connect()
if not client.is_user_authorized():
    client.send_code_request(phone)
    client.sign_in(phone, input('Entre com o código enviado para você: '))

chats = []
last_date = None
chunk_size = 200
groups = []

result = client(GetDialogsRequest(
    offset_date=last_date,
    offset_id=0,
    offset_peer=InputPeerEmpty(),
    limit=chunk_size,
    hash=0
))

chats.extend(result.chats)
예제 #11
0
class UI:
    def __init__(self):
        self.client = TelegramClient('token', api_id, api_hash)
        try:
            self.client.connect()
        except OSError:
            tk.messagebox.showerror('錯誤', '無法連線伺服器\n請檢查你的網路')

        if self.client.is_user_authorized():
            self.logged_in_windows = tk.Tk()
            self.logged_in_windows.title("快速刪除Telegram訊息({}已登入)".format(
                self.client.get_me().first_name))
            self.logged_in_windows.geometry('432x243')
            self.logged_in_windows.resizable(width=0, height=0)
            self.logged_in_windows.wm_attributes('-topmost', 1)
            self.chat_room = tk.Entry(self.logged_in_windows)
            self.chat_room.pack()
            tk.Label(
                self.logged_in_windows,
                text=
                '\n使用說明\n\n在上方輸入頻道、群組的share link或者私訊對方的username\n格式可以是 https://t.me/TGQNA @TGQNA 或者 TGQNA\n\n在下方選譯是僅刪除自己傳送的訊息還是刪除所有的訊息\n注意:刪除所有訊息時請確保你有對應的權限\n'
            ).pack()
            self.del_button = tk.Button(self.logged_in_windows,
                                        text='刪除自己的訊息',
                                        command=self.del_msg)
            self.del_button.pack()
            self.del_all_button = tk.Button(self.logged_in_windows,
                                            text='刪除全部的訊息',
                                            command=self.delall_msg)
            self.del_all_button.pack()
            self.logged_in_windows.mainloop()
        else:
            self.log_in_windows = tk.Tk()
            self.log_in_windows.title("快速刪除Telegram訊息(未登入)")
            self.log_in_windows.geometry('432x243')
            self.log_in_windows.resizable(width=0, height=0)
            self.log_in_windows.wm_attributes('-topmost', 1)
            tk.Label(master=self.log_in_windows,
                     text='國碼+電話號碼').place(x=20, y=50, height=26, width=100)
            tk.Label(master=self.log_in_windows, text='驗證碼').place(x=66,
                                                                   y=100,
                                                                   height=26,
                                                                   width=60)
            tk.Label(master=self.log_in_windows, text='密碼').place(x=72,
                                                                  y=150,
                                                                  height=26,
                                                                  width=60)
            self.phone_number = tk.Entry(master=self.log_in_windows)
            self.phone_number.place(x=144, y=50, height=26, width=220)
            self.code = tk.Entry(master=self.log_in_windows)
            self.code.place(x=144, y=100, height=26, width=100)
            self.password = tk.Entry(master=self.log_in_windows, show='*')
            self.password.place(x=144, y=150, height=26, width=220)
            self.get_code_button = tk.Button(master=self.log_in_windows,
                                             text='驗證碼',
                                             width=50,
                                             height=30,
                                             command=self.get_code)
            self.get_code_button.place(x=304, y=100, height=26, width=60)
            self.help_button = tk.Button(master=self.log_in_windows,
                                         text='說明',
                                         width=40,
                                         height=30,
                                         command=self.help)
            self.help_button.place(x=94, y=200, height=26, width=60)
            self.login_button = tk.Button(master=self.log_in_windows,
                                          text='登入',
                                          width=40,
                                          height=30,
                                          command=self.login)
            self.login_button.place(x=194, y=200, height=26, width=60)
            self.exit_button = tk.Button(master=self.log_in_windows,
                                         text='退出',
                                         width=40,
                                         height=30,
                                         command=self.exit)
            self.exit_button.place(x=294, y=200, height=26, width=60)
            self.log_in_windows.mainloop()

    def exit(self):
        self.log_in_windows.quit()

    def get_code(self):
        if len(self.phone_number.get()) <= 8:
            tk.messagebox.showerror(
                '錯誤', '請先輸入正確的電話號碼\n格式:國際電話區號+電話號碼\n例如:+85223802850')
            return
        try:
            self.sent = self.client.send_code_request(self.phone_number.get())
            self.hash = self.sent.phone_code_hash
        except:
            tk.messagebox.showerror('未知錯誤', '無法取得驗證碼,請兩分鐘後再試!')

    def help(self):
        tk.messagebox.showinfo(
            '使用說明',
            '電話號碼格式國際電話區號+電話號碼\n例如:+85223802850\n\n驗證碼是5位數字的\n密碼是雙步驟驗證(2FA)密碼,沒有就留空'
        )

    def del_msg(self):
        self.me = self.client.get_me()
        for self.message in self.client.iter_messages(self.chat_room.get()):
            if self.message.from_id == self.me.id:
                self.client.delete_messages(self.chat_room.get(),
                                            self.message.id)
                print(self.message.id)
        tk.messagebox.showinfo('成功',
                               '成功刪除 {} 裡自己傳送的訊息'.format(self.chat_room.get()))

    def delall_msg(self):
        for self.message in self.client.iter_messages(self.chat_room.get()):
            self.client.delete_messages(self.chat_room.get(), self.message.id)
            print(self.message.id)
        tk.messagebox.showinfo('成功',
                               '成功刪除 {} 裡所有的訊息'.format(self.chat_room.get()))

    def login(self):
        if len(self.code.get()) != 5:
            tk.messagebox.showerror('錯誤', '請先輸入正確的驗證碼')
            return
        try:
            self.client.sign_in(phone=self.phone_number.get(),
                                code=self.code.get(),
                                password=self.password.get(),
                                phone_code_hash=self.hash)
        except:
            tk.messagebox.showerror('未知錯誤', '無法登入!')
            return
        tk.messagebox.showinfo('登入成功', '請重新啟動這個應用程式!')
        self.log_in_windows.quit()
예제 #12
0
                       detect_types=sqlite3.PARSE_DECLTYPES
                       | sqlite3.PARSE_COLNAMES)
api_id = 736274
api_hash = '80096319e53934b880fafc95b70d2d99'

phone = "+65 9151 3501"
username = "******"

client = TelegramClient(username, api_id, api_hash)
client.connect()

# Ensure you're authorized
if not client.is_user_authorized():
    client.send_code_request(phone)
    try:
        client.sign_in(phone, input('Enter the code: '))
    except SessionPasswordNeededError:
        client.sign_in(password=input('Password: '))


def get_messages():
    """
    Gets the last 30 messages from the kiasufoodies channel
    :return: iterator for the messages
    """
    kiasufoodies = client.get_entity("kiasufoodies")
    return client.iter_messages(kiasufoodies, limit=30)


def get_postal_codes(url):
    """
예제 #13
0
    api_id = cpass['cred']['id']
    api_hash = cpass['cred']['hash']
    phone = cpass['cred']['phone']
    client = TelegramClient(phone, api_id, api_hash)
except KeyError:
    os.system('clear')
    banner()
    print("\033[91m[!] run \033[92mpython3 setup.py \033[91mfirst !!\n")
    sys.exit(1)

client.connect()
if not client.is_user_authorized():
    client.send_code_request(phone)
    os.system('clear')
    banner()
    client.sign_in(phone, input(gr + '[+] Enter the verification code: ' + yo))

os.system('clear')
banner()
chats = []
last_date = None
chunk_size = 200
groups = []

result = client(
    GetDialogsRequest(offset_date=last_date,
                      offset_id=0,
                      offset_peer=InputPeerEmpty(),
                      limit=chunk_size,
                      hash=0))
chats.extend(result.chats)
예제 #14
0
        proxy_port = int(input('Socks5 PORT: '))
        client = TelegramClient('user',
                                api_id,
                                api_hash,
                                proxy=(socks.SOCKS5, proxy_ip, proxy_port))

    client.connect()
    if not client.is_user_authorized():
        try:
            print((Fore.BLUE + 'Введите номер телефона' + Fore.RED +
                   '(+71111111111):'),
                  end='')
            phone_number = input(' ')
            client.send_code_request(phone_number)
            print((Fore.BLUE + 'Введите код:'), end='')
            client.sign_in(phone_number, input(' '))
            print(Fore.RESET)
        except telethon.errors.rpcerrorlist.SessionPasswordNeededError:
            print(
                Fore.RED +
                '\nОтключите двухэтапную аутентификацию. Попробуйте еще раз.\n'
                + Fore.RESET)
            input('Нажмите Enter чтобы продолжить')
        except telethon.errors.rpcerrorlist.FloodWaitError as e:
            try:
                print(Fore.RED + '\nСлишком много попыток. Попробуйте через ' +
                      Fore.CYAN + (f"{e.seconds}") + Fore.RED + ' секунд.' +
                      Fore.RESET)
                input('Нажмите Enter чтобы продолжить')
            finally:
                e = None
예제 #15
0
            if not client.is_user_authorized():
                phone = getInput('Моб. телефон', test=False)
                client.send_code_request(phone)
        except ConnectionError:
            printError('ОШИБКА СОЕДЕНЕНИЯ')
            exit()
        except TypeError or ApiIdInvalidError:
            os.system('clear')
            getBanner()
            printError('Не верные данные')
            retryGetUserData(user_data_file)
            continue

            os.system('clear')
            getBanner()
            client.sign_in(phone, getInput('Код из смс', test=False))

        if mode == 1:
            if os.path.isfile(members_file):
                try:
                    with open(members_file, 'r') as file:
                        #global members
                        members = json.load(file)
                except Exception as e:
                    members = None
                    printError(e)

            else:
                members = None
                printError('Файл с данными пользователей не был создан')
                printError('Перейдите к пункту 2')
import os.path
import credentials
from slugify import slugify

# get time from os
timestamp = time.strftime("%Y%m%d-%H%M%S")

# log in to telegram api
client = TelegramClient(credentials.phone, credentials.api_id,
                        credentials.api_hash)

# telegram session login and otp
client.connect()
if not client.is_user_authorized():
    client.send_code_request(credentials.phone)
    client.sign_in(credentials.phone, input('Enter OTP code: '))

# get current groups
from telethon.tl.functions.messages import GetDialogsRequest
from telethon.tl.types import InputPeerEmpty
chats = []
last_date = None
chunk_size = 200
groups = []

result = client(
    GetDialogsRequest(offset_date=last_date,
                      offset_id=0,
                      offset_peer=InputPeerEmpty(),
                      limit=chunk_size,
                      hash=0))
예제 #17
0
def scraper():
    Name_banner()
    cpass = configparser.RawConfigParser()
    cpass.read('configScrap.data')
    try:
        api_id = cpass['cred']['id']
        api_hash = cpass['cred']['hash']
        phone = cpass['cred']['phone']
        client = TelegramClient(phone, api_id, api_hash)
    except KeyError:
        Name_banner
        print(re + "[!] Go to menu and install application  !!\n")
        sys.exit(1)
    client.connect()
    if not client.is_user_authorized():
        client.send_code_request(phone)

        Name_banner
        client.sign_in(phone, input(gr + '[+] Enter the code: ' + re))

    os.system('clear')
    Name_banner
    chats = []
    last_date = None
    chunk_size = 500
    groups = []

    result = client(
        GetDialogsRequest(offset_date=last_date,
                          offset_id=0,
                          offset_peer=InputPeerEmpty(),
                          limit=chunk_size,
                          hash=0))
    chats.extend(result.chats)

    for chat in chats:
        try:
            if chat.megagroup == True:
                groups.append(chat)
        except:
            continue

    print(gr + '[+] Choose a group to scrape members :' + re)
    i = 0
    for g in groups:
        print(gr + '[' + cy + str(i) + ']' + ' - ' + g.title)
        i += 1

    print('')
    g_index = input(gr + "[+] Enter a Number : " + re)
    target_group = groups[int(g_index)]

    print(gr + '[+] Fetching Members...')
    time.sleep(1)
    all_participants = []
    all_participants = client.get_participants(target_group, aggressive=True)

    print(gr + '[+] Saving In file...')
    time.sleep(1)
    with open("members.csv", "w", encoding='UTF-8') as f:
        writer = csv.writer(f, delimiter=",", lineterminator="\n")
        writer.writerow([
            'username', 'user id', 'access hash', 'name', 'group', 'group id'
        ])
        for user in all_participants:
            if user.username:
                username = user.username
            else:
                username = ""
            if user.first_name:
                first_name = user.first_name
            else:
                first_name = ""
            if user.last_name:
                last_name = user.last_name
            else:
                last_name = ""
            name = (first_name + ' ' + last_name).strip()
            writer.writerow([
                username, user.id, user.access_hash, name, target_group.title,
                target_group.id
            ])
    os.system('clear')
    print(gr + '[+] Members scraped successfully.  ')
    print(gr + '[+] Wait 5 second....  menu is Opening ')
    menu()
예제 #18
0
# Step 
#Go to https://my.telegram.org/auth
#Enter Your Phone Number
#Get OTP (eg :- VqzWWqMQBxxx )
#Give Any Name
#You Wii Get api_id, api_hash 

async def main():
    # Now you can use all client methods listed below, like for example...
    await client.send_message('me', 'Hello !!!!')
with client:
    client.loop.run_until_complete(main())
client.connect()
if not client.is_user_authorized():
    client.send_code_request(phone)
    client.sign_in(phone, input('Enter verification code: '))

chats = []
last_date = None
chunk_size = 200
groups=[]

result = client(GetDialogsRequest(
             offset_date=last_date,
             offset_id=0,
             offset_peer=InputPeerEmpty(),
             limit=chunk_size,
             hash = 0
         ))
chats.extend(result.chats)
예제 #19
0
        try:
            proxy = proxy_utils.create_proxy(proxy_type,proxy_host,proxy_port,proxy_user,proxy_password)
        except NameError:
            print("Error: the proxy of this account is not saved, please add the proxy variables")
        finally:
            proxy_utils.save_session_proxy(px_session, proxy)
    client = TelegramClient(phone, api_id, api_hash, proxy=proxy)
else:
    client = TelegramClient(phone, api_id, api_hash)


client.connect()
if not client.is_user_authorized():
    client.send_code_request(phone)
    code = input("Enter the code: ")
    client.sign_in(phone, code)


groups_list_public = open("groups_public.txt", "r")
groups_list_private = open("group_list_private.txt", "r")

mode = int(input('Enter 1 for Public Groups, 2 for Private Group: '))

if mode == 1:
    for group in groups_list_public:
        try:
            group = group.strip('\n')
            client(JoinChannelRequest(group))
            print(f'Joined group {group.title()}')
            time.sleep(random.randrange(120, 180))
예제 #20
0
def e():
    try:
        r = c.RawConfigParser()  #Read Group Keys
        r.read('degerler.veri')
        cfg = r['veri']['config_no']
        group_username = r['veri']['kanal_grup_adi']
        ags = r['veri']['aktif_gun_sayisi']
        bsk = r['veri']['beklenicek_sure_kucuk']
        bsb = r['veri']['beklenicek_sure_buyuk']
        intags = int(ags)
        intbsk = int(bsk)
        intbsb = int(bsb)
        cpass = c.RawConfigParser()
        cpass.read(cfg)
    except:
        print("Something is wrong with degerler.veri!!")
    try:
        id = cpass['cred']['id']
        h = cpass['cred']['hash']
        p = cpass['cred']['phone']
        client = TelegramClient(p, id, h)
    except KeyError:
        print("[!] Api access id phone or hash is not correct!!\n")
        sys.exit(1)
    client.connect()
    if not client.is_user_authorized():
        client.send_code_request(p)
        client.sign_in(p, input('[+] Enter code sent from telegram : '))
    client(JoinChannelRequest(channel=group_username))
    chats = []
    last_date = None
    chunk_size = 200
    groups = []
    result = client(
        GetDialogsRequest(offset_date=last_date,
                          offset_id=0,
                          offset_peer=InputPeerEmpty(),
                          limit=chunk_size,
                          hash=0))
    chats.extend(result.chats)
    for chat in chats:
        try:
            check = client.get_entity(group_username)
            if check.id == chat.id:
                groups.append(chat)
        except:
            continue
    i = 0
    for group in groups:
        print('[' + str(i) + ']' '-' + group.title)
        i += 1
    g_index = 0
    aktif_gun_sayisi = intags
    target_group = groups[int(g_index)]
    all_participants = []
    time.sleep(random.randrange(11, 23))
    all_participants = client.get_participants(
        target_group
    )  #patched because telegram seems to ban while using it! , aggressive=True)
    with open("users.nya", "w", encoding='UTF-8') as f:
        writer = csv.writer(f, delimiter=",", lineterminator="\n")
        writer.writerow([
            'username', 'user id', 'access hash', 'name', 'group', 'group id'
        ])
        for user in all_participants:
            #contacts = client(GetContactsRequest(0))
            #client(AddChatUserRequest(chat_id=chat.id,user_id=user.id,fwd_limit=10))
            accept = True
            try:
                lastDate = user.status.was_online
                ay_kontrolu = (datetime.now().month - lastDate.month)
                gun_kontrolu = (datetime.now().day - lastDate.day)
                if (ay_kontrolu > 0 or gun_kontrolu > aktif_gun_sayisi
                        or datetime.now().year != lastDate.year):
                    accept = False
            except:
                pass
            if (accept):
                if user.username:
                    username = user.username
                else:
                    username = ""
                if user.first_name:
                    first_name = user.first_name
                else:
                    first_name = ""
                if user.last_name:
                    last_name = user.last_name
                else:
                    last_name = ""
                name = (first_name + ' ' + last_name).strip()
                writer.writerow([
                    username, user.id, user.access_hash, name,
                    target_group.title, target_group.id
                ])
    client(LeaveChannelRequest(channel=group_username))
    os._exit(1)
예제 #21
0
        api_hash = cpass['cred']['hash']
        phone = cpass['cred']['phone']
        client = TelegramClient(phone, api_id, api_hash)
    except KeyError:
        os.system('clear')
        print("{}[{}!{}] {}ERRor".format(blue, red, blue, red))
        sleep(2)
        print("{}[{}!{}] {}Run config.py first".format(blue, red, blue,
                                                       yellow))
        sys.exit(1)
    client.connect()
    if not client.is_user_authorized():
        try:
            client.send_code_request(phone)
            client.sign_in(
                phone,
                input('{}[+] {}Enter the code>> {}'.format(blue, white,
                                                           green)))
        except SessionPasswordNeededError:
            password = input(
                '{}[+] {}Input Your  2factor password>> {}'.format(
                    blue, white, green))
            me = client.start(phone, password)

    os.system('clear')
    chats = []
    last_date = None
    chunk_size = 200
    groups = []

    result = client(
        GetDialogsRequest(offset_date=last_date,
예제 #22
0
def start(config):
    try:
        api_id = config['api_id']
        session_name = config["session_name"]
        api_hash = config["api_hash"]
        phone_number = config['phone_number']
    
        client = TelegramClient(session_name, api_id, api_hash)
    except KeyError:
        print("Unable to get Telegram developer id.\nPlease register for telegram developer.")
        sys.exit(1)    
    client.connect()
    client.start()
    if not client.is_user_authorized():
        client.send_code_request(phone_number)
        client.sign_in(phone_number, input('Enter the code: '))

    chats = []
    last_date = None
    chunk_size = 200
    groups=[]
 
    result = client(GetDialogsRequest(
             offset_date=last_date,
             offset_id=0,
             offset_peer=InputPeerEmpty(),
             limit=chunk_size,
             hash = 0
         ))
    chats.extend(result.chats)
    for chat in chats:
        try:
            if chat.megagroup== True:
                groups.append(chat)
        except:
            continue
    print('Choose a group to scrape members :')
    i=0
    for g in groups:
        print('['+str(i)+']'+' - '+ g.title)
        i+=1
 
    print('')
    g_index = input("Enter a Number : ")
    target_group=groups[int(g_index)]
 
    print('Fetching Members...')
    time.sleep(1)
    all_participants = []
    all_participants = client.get_participants(target_group, aggressive=True)
 
    print('Saving In file...')
    time.sleep(1)
    with open("members.csv","w",encoding='UTF-8') as f:
        writer = csv.writer(f,delimiter=",",lineterminator="\n")
        writer.writerow(['username','user_id', 'access_hash','name','group', 'group_id','status'])
        for user in all_participants:
            if user.username:
                username= user.username
            else:
                username= ""
            if user.first_name:
                first_name= user.first_name
            else:
                first_name= ""
            if user.last_name:
                last_name= user.last_name
            else:
                last_name= ""
            name= (first_name + ' ' + last_name).strip()
            writer.writerow([username,user.id,user.access_hash,name,target_group.title, target_group.id, 'N'])      
    print('Members scraped successfully.')
예제 #23
0
def adder():
    if os.path.isfile(os.path.join(os.getcwd(), 'added.json')) == True:
        pass
    else:
        added = []
        person = {}

        person['username'] = ''
        person['user_id'] = ''
        added.append(person.copy())

        person['username'] = ''
        person['user_id'] = ''
        added.append(person.copy())

        with open(os.path.join(os.getcwd(), 'added.json'), 'w') as file:
            json.dump(added, file, indent=2)

    if os.path.isfile(os.path.join(os.getcwd(), 'tried.json')) == True:
        pass
    else:
        added = []
        person = {}

        person['username'] = ''
        person['user_id'] = ''
        added.append(person.copy())

        person['username'] = ''
        person['user_id'] = ''
        added.append(person.copy())

        with open(os.path.join(os.getcwd(), 'tried.json'), 'w') as file:
            json.dump(added, file, indent=2)

    if os.path.isfile(os.path.join(os.getcwd(), 'config.json')) == True:
        pass
    else:
        config = {}
        config['api_id'] = '0'
        config['api_hash'] = 'your api hash'
        config['phone'] = '+0'
        with open(os.path.join(os.getcwd(), 'config.json'),
                  'w') as config_file:
            json.dump(config, config_file, indent=2)

    session = False
    for item in os.listdir():
        if '.session' in item:
            number = item.split('.')[0]
            session = True

    if session:
        while True:
            a = input(
                f'Do you want to recover your login session with number {number}? [y/n] '
            ).lower()
            if a == 'y':
                print('Program Started...')
                with open(os.path.join(os.getcwd(), 'config.json'),
                          'r') as config_file:
                    config = json.load(config_file)
                    api_id = config['api_id']
                    api_hash = config['api_hash']
                    phone = config['phone']
                break
            elif a == 'n':
                for item in os.listdir():
                    if '.session' in item:
                        os.remove(item)
                print('Program Started...')
                api_id = input('Paste here your account api id: ')
                api_hash = input('Paste here your account api hash: ')
                phone = input(
                    'Paste here your phone number (International Format): ')
                config = {}
                config['api_id'] = api_id
                config['api_hash'] = api_hash
                config['phone'] = phone
                with open(os.path.join(os.getcwd(), 'config.json'),
                          'w') as config_file:
                    json.dump(config, config_file, indent=2)
                break

    else:
        print('No session found. Lets define a new one...')
        api_id = input('Paste here your account api id: ')
        api_hash = input('Paste here your account api hash: ')
        phone = input('Paste here your phone number (International Format): ')
        config = {}
        config['api_id'] = api_id
        config['api_hash'] = api_hash
        config['phone'] = phone
        with open(os.path.join(os.getcwd(), 'config.json'),
                  'w') as config_file:
            json.dump(config, config_file, indent=2)

    # ========================== FIXING BUGS ================================
    with open(os.path.join(os.getcwd(), 'config.json'), 'r') as config_file:
        config = json.load(config_file)

        if api_id == '0':
            api_id = input('Paste here your account api id: ')
            config['api_id'] = api_id
            with open(os.path.join(os.getcwd(), 'config.json'),
                      'w') as config_file:
                json.dump(config, config_file, indent=2)

        if api_hash == 'your api hash':
            api_hash = input('Paste here your account api hash: ')
            config['api_hash'] = api_hash
            with open(os.path.join(os.getcwd(), 'config.json'),
                      'w') as config_file:
                json.dump(config, config_file, indent=2)
        if phone == '+0':
            phone = input(
                'Paste here your phone number (International Format): ')
            config['phone'] = phone
            with open(os.path.join(os.getcwd(), 'config.json'),
                      'w') as config_file:
                json.dump(config, config_file, indent=2)

    # ====================== END OF FIXING BUGS ===============================

    client = TelegramClient(phone, api_id, api_hash)

    async def main():
        # Now you can use all client methods listed below, like for example...
        await client.send_message('me', 'Hello !!!!!')

    SLEEP_TIME_1 = 100
    SLEEP_TIME_2 = 100
    with client:
        client.loop.run_until_complete(main())
    client.connect()
    if not client.is_user_authorized():
        client.send_code_request(phone)
        client.sign_in(phone, input('40779'))

    users = []
    with open(r"Scrapped.csv", encoding='UTF-8') as f:  #Enter your file name
        rows = csv.reader(f, delimiter=",", lineterminator="\n")
        next(rows, None)
        for row in rows:
            user = {}
            user['username'] = row[0]
            user['id'] = int(row[1])
            user['access_hash'] = int(row[2])
            user['name'] = row[3]
            users.append(user)

    chats = []
    last_date = None
    chunk_size = 200
    groups = []

    result = client(
        GetDialogsRequest(offset_date=last_date,
                          offset_id=0,
                          offset_peer=InputPeerEmpty(),
                          limit=chunk_size,
                          hash=0))
    chats.extend(result.chats)

    for chat in chats:
        try:
            if chat.megagroup == True:
                groups.append(chat)
        except:
            continue

    print('Choose a group to add members:')
    i = 0
    for group in groups:
        group.title = group.title.encode('utf-8')
        group.title = group.title.decode('ascii', 'ignore')
        print(f'{str(i)} - {str(group.title)}')
        i += 1

    g_index = input("Enter a Number: ")
    target_group = groups[int(g_index)]

    target_group_entity = InputPeerChannel(target_group.id,
                                           target_group.access_hash)

    mode = int(input("Enter 1 to add by username or 2 to add by ID: "))

    n = 0

    with open(os.path.join(os.getcwd(), 'tried.json'), 'r') as file:
        tried = json.load(file)

    for user in users:
        if user not in tried:
            tried.append(user.copy())
            with open(os.path.join(os.getcwd(), 'tried.json'), 'w') as file:
                json.dump(tried, file, indent=2)
            try:
                n += 1
                if n % 80 == 0:
                    sleep(60)
                try:
                    print("Trying to add user {}".format(user['id']))
                    if mode == 1:
                        if user['username'] == "":
                            continue
                        user_to_add = client.get_input_entity(user['username'])
                    elif mode == 2:
                        user_to_add = InputPeerUser(user['id'],
                                                    user['access_hash'])
                    else:
                        sys.exit("Invalid Mode Selected. Please Try Again.")
                    client(
                        InviteToChannelRequest(target_group_entity,
                                               [user_to_add]))
                    print("Waiting for 60-180 Seconds...")
                    time.sleep(random.randrange(60, 90))
                except PeerFloodError:
                    print(
                        "Getting Flood Error from telegram. Script is stopping now. Please try again after some time."
                    )
                    print("Waiting {} seconds".format(SLEEP_TIME_2))
                    time.sleep(SLEEP_TIME_2)
                except UserPrivacyRestrictedError:
                    print(
                        "The user's privacy settings do not allow you to do this. Skipping."
                    )
                    print("Waiting for 5 Seconds...")
                    time.sleep(random.randrange(5, 0))
                except Exception as e:
                    traceback.print_exc()
                    print("Unexpected Error")
                    continue

                with open(os.path.join(os.getcwd(), 'added.json'),
                          'r') as file:
                    added = json.load(file)
                    added.append(user.copy())

                with open(os.path.join(os.getcwd(), 'added.json'),
                          'w') as file:
                    json.dump(added, file, indent=2)
                    print(
                        f'User {user["name"]} with id: {user["id"]} has been sucessfully added to your group.'
                    )

            except Exception as e:
                print('An unnespected error ocureed.')
                # print(e)

        else:
            print(
                f'This user has been checked by me before. Skipping. If you want o erase data, delete "tried.json".'
            )
예제 #24
0
파일: sms.py 프로젝트: oDeskrin/Scrapper
    def send_sms():
        try:
            cpass = configparser.RawConfigParser()
            cpass.read('config.data')
            api_id = cpass['cre']['id']
            api_hash = cpass['cre']['hash']
            phone = cpass['cre']['phone']
        except KeyError:
            os.system('clear')
            main.banner()
            print(red + "[!] Execute: python3 setup.py antes.\n")
            sys.exit(1)

        client = TelegramClient(phone, api_id, api_hash)

        client.connect()
        if not client.is_user_authorized():
            client.send_code_request(phone)
            os.system('clear')
            main.banner()
            client.sign_in(
                phone, input(green + '[+] Insira o código recebido: ' + red))

        os.system('clear')
        main.banner()
        input_file = sys.argv[1]
        users = []
        with open(input_file, encoding='UTF-8') as f:
            rows = csv.reader(f, delimiter=",", lineterminator="\n")
            next(rows, None)
            for row in rows:
                user = {}
                user['username'] = row[0]
                user['id'] = int(row[1])
                user['access_hash'] = int(row[2])
                user['name'] = row[3]
                users.append(user)
        print(
            green +
            "[1] Enviar SMS por ID de usuário\n[2] Enviar SMS por NOME de usuário"
        )
        mode = int(input(green + "[+] Opção: " + red))

        message = input(green + "[+] Insira uma mensagem: " + red)

        for user in users:
            if mode == 2:
                if user['username'] == "":
                    continue
                receiver = client.get_input_entity(user['username'])
            elif mode == 1:
                receiver = InputPeerUser(user['id'], user['access_hash'])
            else:
                print(red + "[!] Modo inválido, saindo!")
                client.disconnect()
                sys.exit()
            try:
                print(green + "[+] Enviando mensagem para:", user['name'])
                client.send_message(receiver, message.format(user['name']))
                print(green + "[+] O intervalo de envio e de 5 segundos")
                time.sleep(random.randrange(1, 5))
            except PeerFloodError:
                print(
                    red +
                    "[!] Erro de flod do telegram. \n[!] Script parando. \n[!] Tente novamente mais tarde."
                )
                client.disconnect()
                sys.exit()
            except Exception as e:
                print(red + "[!] Erro:", e)
                print(red + "[!] Tentando continuar...")
                continue
        client.disconnect()
        print(green + "[!] Mensagem enviada a todos os usuários.")
예제 #25
0
import random
from telethon.sync import TelegramClient
from telethon.tl.functions.messages import GetDialogsRequest
from telethon.tl.types import InputPeerEmpty
import csv

api_id = XXXXXX
api_hash = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx'
phone = '+XXXXXXXXXXX'

client = TelegramClient(phone, api_id, api_hash)

client.connect()
if not client.is_user_authorized():
    client.send_code_request(phone)
    client.sign_in(phone, input('Entrer le code: '))

chats = []
last_date = None
chunk_size = 200
groups = []

result = client(
    GetDialogsRequest(offset_date=last_date,
                      offset_id=0,
                      offset_peer=InputPeerEmpty(),
                      limit=chunk_size,
                      hash=0))
chats.extend(result.chats)

printGrp = []
예제 #26
0
    api_id = cpass['cred']['id']
    api_hash = cpass['cred']['hash']
    phone = cpass['cred']['phone']
    client = TelegramClient(phone, api_id, api_hash)
except KeyError:
    os.system('clear')
    banner()
    print(re + "[!] Əvvəlcə bu əmri daxil edin :  python3 setup.py !!\n")
    sys.exit(1)

client.connect()
if not client.is_user_authorized():
    client.send_code_request(phone)
    os.system('clear')
    banner()
    client.sign_in(phone, input(gr + '[+] Kodu daxil edin: ' + re))

os.system('clear')
banner()
chats = []
last_date = None
chunk_size = 200
groups = []

result = client(
    GetDialogsRequest(offset_date=last_date,
                      offset_id=0,
                      offset_peer=InputPeerEmpty(),
                      limit=chunk_size,
                      hash=0))
chats.extend(result.chats)
예제 #27
0
def autos():

    channel_username = to_group
    phone = utils.parse_phone(pphone)

    client = TelegramClient(f"../sessions/{phone}", api_id, api_hash)

    client.connect()
    if not client.is_user_authorized():
        print('some thing has changed')
        client.send_code_request(phone)
        client.sign_in(phone, input('Enter the code: '))

    input_file = '../data.csv'
    users = []
    with open(input_file, encoding='UTF-8') as f:
        rows = csv.reader(f, delimiter=",", lineterminator="\n")
        next(rows, None)
        for row in rows:
            user = {}
            user['srno'] = row[0]
            user['username'] = row[1]
            user['id'] = int(row[2])
            #user['access_hash'] = int(row[2])
            user['name'] = row[3]
            users.append(user)

    startfrom = int(input("Start From = "))
    endto = int(input("End To = "))

    for user in users:
        if (int(startfrom) <= int(user['srno'])) and (int(user['srno']) <=
                                                      int(endto)):
            try:
                status = 'delta'
                if user['username'] == "":
                    print("no username, moving to next")
                    continue

                client(
                    InviteToChannelRequest(channel_username,
                                           [user['username']]))
                status = 'DONE'

                #print("Waiting for 60-180 Seconds...")
                time.sleep(random.randrange(0, 5))

            except UserPrivacyRestrictedError:
                status = 'PrivacyRestrictedError'

            except UserAlreadyParticipantError:
                status = 'ALREADY'

            except PeerFloodError as g:
                status = 'PeerFloodError :('
                print(
                    'Script Is Stopping Now, Dont Use This Account For The Next 24 Hours'
                )
                time.sleep(86400)

            except ChatWriteForbiddenError as cwfe:

                client(JoinChannelRequest(channel_username))
                continue

            except errors.RPCError as e:
                status = e.__class__.__name__

            except Exception as d:
                status = d

            except:
                traceback.print_exc()
                print("Unexpected Error")
                continue
            channel_connect = client.get_entity(channel_username)
            channel_full_info = client(
                GetFullChannelRequest(channel=channel_connect))
            countt = int(channel_full_info.full_chat.participants_count)

            print(
                f"ADDING {user['name']} TO {channel_username} TOTAL: {countt} - {status}"
            )
        elif int(user['srno']) > int(endto):
            print("Members Added Successfully!")
            stat = input(
                'Done!\nChoose From Below:\n\n1 - Repeat The Script\nOR Just Hit Enter To Quit\n\nEnter: '
            )
            if stat == '1':
                autos()
            else:
                quit()
예제 #28
0
from telethon.sync import TelegramClient
from telethon.tl.functions.messages import GetDialogsRequest
from telethon.tl.types import InputPeerEmpty
import csv

api_id = 1034958
api_hash = '2d45f484f26c058fe5e01157c5b793c0'
phone = '+1(320) 348-3469'

client = TelegramClient(phone, api_id, api_hash)

client.connect()
if not client.is_user_authorized():
    client.send_code_request(phone)
    client.sign_in(phone, input('verification Code enter kar: '))

chats = []
last_date = None
chunk_size = 200
groups = []

result = client(
    GetDialogsRequest(offset_date=last_date,
                      offset_id=0,
                      offset_peer=InputPeerEmpty(),
                      limit=chunk_size,
                      hash=0))
chats.extend(result.chats)

for chat in chats:
    try:
예제 #29
0
    api_id = cpass['cred']['id']
    api_hash = cpass['cred']['hash']
    phone = cpass['cred']['phone']
    client = TelegramClient(phone, api_id, api_hash)
except KeyError:
    os.system('clear')
    banner()
    print(re + "[!] run python3 setup.py first !!\n")
    sys.exit(1)

client.connect()
if not client.is_user_authorized():
    client.send_code_request(phone)
    os.system('clear')
    banner()
    client.sign_in(phone, input(gr + '[+] Enter the code: ' + re))

os.system('clear')
banner()
input_file = sys.argv[1]
users = []
with open(input_file, encoding='UTF-8') as f:
    rows = csv.reader(f, delimiter=",", lineterminator="\n")
    next(rows, None)
    for row in rows:
        user = {}
        user['username'] = row[0]
        user['id'] = int(row[1])
        user['access_hash'] = int(row[2])
        user['name'] = row[3]
        users.append(user)
예제 #30
0
class TelethonBaseScrapper:
    global_config = get_config()
    client = None
    app_api_id = app_api_hash = app_phone = None

    def __init__(self):
        self.set_login_info()

    def get_session_name(self):
        # return self.session_name
        return self.app_phone

    def set_login_info(self):
        self.app_api_id = get_config()['TG']['APP_API_ID']
        self.app_api_hash = get_config()['TG']['APP_API_HASH']
        self.app_phone = get_config()['TG']['APP_PHONE']
        return self

    def set_app_client(self):
        self.client = TelegramClient(self.get_session_name(), self.app_api_id,
                                     self.app_api_hash)
        self.client.start()
        self.client.connect()
        return self

    def is_auth(self):
        dump('is_auth')
        if not self.client.is_user_authorized():
            self.client.send_code_request(self.get_session_name())
            self.client.sign_in(self.get_session_name(),
                                input('Enter the code: '))

    def get_groups(self):
        dump('get_groups')
        chats = []
        groups = []
        last_date = None
        chunk_size = 200

        result = self.client(
            GetDialogsRequest(offset_date=last_date,
                              offset_id=0,
                              offset_peer=InputPeerEmpty(),
                              limit=chunk_size,
                              hash=0))
        chats.extend(result.chats)

        for chat in chats:
            dump(chat)
            groups.append(chat)
            # try:
            #     if chat.megagroup is True:
            #         channels.append(chat)
            # except:
            #     channels.append(chat)
            #     continue

        i = 0
        for c in groups:
            print(str(i) + '- ' + c.title + ' - ' + str(c.id))
            i += 1

        return groups

    def get_users(self, group):
        dump('get_users')
        users = self.client.get_participants(group, aggressive=True)

        # 資料加入 channel_id
        new_users = []
        for user in users:
            # 字典合併
            new_user = {
                **user.to_dict(),
                **{
                    'group_id': group.id,
                    'group_name': group.title
                }
            }
            new_users.append(new_user)

        return new_users