Exemple #1
0
def handle():
    client = TelegramClient("sessions", API_ID, API_KEY)

    try:
        client.start()

        docs = client.get_messages(args.channel,
                                   None,
                                   filter=InputMessagesFilterDocument)
        books = filter(filter_by_name, docs)
        if args.extensions:
            books = list(filter(filter_by_ext, books))

        total = len(books)
        print("{} books found".format(total))

        for i, book in enumerate(books):
            book_name = get_name(book)
            if args.action == "list":
                print(i + 1, book_name)

            elif args.action == "download":
                print("Downloading {index} of {total} | {name}".format(
                    index=i + 1, total=total, name=book_name))

                book.download_media(args.path + book_name)

    finally:
        client.disconnect()
    def test_cdn_download(self):
        client = TelegramClient(None, api_id, api_hash)
        client.session.set_dc(0, '149.154.167.40', 80)
        self.assertTrue(client.connect())

        try:
            phone = '+999662' + str(randint(0, 9999)).zfill(4)
            client.send_code_request(phone)
            client.sign_up('22222', 'Test', 'DC')

            me = client.get_me()
            data = os.urandom(2**17)
            client.send_file(
                me,
                data,
                progress_callback=lambda c, t: print(
                    'test_cdn_download:uploading {:.2%}...'.format(c / t)))
            msg = client.get_messages(me)[1][0]

            out = BytesIO()
            client.download_media(msg, out)
            self.assertEqual(
                sha256(data).digest(),
                sha256(out.getvalue()).digest())

            out = BytesIO()
            client.download_media(msg, out)  # Won't redirect
            self.assertEqual(
                sha256(data).digest(),
                sha256(out.getvalue()).digest())

            client.log_out()
        finally:
            client.disconnect()
Exemple #3
0
    def run(self):
        database = Database()
        client = TelegramClient('session_name', local.api_id, local.api_hash)
        client.start()

        add_notification = (
            "INSERT INTO coin_notification (id, message, date) VALUES (%(notification_id)s, %(notification_message)s, %(notification_date)s)"
        )

        cursor = database.query("select max(id) as mx from coin_notification")

        last_db_id = 0
        for mx in cursor:
            last_db_id = mx[0]

        regex = r'[^a-zA-Z0-9.()%/#]+'
        channel = PeerChannel(channel_id=1131948783)

        while True:
            messages = client.get_messages(channel,
                                           min_id=last_db_id,
                                           limit=1000)
            if len(messages) == 0:
                break

            for m in messages:
                m.message = re.sub(regex, ' ', m.message)
                notification = {
                    'notification_id': m.id,
                    'notification_message': m.message.encode('utf8'),
                    'notification_date': m.date
                }
                database.execute(add_notification, notification)

        database.close()
Exemple #4
0
def main():
    # get your api id from my.telegram.org
    api_id = "your_id_here"
    api_hash = 'your_hash_here'
    # archive.session is a sqlite database and where program store your account details
    session_name = 'archive.session'
    # client initiation
    client = TelegramClient(session_name,
                            api_id,
                            api_hash,
                            proxy=None,
                            update_workers=4,
                            spawn_read_thread=False)
    client.start()
    str = ""
    count = 0
    # descriptions about how many messages program is retrieving
    print("""Number of messages to be retrieved. Due to limitations with
the API retrieving more than 3000 messages will take longer
than half a minute (or even more based on previous calls).
The limit may also be ``None``, which would eventually return
the whole history.

working...
""")
    # program retrieves messages with 'me' contact which is your chat id
    for message in client.get_messages('me', limit=None):
        sender = utils.get_display_name(message.sender)
        message = message.message
        str += "<h1>{}</h1>{}<hr>".format(sender, message)
        count += 1
    mkhtml(str, count)
    print("history archived successfully :)")
Exemple #5
0
def balance(x, summ, flag):
    Phone = accounts[x][1]
    print(f"Входим в аккаунт -> {x+1}: {Phone}")
    api_id = accounts[x][3]
    api_hash = accounts[x][4]
    session = str("anon" + str(x+1))
    client = TelegramClient(session, api_id, api_hash)
    client.start()

    dlgs = client.get_dialogs()
    for dlg in dlgs:
        if dlg.title == 'LTC Click Bot':
            tegmo = dlg

    client.send_message('LTC Click Bot', "/balance")
    time.sleep(10)
    msgs = client.get_messages(tegmo, limit=1)

    for mes in msgs:
        str_a = str(mes.message)
        zz = str_a.replace('Available balance: ', '')
        qq = zz.replace(' LTC', '')
        print(qq)
        waitin = float(qq)
    summ.value += waitin
    flag.value += 1
    time.sleep(1)
class telegram_API:
    def __init__(self):
        self.api_id = YOUR_API_ID
        self.api_hash = 'YOUR_API_HASH'

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

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

    def teleg_ch_posts(self, username):
        #posts info
        self.client = TelegramClient('session', self.api_id,
                                     self.api_hash).start()
        chats = self.client.get_messages(username, 100)
        message_id = []
        message = []
        sender = []
        reply_to = []
        time = []
        if len(chats):
            for chat in chats:
                message_id.append(chat.id)
                message.append(chat.message)
                sender.append(chat.from_id)
                reply_to.append(chat.reply_to_msg_id)
                time.append(chat.date)
        data = {
            'message_id': message_id,
            'message': message,
            'sender_ID': sender,
            'reply_to_msg_id': reply_to,
            'time': time
        }
        pd.DataFrame(data).to_csv('farsna_messages.csv')
        return data
Exemple #7
0
async def feed(request, ws, _id):
    print(_id)
    client = TelegramClient('session_name', api_id, api_hash)
    async with client:
        print(client.get_entity(_id))
    await ws.send('hello im {}. how can i help you'.format(_id))
    client = TelegramClient('session_name', api_id, api_hash)
    async with client:
        while True:
            try:
                await asyncio.wait_for(client.send_message(
                    _id, await ws.recv()),
                                       timeout=.5)
            except:
                for message in client.get_messages(_id):
                    ws.send(message)
Exemple #8
0
    def execute(self):
        api_id = 263724
        api_hash = "3a8ae22a8e6981038a370c7149d51fc2"

        sn_path = Path.join(Path.dirname(__file__), 'session_name')
        client = TelegramClient(sn_path, api_id, api_hash)
        client.connect()
        username = '******'
        try:
            for message in client.get_messages(username, limit=1):
                if not DBWorker.get_telega_id_date(message.id):

                    file = client.download_media(message, Config().type_paths.get('import'))
                    FSWorker.log('From telega was downloaded: "{}"'.format(file))
                    DBWorker.write_telega_id(message.id)
        except Exception as err:
            FSWorker.log("Fucken bitch dead again. BIIIIITCH")
Exemple #9
0
def check_new():
    print('Start cheking')
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    bot = telebot.AsyncTeleBot(TOKEN, num_threads=3)
    proxy = ('proxy.digitalresistance.dog', 443,
             'd41d8cd98f00b204e9800998ecf8427e')
    api_hash = "e9d6b9e0826b56613da7a625b1ced401"
    api_id = 995881
    client = TelegramClient('session_name',
                            api_id,
                            api_hash,
                            proxy=proxy,
                            connection=connection.tcpmtproxy.
                            ConnectionTcpMTProxyRandomizedIntermediate)

    client.connect()
    while CHECKER:
        print('Checking...')
        cursor.execute("select * from users")
        for i in cursor.fetchall():
            temp = 0
            print('Work with', i)
            dp = client.get_entity(i[1])
            messages = client.get_messages(dp, limit=100, min_id=1)
            for j in messages:
                temp = max(j.id, temp)
                if i[3] in j.text:
                    bot.send_message(i[1], j.text)
            print('???', j.id, i[0], i[1])
            cursor.execute(
                "update users set Last_id = {} where User_id = '{}' and Channel_id = '{}'"
                .format(temp, i[0], i[1]))
            conn.commit()
            print('!!!')
            time.sleep(1)
        time.sleep(15)
        print('END CHECK')
    bot.polling()

    conn.close()
    client.disconnect()
Exemple #10
0
def func(url):
    print('Start parsing')
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    proxy = ('proxy.digitalresistance.dog', 443,
             'd41d8cd98f00b204e9800998ecf8427e')
    api_hash = "e9d6b9e0826b56613da7a625b1ced401"
    api_id = 995881
    client = TelegramClient('session_name',
                            api_id,
                            api_hash,
                            proxy=proxy,
                            connection=connection.tcpmtproxy.
                            ConnectionTcpMTProxyRandomizedIntermediate)
    print('qwer')
    client.connect()
    dp = client.get_entity(url)
    messages = client.get_messages(dp, limit=100)
    client.disconnect()
    return messages
Exemple #11
0
def _fetch_tg_tasks(logger):
    client = TelegramClient(TELETHON_SESSION, TG_APP_ID, TG_APP_HASH)
    client.connect()
    client.start()
    [todo_dialog] = [d for d in client.get_dialogs() if d.name == GROUP_NAME]
    api_messages = client.get_messages(
        todo_dialog.input_entity, limit=1000000)  # TODO careful about limit?

    messages = [m for m in api_messages
                if not isinstance(m, MessageService)]  # wtf is that...

    # group together multiple forwarded messages. not sure if there is a more robust way but that works well
    from itertools import groupby
    key = lambda f: f.date
    grouped = groupby(sorted(messages, key=key), key=key)
    tasks = []
    for _, group in grouped:
        res = format_group(list(group), dialog=todo_dialog, logger=logger)
        tasks.append(res)
    return tasks
def get_diags(session_name, api_id, api_hash):
    """
    Getting dialogs list

    Args:
        session_name: session name for telegram
        api_id: Telegram Api Id
        api_hash: Telegram Api Hash

    Returns:
        dict of diags:
        {
            'id':[],
            'name':[],
            'total_msgs':[],
            'is_user':[],
            'is_group':[],
            'is_channel':[],
        } 
    """
    diags = {
        'id': [],
        'name': [],
        'total_msgs': [],
        'is_user': [],
        'is_group': [],
        'is_channel': []
    }
    client = TelegramClient(session_name, api_id, api_hash)
    client.connect()
    for diag in client.iter_dialogs():
        diags['id'].append(diag.id)
        diags['name'].append(diag.name)
        diags['total_msgs'].append(client.get_messages(diag).total)
        diags['is_user'].append(diag.is_user)
        diags['is_group'].append(diag.is_group)
        diags['is_channel'].append(diag.is_channel)
        print(diag.name)
    client.disconnect()
    return diags
Exemple #13
0
api_id 你的api id
api_hash 你的api hash
channel_link 要下载图片的频道链接
proxy 将localhost改成代理地址,1080改成代理端口
picture_storage_path 图片下载到的路径
'''

api_id = 80xxxxx
api_hash = "3066c1322d6931a85470xxxxxx"
channel_link = "https://t.me/xx"
proxy =(socks.SOCKS5,"0.0.0.0",1080) #不需要代理的话删掉该行
picture_storage_path = "/"
# ==========================================
client = TelegramClient('my_session',api_id=api_id,api_hash=api_hash).start()
    
photos = client.get_messages(channel_link,None,max_id=100000,min_id=0, filter=InputMessagesFilterPhotos)
    
total = len(photos)
index = 0
for photo in photos:
#    filename = picture_storage_path + "/" +str(photo.text)+"_"+str(photo.id) + ".jpg" #名字_id
    filename = picture_storage_path + "/" +str(photo.id) + ".jpg"
    index = index + 1
    print("downloading:", index, "/", total, " : ", filename)
    if  os.path.exists(filename)==False:
        client.download_media(photo, filename)
        print('done!')
    else:
        print('exist!')
client.disconnect()
print("Done.")
Exemple #14
0
    msgs = client.get_messages(name)

    result = client(
        functions.messages.ForwardMessagesRequest(from_peer=name,
                                                  id=[msgs[0].id],
                                                  to_peer="Litecoin_click_bot",
                                                  with_my_score=True))
    if len(bot_l) >= 3:
        del bot_l[0]


while True:
    if n % 10 == 0:
        client.send_message('Litecoin_click_bot', '/withdraw')
        time.sleep(1)
        msgs = client.get_messages('Litecoin_click_bot')

        if "To withdraw, enter your" in msgs[0].message:
            client.send_message('Litecoin_click_bot', wallet)
            time.sleep(1)
            client.send_message('Litecoin_click_bot', '0.0004')
            time.sleep(1)
            client.send_message('Litecoin_click_bot', 'Confirm')
    j = 0

    msgs = client.get_messages('Litecoin_click_bot')
    while True:
        j += 1
        if j == 20:
            h = 0
            print("другой заработок")
Exemple #15
0
    def run(self, conf, args, plugins):
        session_file = os.path.join(os.path.expanduser("~"),
                                    ".config/harpoon/telegram")
        client = TelegramClient(session_file, int(conf['Telegram']['id']),
                                conf['Telegram']['hash'])
        # FIXME : do not connect if it's help
        client.connect()
        if not client.is_user_authorized():
            client.send_code_request(conf['Telegram']['phone'])
            code_ok = False
            while not code_ok:
                code = input("Enter Telegram code:")
                try:
                    code_ok = client.sign_in(conf['Telegram']['phone'], code)
                except SessionPasswordNeededError:
                    # FIXME: getpass is not imported, that would not work
                    password = getpass(
                        'Two step verification enabled. Please enter your password: '******'subcommand'):
            if args.subcommand == 'id':
                try:
                    res = client.get_entity(args.ID)
                    print(
                        json.dumps(res.to_dict(),
                                   sort_keys=True,
                                   indent=4,
                                   default=json_serial))
                except ValueError:
                    print('Identifier not found')
            elif args.subcommand == "messages":
                entity = client.get_entity(args.ID)
                messages = client.get_messages(entity, args.limit)
                users = {}
                if args.dump:
                    if not os.path.exists(args.dump):
                        os.makedirs(args.dump)
                if args.format == "text":
                    if len(messages) == 0:
                        print("No messages in this channel")
                    else:
                        print("%i messages downloaded:" % len(messages))
                        for msg in messages:
                            if isinstance(msg,
                                          telethon.tl.types.MessageService):
                                if isinstance(
                                        msg.action, telethon.tl.types.
                                        MessageActionChatEditPhoto):
                                    print("[%s] Channel Photo Changed" %
                                          msg.date.isoformat())
                                elif isinstance(
                                        msg.action, telethon.tl.types.
                                        MessageActionChannelCreate):
                                    print("[%s] Channel Created" %
                                          msg.date.isoformat())
                                elif isinstance(
                                        msg.action, telethon.tl.types.
                                        MessageActionChatAddUser):
                                    print(
                                        "[%s] Add Users To the Chat - %s" %
                                        (msg.date.isoformat(), ", ".join(
                                            [str(a)
                                             for a in msg.action.users])))
                                elif isinstance(
                                        msg.action, telethon.tl.types.
                                        MessageActionChatDeleteUser):
                                    print(
                                        "[%s] Remove User from the chat - %i" %
                                        (msg.date.isoformat(),
                                         msg.action.user_id))
                                else:
                                    print("[%s] Message Service: %s" %
                                          (msg.date.isoformat(),
                                           msg.action.message))
                            else:
                                if msg.media is None:
                                    if entity.megagroup:
                                        if msg.from_id not in users:
                                            users[msg.
                                                  from_id] = client.get_entity(
                                                      msg.from_id)
                                        print(
                                            "[%s][%i - @%s] %s" %
                                            (msg.date.isoformat(), msg.from_id,
                                             users[msg.from_id].username,
                                             msg.message))
                                    else:
                                        print("[%s] %s (%i views)" %
                                              (msg.date.isoformat(),
                                               msg.message, msg.views))
                                else:
                                    if msg.views:
                                        print(
                                            "[%s] Media (%i views)" %
                                            (msg.date.isoformat(), msg.views))
                                    else:
                                        print("[%s] Media" %
                                              (msg.date.isoformat()))
                                    if args.dump:
                                        if not os.path.exists(
                                                os.path.join(
                                                    args.dump,
                                                    str(msg.id) + '.jpg')):
                                            client.download_media(
                                                msg.media,
                                                os.path.join(
                                                    args.dump, str(msg.id)))
                                            time.sleep(7)
                elif args.format == "json":
                    msg = [m.to_dict() for m in messages]
                    print(
                        json.dumps(msg,
                                   sort_keys=True,
                                   indent=4,
                                   default=json_serial))
                    if args.dump:
                        for msg in messages:
                            if msg.media is None:
                                if not os.path.exists(
                                        os.path.join(args.dump,
                                                     str(msg.id) + '.jpg')):
                                    client.download_media(
                                        msg.media,
                                        os.path.join(args.dump, str(msg.id)))
                                    time.sleep(7)
                elif args.format == "csv":
                    if entity.megagroup:
                        # Chat
                        w = csv.writer(sys.stdout, delimiter=';')
                        w.writerow([
                            "Date", "id", "Username", "userid", "Type",
                            "Message"
                        ])
                        for m in messages:
                            if m.from_id not in users:
                                users[m.from_id] = client.get_entity(m.from_id)
                            if isinstance(m, telethon.tl.types.MessageService):
                                w.writerow([
                                    m.date.isoformat(), m.id,
                                    users[m.from_id].username, m.from_id,
                                    m.__class__.__name__,
                                    m.action.__class__.__name__
                                ])
                            else:
                                w.writerow([
                                    m.date.isoformat(), m.id,
                                    users[m.from_id].username, m.from_id,
                                    m.__class__.__name__, m.message
                                ])
                    else:
                        w = csv.writer(sys.stdout, delimiter=';')
                        w.writerow([
                            "Date", "id", "Type", "Information", "Media",
                            "Views"
                        ])
                        for m in messages:
                            if isinstance(m, telethon.tl.types.MessageService):
                                if isinstance(
                                        m.action, telethon.tl.types.
                                        MessageActionChatEditPhoto):
                                    w.writerow([
                                        m.date.isoformat(), m.id,
                                        m.__class__.__name__,
                                        "Channel Photo Changed", "No", ""
                                    ])
                                elif isinstance(
                                        m.action, telethon.tl.types.
                                        MessageActionChannelCreate):
                                    w.writerow([
                                        m.date.isoformat(), m.id,
                                        m.__class__.__name__,
                                        "Channel Created", "No", ""
                                    ])
                                else:
                                    w.writerow([
                                        m.date.isoformat(), m.id,
                                        m.__class__.__name__,
                                        m.action.__class__.__name__, "No", ""
                                    ])
                            else:
                                if m.media is None:
                                    # message
                                    w.writerow([
                                        m.date.isoformat(), m.id,
                                        m.__class__.__name__, m.message, "No",
                                        m.views
                                    ])
                                else:
                                    w.writerow([
                                        m.date.isoformat(), m.id,
                                        m.__class__.__name__, m.message, "Yes",
                                        m.views
                                    ])
                                    if args.dump:
                                        if not os.path.exists(
                                                os.path.join(
                                                    args.dump,
                                                    str(m.id) + '.jpg')):
                                            client.download_media(
                                                m.media,
                                                os.path.join(
                                                    args.dump, str(m.id)))
                                            # Sleep to avoid being banned
                                            time.sleep(7)
                else:
                    print("Not implemented yet, sorry!")
            elif args.subcommand == "users":
                # List users from a group
                try:
                    entity = client.get_entity(args.ID)
                    offset = 0
                    limit = args.limit
                    all_participants = []

                    while True:
                        participants = client.invoke(
                            GetParticipantsRequest(
                                entity,
                                ChannelParticipantsSearch(''),
                                offset,
                                limit,
                                hash=0))
                        if not participants.users:
                            break
                        all_participants.extend(participants.users)
                        offset += len(participants.users)
                        time.sleep(
                            1
                        )  # This line seems to be optional, no guarantees!
                except ChatAdminRequiredError:
                    print(
                        "You don't have required access rights to get this list"
                    )
                else:
                    if args.format == "text":
                        for p in all_participants:
                            print("[+] User: %s (%s %s)" %
                                  (p.username, p.first_name, p.last_name))
                    elif args.format == "json":
                        users = [u.to_dict() for u in all_participants]
                        print(
                            json.dumps(users,
                                       sort_keys=True,
                                       indent=4,
                                       default=json_serial))
                    else:
                        print("Not implemented yet, sorry!")

            else:
                self.parser.print_help()
        else:
            self.parser.print_help()
Exemple #16
0
from telethon import TelegramClient, sync
import time
from mss import mss
import traceback

api_id = 250149
api_hash = '898d3c607f66f9049a944ec8dfd7a23b'

try:

    client = TelegramClient('session_name', api_id, api_hash)
    client.start()

    while True:
        time.sleep(1)
        messages = client.get_messages('mani_google_bot')
        if messages[0].message == 'screenshot':
            print("entered if")
            with mss() as sct:
                sct.shot()
            client.send_file('mani_google_bot', "monitor-1.png")
        print("mani")

except:
    print("exception happened")
    traceback.print_exc()
    input()
                                                           exist_ok=True)

    file_csv = os.path.join('..', 'data', group_username,
                            '{}_messages.csv'.format(group_username))
    with open(file_csv, 'w') as output_file:
        dict_writer = csv.DictWriter(output_file, keys)
        dict_writer.writeheader()

    # We scrape starting from the first message and until we haven't reached the max number of messages.
    # For each message, we create a dictionary associated to its most important info for us and then we append it to
    # the "messages" list. After that, we save the list to a file in CSV format.
    #
    # This could take up to 3 hours for each group...
    messages = []
    chats = client.get_messages(group_username,
                                max_id=max,
                                min_id=0,
                                reverse=True)

    if len(chats):

        for chat in chats:
            row = {
                'message_id': chat.id,
                'sender_id': chat.from_id,
                'reply_to_msg_id': chat.reply_to_msg_id,
                'time': chat.date
            }
            messages.append(row)

        if len(messages):
            with open(file_csv.format(group_username), 'a') as output_file:
Exemple #18
0
    class controller:
        def __init__(self):
            self.accs_list = []
            self.done_counter = 0
            self.sorry_counter = 0
            self.main_dialog = False
            self.acc_id = ''
            self.phone = ''
            self.api_id = 0
            self.api_hash = ''
            self.session = ''
            self.main_dialog = False
            self.sleep_after_start = 20

        @autolog
        def get_accs_list(self):
            db = sqlite3.connect('Account.db')
            cursor = db.cursor()
            cursor.execute("SELECT * FROM Account")
            rows = cursor.fetchall()
            _list = []

            for row in rows:
                _list.append({
                    'id': row[0],
                    'phone': row[1],
                    'pass': row[2],
                    'api_id': row[3],
                    'api_hash': row[4],
                })


#            self.accs_list = _list[42:]
            self.accs_list = _list

        @autolog
        def acc_initialization(self, acc):
            self.done_counter = 0
            self.sorry_counter = 0
            self.main_dialog = False
            self.acc_id = acc.get('id')
            self.phone = acc.get('phone')
            self.api_id = acc.get('api_id')
            self.api_hash = acc.get('api_hash')
            self.session = f"anon{self.acc_id}"

        @autolog
        def stat_upd_for_notify_bot(self):
            status_file = open('queue.tmp', 'w')
            status_file.write(f"{self.acc_id}")
            status_file.close()

        def login_bot(self):
            logging.warning(
                f"\n\n\nLogging as: {self.phone} (bot {self.acc_id})\n")
            self.client = TelegramClient(self.session, self.api_id,
                                         self.api_hash)
            self.client.start()

        @autolog
        def get_main_dialog(self):
            # ?????????????????????????
            self.main_dialog = False
            for dialog in self.client.get_dialogs():
                if dialog.title == 'LTC Click Bot':
                    self.main_dialog = dialog

        @autolog
        def start_message(self):
            logging.warning(
                "Time to sleep: {time_set}+2 ({realtime}) sec".format(
                    time_set=self.sleep_after_start,
                    realtime=self.sleep_after_start + 2))

            self.client.send_message('LTC Click Bot', "/menu")
            time.sleep(2)
            self.client.send_message('LTC Click Bot', "🖥 Visit sites")
            time.sleep(self.sleep_after_start)

        @autolog
        def get_last_msg_str(self):
            #self.last_msg_str = self.client.get_messages(self.main_dialog)[0].message
            time.sleep(3)
            self.last_msg_str = self.client.get_messages('Litecoin_click_bot',
                                                         limit=2)[0].message
            logging.warning(f'Message is: \n{self.last_msg_str}')

        @autolog
        def get_previous_msg_str(self):
            try:
                time.sleep(3)
                self.previous_msg_str = self.client.get_messages(
                    'Litecoin_click_bot', limit=2)[1].message
                logging.warning(f'PRE-Message is: \n{self.previous_msg_str}')

            except Exception as e:
                logging.warning(e)
                self.previous_msg_str = ''

        @autolog
        def sorry_reactor(self):
            self.start_message()
            self.sorry_counter += 1

        @autolog
        def skip_task(self):
            self.client.send_message('LTC Click Bot', "/visit")
            time.sleep(3)
            msgs_2 = self.client.get_messages('Litecoin_click_bot')
            self.skip_message_id = msgs_2[0].id
            self.skip_button_data = msgs_2[0].reply_markup.rows[1].buttons[
                1].data

            from telethon.tl.functions.messages import GetBotCallbackAnswerRequest
            self.client(
                GetBotCallbackAnswerRequest('LTC Click Bot',
                                            self.skip_message_id,
                                            data=self.skip_button_data))
            time.sleep(2)

        @autolog
        def get_time_to_wait(self):
            try:
                if re.search(r'seconds to get your reward', self.last_msg_str):
                    self.time_to_wait = int(
                        re.search(r'\d+', self.last_msg_str).group())
                else:
                    self.time_to_wait = 4

            except Exception as e:
                self.time_to_wait = 30
                logging.warning(e)

        @autolog
        def calculate_profit(self):
            try:
                profit = 0
                with open('profit_', 'r') as profit_file:
                    for line in profit_file.readlines():
                        profit = float(line)

                new_money = float(
                    re.search(r'\d+.\d+', self.previous_msg_str[:45]).group())
                new_profit = float(profit + new_money)

                logging.warning('\n'
                                f'money: {"{0:.8f}".format(new_money)}\n'
                                f'had__: {"{0:.8f}".format(profit)}\n'
                                f'itog_: {"{0:.8f}".format(new_profit)}\n')

                with open('profit_', 'w') as profit_file:
                    profit_file.write(f'{"{0:.8f}".format(new_profit)}')

                logging.warning(
                    f'{"=" * 10}\nPROFIT: {"{0:.8f}".format(ltc_profit)} LTC')

            except Exception as e:
                logging.warning(e)

        @autolog
        def chrome_test(self):
            logging.warning(f'Time to wait: {self.time_to_wait}')
            selenium_url = "http://localhost:4444/wd/hub"
            caps = {'browserName': 'chrome'}
            driver = webdriver.Remote(command_executor=selenium_url,
                                      desired_capabilities=caps)
            driver.maximize_window()
            driver.get(self.adw_url)
            time.sleep(self.time_to_wait + 10 if self.time_to_wait > 4 else 4)
            driver.close()
            driver.quit()

        @autolog
        def chrome_reactor(self):
            self.client.send_message('LTC Click Bot', "/visit")
            time.sleep(3)

            try_counter = 0

            while try_counter < 2:
                try:
                    self.chrome_test()
                    break
                except Exception as e:
                    logging.warning(f'\n         Chrome crushed (1)')
                    logging.warning(e)
                    try_counter += 1

        @autolog
        def req_reactor(self):
            self.previous_msg_str = ''
            self.client.send_message('LTC Click Bot', "/visit")
            time.sleep(3)

            self.get_last_msg_str()
            msgs_2 = self.client.get_messages('Litecoin_click_bot', limit=2)
            self.adw_url = msgs_2[0].reply_markup.rows[0].buttons[0].url

            self.get_time_to_wait()
            self.chrome_reactor()

            logging.warning('\nWaiting for an answer...')

            self.get_last_msg_str()
            if re.search(r'stay on the site for at', self.last_msg_str):
                temp_req = requests.get(self.adw_url).json
                time.sleep(5)
                self.get_last_msg_str()

            if re.search(r'seconds to get your reward', self.last_msg_str):
                self.get_time_to_wait()
                self.chrome_reactor()

            self.get_previous_msg_str()
            if re.search(r'You earned', self.previous_msg_str):
                self.done_counter += 1
                self.calculate_profit()
                return logging.warning('Task done! Ez-pz!')

            if re.search(r'Sorry, there are no new ads available',
                         self.last_msg_str):
                self.done_counter += 1
                return logging.warning('Task done! Ez-pz!')

            else:
                self.skip_task()
                return logging.warning('Task skipped')

        @autolog
        def select_reactor(self):
            self.get_last_msg_str()

            if re.search(r'Sorry, there are no new ads available.',
                         self.last_msg_str):
                self.sorry_reactor()

            #elif re.search(r'\bseconds to get your reward\b', self.last_msg_str):
            #    self.chrome_reactor()

            else:
                self.req_reactor()

        @autolog
        def make_tasks(self):
            while True:
                logging.warning(
                    f"Bot {self.acc_id} has DONE {self.done_counter} tasks")

                if self.sorry_counter == 2:
                    logging.warning("Have no ads 2 times")
                    logging.warning("Moving to the next account")
                    break

                elif self.done_counter == 16:
                    logging.warning("Moving to the next account")
                    break

                else:
                    self.select_reactor()

        @autolog
        def mining(self):
            self.get_accs_list()

            if self.accs_list:
                for acc in self.accs_list:
                    try:
                        self.acc_initialization(acc)
                        self.stat_upd_for_notify_bot()
                        self.login_bot()
                        self.get_main_dialog()
                        if not bool(self.main_dialog):
                            logging.warning(
                                f'{self.phone} (bot {self.acc_id}) HAVE NO LITECOIN BOT!!!'
                            )
                            break

                        else:
                            self.start_message()
                            self.get_last_msg_str()

                            if self.last_msg_str is not "🖥 Visit sites":
                                self.make_tasks()

                            else:
                                logging.warning(
                                    "Didn't get an answer for a start_message()"
                                )

                    except Exception as e:
                        logging.warning(f'\n\n WE ARE DOWN \nError: {e}')
                        pass

                time.sleep(3)
            else:
                logging.warning('No accounts list is empty')
Exemple #19
0
#邀请成员进入频道,加机器人可以,加朱铭不可以,用户的隐私不允许你这样做
# client(InviteToChannelRequest(
#     channel= 1219921340,
#     users = ['HuingZM'],
#     ))

#转发信息
# messages = client.get_messages('china_BiBi')
# print(messages[0])
# mes_id = messages[0].id
# mes_text = messages[0].text
# print(mes_text)
# client.forward_messages(1219921340,mes_id,1182116619)

messages = client.get_messages('china_BiBi')
mes_id_1 = messages[0].id
while True:
    messages = client.get_messages('china_BiBi')
    mes_id = messages[0].id
    if mes_id != mes_id_1:
        client.forward_messages(1219921340, mes_id, 1182116619)
        mes_id_1 = mes_id

# For normal chats
# client(AddChatUserRequest(
#     chat_id = -1001219921340 , #chat_id
#     user_id = 585015279, #被邀请人id
#     fwd_limit=10  # Allow the user to see the 10 last messages
# ))
# сюда перешел, свои вводные получил https://my.telegram.org
api_id = 77777777 # свой получай
api_hash = 'durovpriexalnasadovod'  #тоже свой получай

#укажи прокси, я поднял ssh туннель через putty
client = TelegramClient('session_name', api_id, api_hash, proxy=(socks.SOCKS5, 'localhost', 5555))

phone_number = '+777777777777' #свой телефон вбивай
client.connect()
if not client.is_user_authorized():
    client.send_code_request(phone_number)
    me = client.sign_in(phone_number, input('Enter code: '))

channel_username = sys.argv[1] # чат\канал
# загружаем косарь сообщений. Можно увеличить/уменьшить
msgs = client.get_messages(channel_username, 1000, filter=InputMessagesFilterDocument)
for msg in msgs:
    if msg.media is not None:        
        if os.path.exists('./'+channel_username+'/'+msg.media.document.attributes[0].file_name) and os.path.getsize('./'+channel_username+'/'+msg.media.document.attributes[0].file_name) == msg.media.document.size:
            print('File: '+ msg.media.document.attributes[0].file_name + ' exists and size is ok, skipping...')
            continue
        else:
            try:
                fn = msg.media.document.attributes[0].file_name.replace('\n',' ').replace('\r', '').replace('\\', ' ')
                client.download_media(msg,file='./'+channel_username+'/'+fn)
            except FloodWaitError as e:
                print('Flood waited for', e.seconds)
                quit(1)
        print('Downloaded file: '+ msg.media.document.attributes[0].file_name)
print('Downloading complete')
Exemple #21
0
    msgs = client.get_messages(name)

    result = client(
        functions.messages.ForwardMessagesRequest(from_peer=name,
                                                  id=[msgs[0].id],
                                                  to_peer="BCH_clickbot",
                                                  with_my_score=True))
    if len(bot_l) >= 3:
        del bot_l[0]


while True:
    if n % 10 == 0:
        client.send_message('BCH_clickbot', '/withdraw')
        time.sleep(1)
        msgs = client.get_messages('BCH_clickbot')

        if "To withdraw, enter your" in msgs[0].message:
            client.send_message('BCH_clickbot', wallet)
            time.sleep(1)
            client.send_message('BCH_clickbot', '0.0001')
            time.sleep(1)
            client.send_message('BCH_clickbot', 'Confirm')
    j = 0

    msgs = client.get_messages('BCH_clickbot')
    while True:
        j += 1
        if j == 20:
            h = 0
            print("другой заработок")
Exemple #22
0
def bot(x, tasks, taskMode, botMode):
    n = 0
    u = 0

    Phone = accounts[x][1]
    print(f"\nВходим в аккаунт: {x+1} --> {Phone}\n")

    api_id = accounts[x][3]
    api_hash = accounts[x][4]
    session = str("anon" + str(x + 1))
    client = TelegramClient(session, api_id, api_hash)
    try:
        client.start()
    except:
        print("Connection Error!!!")

    dlgs = client.get_dialogs()
    for dlg in dlgs:
        if dlg.title == 'LTC Click Bot':
            tegmo = dlg
    client.send_message('LTC Click Bot', "🖥 Visit sites")
    time.sleep(15)
    while True:
        time.sleep(6)
        if u == 2:
            botMode[x] = 'W'
            n = 0
            taskMode[x] = '-'
            time.sleep(3600 * 5)
        tasks[x] = n
        botMode[x] = 'G'
        msgs = client.get_messages(tegmo, limit=1)
        for mes in msgs:
            if re.search(r'\bseconds to get your reward\b', mes.message):
                str_a = str(mes.message)
                zz = str_a.replace('You must stay on the site for', '')
                qq = zz.replace('seconds to get your reward.', '')
                waitin = int(qq)
                taskMode[x] = f'r({waitin})'
                client.send_message('LTC Click Bot', "/visit")
                time.sleep(3)
                msgs2 = client.get_messages(tegmo, limit=1)
                for mes2 in msgs2:
                    button_data = mes2.reply_markup.rows[1].buttons[1].data
                    message_id = mes2.id
                    taskMode[x] = f'r --> {waitin}'
                    time.sleep(2)
                    try:
                        url_rec = messages[0].reply_markup.rows[0].buttons[
                            0].url
                    except:
                        print(messages[0].reply_markup)
                        break
                    ch = RunChromeTests()

                    ch.testMethod(url_rec, waitin)
                    fp = urllib.request.urlopen(
                        urllib.request.Request(
                            url_rec, headers={'User-Agent': 'Mozilla/5.0'}))
                    bytes = fp.read()
                    mystr = bytes.decode("utf8")
                    fp.close()
                    if re.search(r'\bSwitch to reCAPTCHA\b', mystr):
                        resp = client(
                            GetBotCallbackAnswerRequest('LTC Click Bot',
                                                        message_id,
                                                        data=button_data))
                        time.sleep(2)
                        print("КАПЧА!")

            elif re.search(r'\bSorry\b', mes.message):
                u = u + 1

            else:
                taskMode[x] = 'S'
                messages = client.get_messages('Litecoin_click_bot')
                try:
                    url_rec = messages[0].reply_markup.rows[0].buttons[0].url
                except:
                    print(messages[0].reply_markup)
                    break
                try:
                    f = open(f"per{x}.txt")
                except:
                    f = open(f"per{x}.txt", 'w')
                fd = f.read()
                if fd == url_rec:
                    #print("Найдено повторение переменной")
                    msgs2 = client.get_messages(tegmo, limit=1)
                    for mes2 in msgs2:
                        button_data = mes2.reply_markup.rows[1].buttons[1].data
                        message_id = mes2.id
                        resp = client(
                            GetBotCallbackAnswerRequest(tegmo,
                                                        message_id,
                                                        data=button_data))
                        time.sleep(2)
                else:
                    waitin = 15
                    try:
                        data1 = requests.get(url_rec).json
                    except:
                        print("Request Error!!!")
                        break

                    my_file = open(f'per{x}.txt', 'w')
                    my_file.write(url_rec)
                    #print("Новая запись в файле сделана")
                    time.sleep(12)
                    n += 1
Exemple #23
0
api_id = -1
api_hash = ''

client = TelegramClient('session_name', api_id, api_hash)
client.start()

dialogs = client.get_dialogs(limit=100)

lectures = None
for dialog in dialogs:
    if dialog.name == 'Лекции':
        lectures = dialog

# print(lectures)

messages = client.get_messages(lectures, limit=1000)

for message in messages:
    if message.message is None:
        continue

    text = message.message

    if '#' not in text:
        continue

    if '_Л' not in text and '#Г' not in text:
        lines = text.splitlines()

        tags = []
api_hash 你的api hash
channel_link 要下载图片的频道链接
proxy 将localhost改成代理地址,12345改成代理端口
picture_storage_path 图片下载到的路径
'''
api_id = 123456
api_hash = "23jhbfj23kbf3wkfbwk3j8w3fbesiug"
channel_link = "https://t.me/xxxx"
proxy = ("socks5", "localhost", 12345)  #不需要代理的话删掉该行
picture_storage_path = "picture_storage_path"
# ==========================================
client = TelegramClient('my_session',
                        api_id=api_id,
                        api_hash=api_hash,
                        proxy=proxy).start()

photos = client.get_messages(channel_link,
                             None,
                             filter=InputMessagesFilterPhotos)

total = len(photos)
index = 0
for photo in photos:
    filename = picture_storage_path + "/" + str(photo.id) + ".jpg"
    index = index + 1
    print("downloading:", index, "/", total, " : ", filename)
    client.download_media(photo, filename)

client.disconnect()
print("Done.")
Exemple #25
0
        break

client.send_message(tegmo, '/start')
client1.send_message(tegmo1, '/start')
client2.send_message(tegmo2, '/start')
client3.send_message(tegmo3, '/start')
client4.send_message(tegmo4, '/start')
client5.send_message(tegmo5, '/start')
client6.send_message(tegmo6, '/start')
client7.send_message(tegmo7, '/start')
client8.send_message(tegmo8, '/start')
client9.send_message(tegmo9, '/start')

time.sleep(5)

msgs = client.get_messages(tegmo, limit=1)
msgs1 = client1.get_messages(tegmo1, limit=1)
msgs2 = client2.get_messages(tegmo2, limit=1)
msgs3 = client3.get_messages(tegmo3, limit=1)
msgs4 = client4.get_messages(tegmo4, limit=1)
msgs5 = client5.get_messages(tegmo5, limit=1)
msgs6 = client6.get_messages(tegmo6, limit=1)
msgs7 = client7.get_messages(tegmo7, limit=1)
msgs8 = client8.get_messages(tegmo8, limit=1)
msgs9 = client9.get_messages(tegmo9, limit=1)

msg = msgs[0]
msg1 = msgs1[0]
msg2 = msgs2[0]
msg3 = msgs3[0]
msg4 = msgs4[0]
Exemple #26
0
            print("El mensaje no era valido\n")
            message_lower = ''

        for keyword in keywords:
            if keyword in message_lower:
                print(f'mensaje enviado: {message_lower}\n')
                message.forward_to(chat)


while 1:
    print('start')
    # client.send_message(entity=log_chat,
    #                     message=f'start')

    messages = client.get_messages('DondeHayEnLaHabana',
                                   limit=500,
                                   min_id=int(MIN_MSG_ID))

    if len(messages) > 0:
        MIN_MSG_ID = messages[0].id
        with open('info.json', 'w') as info_file:
            json_string = "{'MIN_MSG_ID': '" + str(MIN_MSG_ID) + "'}"
            json_string = {"MIN_MSG_ID": str(MIN_MSG_ID)}
            json_string = json.dumps(json_string)
            json.dump(json_string, info_file)
        # client.send_message(entity=log_chat,
        #                     message=f'Min message id: {MIN_MSG_ID}, {messages[0].message}\n')
        # print(f'Min message id: {MIN_MSG_ID}, {messages[0].message}\n')
        detect_relevantinfo(messages, KEYWORDS)

    print(f'Sleeping for {SLEEP_MINUTES} minutes\n')
Exemple #27
0
client.start()
'''
ent = client.get_messages("@realoriginalferrari");

print(ent[0].id)
print(ent[0].message)

client.send_message('cricket_project', ent[0].message);
'''

current_id = 0
while (True):
    sleep(1)
    try:
        ent = client.get_messages("@realoriginalferrari")
        msg_id = ent[0].id
        msg_content = ent[0].message
        editted = (ent[0].edit_date == None)
        lst = [
            '%', 'Ferrari', 'Offer', 'Bookie', 'Widraw', 'Joinchat', 'http',
            'Book', 'Ahuja', 'Join', 'Offer', 'Guarantee', 'W.me', 'Withdraw',
            'Guarantee', 'Christmas', 'Minimum', 'Id', 'Try', 'Fake'
        ]

        matched = 0
        for l in lst:
            if (l.lower() in msg_content.lower()):
                matched = 1

        if (current_id != msg_id):
Exemple #28
0
from telethon import TelegramClient
from telethon import events

import asyncio
api_id = 3409046
api_hash = '48ae9fbdf79edda291e1fa5796fc4665'
#phone_number = '+528132341246'
channel = '@pruebastienda'
################################################
client = TelegramClient('sessionname', api_id, api_hash)
#client.connect()
client.start()
#d=client.get_dialogs()
#p=client.get_participants(channel)
m = client.get_messages(channel, 100)
print(m)
Exemple #29
0
class RunChromeTests():
    def testMethod(self):
        caps = {'browserName': 'chrome'}
        driver = webdriver.Remote(
            command_executor=f'http://localhost:4444/wd/hub',
            desired_capabilities=caps)
        driver.maximize_window()
        driver.get(url_rec)
        time.sleep(waitin + 10)
        driver.close()
        driver.quit()


print('start')
while True:
    msgs = client.get_messages(tegmo, limit=1)
    for mes in msgs:
        if re.search(r'\bseconds to get your reward\b', mes.message):
            print("Найдено reward")
            str_a = str(mes.message)
            zz = str_a.replace('You must stay on the site for', '')
            qq = zz.replace('seconds to get your reward.', '')
            waitin = int(qq)
            print("Ждать придется: ", waitin)
            client.send_message('ZEC Click Bot', "/visit")
            time.sleep(3)
            msgs2 = client.get_messages(tegmo, limit=1)
            for mes2 in msgs2:
                button_data = mes2.reply_markup.rows[1].buttons[1].data
                message_id = mes2.id
Exemple #30
0
    client.send_message('Litecoin_click_bot', "/balance")
    time.sleep(2)
    messages = client.get_messages('Litecoin_click_bot', limit=1)
    for mes in messages:
        str_balance = str(mes.message)
        balance = (str_balance.replace('Available balance: ',
                                       '')).replace(' LTC', '')
    client.send_message('Litecoin_click_bot', "/visit")
    if (float(balance) >= 0.0004):
        print('Balance:' + balance + ' LTC. Time to export money')
    else:
        print('Balance:' + balance + ' LTC. more farm!')


while True:
    msgs = client.get_messages(tegmo, limit=1)

    for mes in msgs:
        if re.search(r'\bseconds to get your reward\b', mes.message):
            print("Найдено reward")
            str_response = str(mes.message)
            timer = (str_response.replace('You must stay on the site for',
                                          '')).replace(
                                              'seconds to get your reward.',
                                              '')
            waitin = int(timer)
            print("Ждать придется: ", waitin)
            client.send_message('Litecoin_click_bot', "/visit")
            time.sleep(3)
            msgs2 = client.get_messages(tegmo, limit=1)
            for mes2 in msgs2: