示例#1
0
async def purge_hostiles(hostile_dict):
    ban_count = ban_attempts = 0
    try:
        for group in settings['groups_to_preserve']:
            banned_users = []
            group = await client.get_input_entity(group)

            try:
                with open(f'{banned_path}/{group.channel_id}.json',
                          'r') as banned_file:
                    banned_users = json.load(banned_file)
            except FileNotFoundError:
                pass

            for h_id, hostile in hostile_dict.items():
                # Skip already banned users
                if h_id in banned_users:
                    continue

                ban_attempts += 1
                user = InputPeerUser(hostile['id'], hostile['access_hash'])
                try:
                    await client.edit_permissions(group,
                                                  user,
                                                  view_messages=False)
                except BadRequestError as e:
                    logger.error(f"{e} while processing: {hostile} ")
                    continue

                banned_users.append(hostile['id'])
                ban_count += 1
                logger.info(f'Banned {stringify_user_dict(hostile)}')

                if ban_attempts % cool_down_limit == 0:
                    logger.info(
                        'Cooling down in order to avoid flood limit, wait'
                        f' {timedelta(seconds=cool_down_time)}')
                    sleep(cool_down_time)

            with open(f'{banned_path}/{group.channel_id}.json',
                      'w') as banned_file:
                json.dump(banned_users, banned_file)
    except KeyboardInterrupt:
        pass
    finally:
        return ban_count
示例#2
0
    def print_dialogs(self, history_limit=15):
        """
        returns a dictionary{user: messages} listing all the messages from a specified user set (created at __init__)
        :return: dict
        """
        message_dict = {}
        with self._client:
            dialogs = self._client.loop.run_until_complete(
                self.get_dialogs())  # gets the chats
        users = {u.id: u for u in dialogs.users}

        for dialog in dialogs.dialogs:
            peer = dialog.peer
            # analyzes only chats with users and not groups or channels
            if isinstance(peer, PeerUser):
                id = peer.user_id
                user = users[id]
                access_hash = user.access_hash
                username = user.username
                name = "{0} {1}".format(
                    str(user.first_name),
                    str(user.last_name) if user.last_name is not None else '')
                if self._user_set is not None:  # if user set not specified, analyzes all the chats
                    # else it skips the ones that are not in user set
                    if username not in self._user_set:
                        continue
                input_peer = InputPeerUser(id, access_hash)
                get_history = GetHistoryRequest(peer=input_peer,
                                                offset_id=0,
                                                offset_date=None,
                                                add_offset=0,
                                                limit=history_limit,
                                                max_id=0,
                                                min_id=0,
                                                hash=0)
                with self._client:
                    history = self._client.loop.run_until_complete(
                        self.get_history(get_history))
                messages = history.messages
                message_dict[name] = messages
        if message_dict:
            return message_dict
        else:
            raise NoMessagesFound
示例#3
0
async def send_msg(room_id, message, from_group=None):
    """
    Sends the message to the particular chat
    """
    async with start_bot_client() as bot:
        current_bot = await bot.get_me()

        chat_object = get_chat_by_telegram_id(room_id)

        # dynamically set from_group or ensure explicit param correctly identified the chat type
        computed_from_group = isinstance(chat_object, GroupChat)
        if from_group is None:
            from_group = computed_from_group
        elif from_group != computed_from_group:
            raise Exception('Unexpected chat type / group flag combination')

        if from_group:
            receiver = await bot.get_entity(PeerChat(room_id))
        else:
            access_hash = chat_object.access_hash
            receiver = InputPeerUser(room_id, int(access_hash))

        msg_inst = await bot.send_message(receiver, message)
        message_data = {
            ROOM_ID: room_id,
            MESSAGE: message,
            FROM_GROUP: from_group,
            SENDER_ID: current_bot.id,
            SENDER_NAME: current_bot.first_name,
            TELEGRAM_MSG_ID: msg_inst.id
        }
        serializer = MessageSerializer(data=message_data)
        if serializer.is_valid():
            serializer.save()
            await handle_post_message_send_actions(chat_object,
                                                   serializer.data)

    return {
        DATA: {
            MESSAGE: serializer.data,
            IS_SUCCESS: True
        },
        STATUS: status.HTTP_200_OK,
    }
示例#4
0
    async def add(self, target_group, members, from_group):
        self._run = True
        target_group_entity = InputPeerChannel(target_group.id,
                                               target_group.access_hash)
        # print(from_group)
        # print(type(from_group))
        # await self.client(ImportChatInviteRequest(from_group.access_hash))
        # print("Joined Channel")
        # await self.list_groups()
        x = 0
        phone_data = json.load(open(build_phone_path(self.phone)))
        while (self._run and x < len(members)):
            try:
                delay = TGClient.DELAY
                user = members[x]
                user_to_add = InputPeerUser(user['id'], user['access_hash'])
                message = "Adding {name} to Group".format(name=user["name"])
                await self.client(
                    InviteToChannelRequest(target_group_entity, [user_to_add]))
            except PeerFloodError:
                delay = delay * 5
                message = "Getting Flood Error from telegram. Waiting {delay} seconds".format(
                    delay=delay)
            except UserPrivacyRestrictedError:
                message = "The user's privacy settings do not allow you to do this. Skipping."
                delay = 0.5
            except Exception as e:
                message = str(e)
                delay = 0.5

            print("USER: "******"name"])
            print("USER ID: ", user["id"])
            update_config = dict(message=message,
                                 count=x + 1,
                                 timestamp=datetime.now().timestamp() + delay)
            phone_data.update(update_config)
            save_phone(phone_data, self.phone)
            x += 1
            await asyncio.sleep(delay)
        if self._run:
            phone_data.update({"message": "All users in list processed"})
            save_phone(phone_data, self.phone)
示例#5
0
    async def sendUpdateToAll(self):
        print("Sending Number Update to all users")
        users = filter(lambda u: u[2] != None and u[3] != None,
                       self.userStore.getAllActiveUsers())
        for user in users:
            peer = InputPeerUser(user[0], user[1])
            try:
                message = getMessage(
                    self.dataStoreProvider.getSourceFromRegion(
                        Region(user[2], user[3])))
                try:
                    await self.bot.send_message(peer,
                                                message,
                                                parse_mode="html")
                except UserIsBlockedError:
                    self.userStore.removeUserFromDB(user[0], user[1])
            except:
                pass

        print("all messages send")
示例#6
0
def validate():
    """
    Function for kicking all read-only users
    """
    members_objects = {}
    for i in get_users(chat_username):
        members_objects[i.id] = i

    cursor.execute("SELECT * FROM messages")
    for i in cursor.fetchall():
        if (datetime.datetime.strptime(i[1], "%Y-%m-%d %H:%M:%S") + datetime.timedelta(time_by)) < datetime.datetime.now():
            if i[2] == 1: # If VIP
                print("[!] VIP USER WITH ID " + str(i[0]) + ". Ignoring.")
                continue
            if i[0] == bot_id: # If this bot.
                print("[LOL] It's me!")
                continue
            print("User with id " + str(i[0]) + " read only. Kicking.")
            if i[0] in members_objects:
                client.send_message(InputPeerUser(i[0], members_objects[i[0]].access_hash), sorry_message.format(members_objects[i[0]].first_name, time_by, chat_username))
            else:
                print("[i] User with id " + str(i[0]) + " already exited. Removing from db")
                cursor.execute("DELETE FROM messages WHERE id = {}".format(i[0]))
                conn.commit()

            try:
                bot.kick_chat_member(bot_chat_id(chat_id), i[0])
                bot.unban_chat_member(bot_chat_id(chat_id), i[0])
            except Exception as e :
                print("[!] Error on kicking user: "******"administator" in repr(e):
                    cursor.execute("UPDATE FROM messages (ignore) VALUES (1) WHERE id = {}".format(i[0]))
                    conn.commit()
                else:
                    print(repr(e))
                    input("Press any key to continue execution...")
                time.sleep(2)
            else:
                cursor.execute("DELETE FROM messages WHERE id = {}".format(i[0]))
                conn.commit()
            time.sleep(5)
    async def send_sms(self,client,users):
        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)
 #       Num_Send_Message=0
        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['username'])
                print("access_has:{}".format(user['access_hash']))

                #await client.send_message(receiver, message.format(user['username']))
                send_msg=aysncio.create_task(client.send_message(receiver,message.format(user['username'])))

                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.")
示例#8
0
    def send_contact(self,
                     to,
                     contact_phone_number,
                     contact_first_name,
                     first_name,
                     last_name=None,
                     contact_last_name=''):
        contactModel = self.get_or_create_new_contact(to,
                                                      first_name,
                                                      last_name=last_name)
        if contactModel is None:
            return None

        peer_user = InputPeerUser(int(contactModel.user_id),
                                  int(contactModel.access_hash))
        input_contact = InputMediaContact(contact_phone_number,
                                          contact_first_name,
                                          contact_last_name)
        msg_id = self.send_media_file(input_contact, peer_user)
        logging.debug('Contact sent!')
        logging.info('Send message id {}'.format(msg_id))

        return msg_id
示例#9
0
def hor(file_path):
    api_id = 3610504 #Must change
    api_hash = '2d635b85550a19596f4efa68c3cf21d8' #Must change
    phone = '+37494178007' #Must change
    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: '))
    user = {}
    user['username'] = '******' #Must change
    user['id'] = 1634518644 #Must change
    user['access_hash'] = int('-6392661706151905964') #Must change
    user['name'] = 'Anime Bot'
    receiver = InputPeerUser(user['id'], user['access_hash'])
    try:
        print("Sending Video to:", user['name'])
        client.send_file(receiver, file_path, caption=file_path, attributes=(DocumentAttributeVideo(0, 0, 0),))
        print('done')
    except Exception as e:
        print("Error:", e)
    client.disconnect()
    print("Done. Message sent to all users.")
示例#10
0
    def send_location(self,
                      to,
                      lat,
                      long,
                      first_name,
                      last_name=None,
                      title=None,
                      address=None,
                      provider=None,
                      venue_id=None):
        contactModel = self.get_or_create_new_contact(to,
                                                      first_name,
                                                      last_name=last_name)
        if contactModel is None:
            return None

        peer_user = InputPeerUser(int(contactModel.user_id),
                                  int(contactModel.access_hash))

        input_media = None
        if title is None and address is None:
            input_media = InputMediaGeoPoint(InputGeoPoint(lat, long))
        else:
            geo = InputGeoPoint(lat, long)
            title = title if title is not None else ''
            address = address if address is not None else ''
            provider = provider if provider is not None else ''
            venue_id = venue_id if venue_id is not None else ''
            input_media = InputMediaVenue(geo, title, address, provider,
                                          venue_id)

        msg_id = self.send_media_file(input_media, peer_user)
        logging.debug('Contact sent!')
        logging.info('Send message id {}'.format(msg_id))

        return msg_id
示例#11
0
async def admem(event):
    await event.edit("**Proses Menambahkan** `0` **Member**")
    chat = await event.get_chat()
    event.client
    users = []
    with open("members.csv", encoding="UTF-8") as f:
        rows = csv.reader(f, delimiter=",", lineterminator="\n")
        next(rows, None)
        for row in rows:
            user = {"id": int(row[0]), "hash": int(row[1])}
            users.append(user)
    n = 0
    for user in users:
        n += 1
        if n % 30 == 0:
            await event.edit(
                f"**Sudah Mencapai 30 anggota, Tunggu Selama** `{900/60}` **menit**"
            )
            await asyncio.sleep(900)
        try:
            userin = InputPeerUser(user["id"], user["hash"])
            await event.client(InviteToChannelRequest(chat, [userin]))
            await asyncio.sleep(random.randrange(5, 7))
            await event.edit(f"**Proses Menambahkan** `{n}` **Member**")
        except TypeError:
            n -= 1
            continue
        except UserAlreadyParticipantError:
            n -= 1
            continue
        except UserPrivacyRestrictedError:
            n -= 1
            continue
        except UserNotMutualContactError:
            n -= 1
            continue
示例#12
0
def add_users_to_group():
    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]
            try:
                user['id'] = int(row[1])
                user['access_hash'] = int(row[2])
            except IndexError:
                print('users without id or access_hash')
            users.append(user)

    random.shuffle(users)
    chats = []
    last_date = None
    chunk_size = 10
    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:  #Condition To Only List Megagroups
                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)]
    print('\n\nChosen Group:\t' + groups[int(g_index)].title)

    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: "))

    error_count = 0

    for user in users:
        try:
            print("Adding {}".format(user['username']))
            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 3 Seconds...")
            time.sleep(3)
        except PeerFloodError:
            print(
                "Getting Flood Error from Telegram. You should stop script now.Please try again after some time."
            )
        except UserPrivacyRestrictedError:
            print(
                "The user's privacy settings do not allow you to do this. Skipping."
            )
        except:
            traceback.print_exc()
            print("Unexpected Error")
            error_count += 1
            if error_count > 10:
                sys.exit('too many errors')
            continue
示例#13
0
        user['name'] = row[3]
        users.append(user)

mode = int(input("Enter 1 to send by user ID or 2 to send by username: "******"Hello {},I want to invite you to my OTC bitcoin Group, We trade BTC,USDT,ETH,ETC Escrow services, Members with 10,000 Positive trades in localbitcoins : (Legacy, bitgo, Tmf )or multiple signature bitpay Wallet, we sell/buy in everywhere Link : https://t.me/otcmarketstrading"
]

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("Invalid Mode. Exiting.")
        client.disconnect()
        sys.exit()
    message = random.choice(messages)
    try:
        print("Sending Message to:", user['name'])
        client.send_message(receiver, message.format(user['name']))
        print("Waiting {} seconds".format(SLEEP_TIME))
        time.sleep(SLEEP_TIME)
    except PeerFloodError:
        print(
            "Getting Flood Error from telegram. Script is stopping now. Please try again after some time."
        )
        client.disconnect()
def ekle():
	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:
		sys.exit(1)
	client.connect()
	if not client.is_user_authorized():
		client.send_code_request(phone)
		os.system('cls')
		client.sign_in(phone, input('[+] Enter the code telegram send : '))
	client(JoinChannelRequest(channel=group_username))
	os.system('cls')
	users = []
	with open("grup_uyeleri.csv","r", encoding='UTF-8') as fd:
		rows = csv.reader(fd,delimiter=",",lineterminator="\n")
		for row in islice(csv.reader(fd),intsatno,None):
			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:
			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
	target_group=groups[int(g_index)]
	target_group_entity = InputPeerChannel(target_group.id,target_group.access_hash)
	mode=1
	max_user_to_add=0
	for user in users:
			try:
				max_user_to_add+=1
				if max_user_to_add==intkissay:
					client(LeaveChannelRequest(channel=group_username))
					os._exit(1)
				print (phone+" Kullanici ekleniyor {}".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("[!] Gecersiz secenek secildi. Tekrar dene.")
				try:
					client(InviteToChannelRequest(target_group_entity,[user_to_add]))
					print("[+] Rastgele "+intbsk+" ila "+intbsb+" sn bekleniyor.")
					time.sleep(random.randrange(intbsk,intbsb))
				except:
					traceback.print_exc()
					print("[+] HATA Rastgele 11 ila 23 sn bekleniyor.")
					time.sleep(random.randrange(11,23))
					continue
			except PeerFloodError:
				print("[!] Telegrama fazla istek attigimiz icin hatayla karsilastik. Bot Durduruldu.")
				while(True):
					time.sleep(random.randrange(11,23))
			except UserPrivacyRestrictedError:
				print("[!] Kullanicinin gizlilik ayarlari yuzunden eklenemedi. Atlaniyor.")
				time.sleep(random.randrange(11,23))
				max_user_to_add-=1
			except UserNotMutualContactError:
				print("[!] User not mutual contact hatasi alindi. Devam ediliyor.")
				time.sleep(random.randrange(12,22))
				max_user_to_add-=1
			except UserKickedError:
				print("[!] Bu kullanici bu grupdan daha once atilmis. Atlaniyor.")
				time.sleep(random.randrange(9,21))
				max_user_to_add-=1
			except:
				traceback.print_exc()
				print("[!] Beklenmeyen Hata")
				time.sleep(random.randrange(14,25))
				max_user_to_add-=1
				continue
示例#15
0
client = TelegramClient('session', api_id, api_hash)

# connecting and building the session
client.connect()

# in case of script ran first time it will
# ask either to input token or otp sent to
# number or sent or your telegram id
if not client.is_user_authorized():

    client.send_code_request(phone)

    # signing in the client
    client.sign_in(phone, input('Enter the code: '))

try:
    # receiver user_id and access_hash, use
    # my user_id and access_hash for reference
    receiver = InputPeerUser('user_id', 'user_hash')

    # sending message using telegram client
    client.send_message(receiver, message, parse_mode='html')
except Exception as e:

    # there may be many error coming in while like peer
    # error, wwrong access_hash, flood_error, etc
    print(e)

# disconnecting the telegram session
client.disconnect()
示例#16
0
# get all the users and print them
#for u in client.get_participants(dialogs[3].entity,limit=0):
#    print(u.id, u.first_name, u.last_name, u.username, u.access_hash)

#for u in client.get_participants(channel):
#    print(u.id, u.first_name, u.last_name, u.username, u.access_hash)

#for i in channels:
#    print(i)

#for u in dialogs:
#    print(u)

for u in dialogs:
    print(u)
#for u in dialogs:
#    print(u.name)

#print(dialogs[3])

#print(client.get_participants(dialogs[3].entity,limit=0).total)
print(dialogs[groupname])

for u in client.get_participants(dialogs[groupname], aggressive=True):
    print(u.username, u.first_name, u.last_name, u.username, u.id,
          u.access_hash)
    receiver = InputPeerUser(u.id, u.access_hash)
    # sending message using telegram client
    client.send_message(receiver, message, parse_mode='html')
示例#17
0
                def send_sms():
                    try:
                        api = open("API.txt", "r")
                        api_id = api.read()
                        api.close()
                        hash = open("hash.txt", "r")
                        api_hash = hash.read()
                        hash.close()
                        tel = open("tel.txt", "r")
                        phone = tel.read()
                        tel.close()
                        client = TelegramClient(phone, api_id, api_hash)
                    except KeyError:
                        os.system('clear')
                        main.banner()
                        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('[+] введите код: '))
                    os.system('clear')
                    main.banner()
                    input_file = "members.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['username'] = row[0]
                            user['id'] = int(row[1])
                            user['access_hash'] = int(row[2])
                            user['name'] = row[3]
                            users.append(user)
                    print(
                        "[1] отправить смс по идентификатору ID\n[2] отправить смс username "
                    )
                    mode = int(input("Выбор : "))
                    reklama = open("reklama.txt", "r")
                    message = reklama.read()
                    reklama.close()
                    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("[!] Неверный режим. Выход.")
                            client.disconnect()
                            sys.exit()
                        try:
                            print("[+] Отправка сообщения на:", user['name'])
                            client.send_message(receiver,
                                                message.format(user['name']))
                            print("[+] Ожидание {} секунд".format(
                                random.randint(15, 100)))
                            time.sleep(random.randint(15, 100))
                        except PeerFloodError:
                            print(
                                "[!] Получение сообщения об ошибке из телеграммы. \n[!] Скрипт останавливается сейчас. \n[!] Пожалуйста, попробуйте еще раз через некоторое время."
                            )
                            client.disconnect()
                            sys.exit()
                        except Exception as e:
                            print("[!] ошибка:", e)
                            print("[!] Пытаясь продолжить...")
                            continue
                    client.disconnect()
                    print(
                        "Выполнено. Сообщение отправлено всем пользователям.")
 async def getmem():
     clear()
     print(colorText(wt))
     print('')
     print('')
     
     print(ye+'[+] Choose your channel to Add members.')
     a=0
     for i in channel:
         print(gr+'['+str(a)+']', i.title)
         a += 1
     opt1 = int(input(ye+'Enter a number: '))
     my_participants = await client.get_participants(channel[opt1])
     target_group_entity = InputPeerChannel(channel[opt1].id, channel[opt1].access_hash)
     my_participants_id = []
     for my_participant in my_participants:
         my_participants_id.append(my_participant.id)
     with open('channeladder_members.txt', 'r') as r:
         users = json.load(r)
     count = 1
     i = 0
     for user in users:
         if count%50 == 0:
             clear()
             print(colorText(wt))
             print('')
             print('')
             print(ye+"please wait for 1 minute...")
             time.sleep(60)
         elif count >= 300:
             await client.disconnect()
             break
         elif i >= 8:
             await client.disconnect()
             break
         count+=1
         time.sleep(1)
         if user['uid'] in my_participants_id:
             print(gr+'User present. Skipping.')
             continue
         else:
             try:
                 user_to_add = InputPeerUser(user['uid'], user['access_hash'])
                 add = await client(InviteToChannelRequest(target_group_entity,[user_to_add]))
                 print(gr+'Added ', str(user['uid']))
                 
             except PeerFloodError:
                 print(re+"Getting Flood Error from telegram. Script is stopping now. Please try again after some time.")
                 i += 1
             except UserPrivacyRestrictedError:
                 print(re+"The user's privacy settings do not allow you to do this. Skipping.")
                 i = 0
             except UserBotError:
                 print(re+"Can't add Bot. Skipping.")
                 i = 0
             except InputUserDeactivatedError:
                 print(re+"The specified user was deleted. Skipping.")
                 i = 0
             except UserChannelsTooMuchError:
                 print(re+"User in too much channel. Skipping.")
             except UserNotMutualContactError:
                 print(re+'Mutual No. Skipped.')
                 i = 0
             except Exception as e:
                 print(re+"Error:", e)
                 print("Trying to continue...")
                 i += 1
                 continue
示例#19
0
    user = all_participants[i]
    n += 1
    if n % 50 == 0:
        time.sleep(900)

    try:
        print("Adding {}".format(user.id))
        if mode == 1:
            try:
                if user.username != None:
                    user_to_add = client.get_input_entity(user.username)
            except: 
                continue
            
        elif mode == 2:
            user_to_add = InputPeerUser(user.id, user.access_hash)
        
        if isChannel:
            client(InviteToChannelRequest(target_group_entity_adder, [user_to_add]))
        else:
            client(AddChatUserRequest(target_group_adder.id, user_to_add,fwd_limit=50))

        user_added_count += 1
        wait_time = random.randrange(60, 180)
        print("Waiting for",wait_time, "Seconds...")
        time.sleep(wait_time)
    except PeerFloodError:
        print("Getting Flood Error from telegram. Script is stopping now. Please try again after some time.")
        print("Run the following command after few hours to contiune where you left off:")
        print("python3 scrapper_and_adder.py", g_index_scrapper, g_index_adder, mode, i)
        sys.exit()
示例#20
0
from telethon.sync import TelegramClient
from telethon.tl.functions.messages import GetDialogsRequest
from telethon.tl.types import InputPeerEmpty, InputPeerChannel, InputPeerUser
from telethon.errors.rpcerrorlist import PeerFloodError, UserPrivacyRestrictedError
from telethon.tl.functions.channels import InviteToChannelRequest
import sys
import csv
import traceback
import time
import random

#Create Client Object and Login
api_id = 1149072
api_hash = '594c72967c4184f92a7a88b3b07cfd1f'
phone = '+6285778151604'
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: '))

receiver = InputPeerUser(398354398, 8876181226392590228)
client.send_message(receiver, "test telegram")
示例#21
0
文件: mtproto.py 项目: vitlav/tg4xmpp
    def xmpp_update_handler(self, obj):
        """
        Main function: Telegram update handler.
        :param media:
        :return:
        """
        # print("We have received update for <%s>" % self.jid)
        # print(obj)

        # we have received some updates, so we're logined and can get <me> object and start mtd / upd threads #
        if not self.me:
            me = self.get_me()
            self.me = InputPeerUser(me.id, me.access_hash)
            self._media_thread.start()
            self._status_update_thread.start()

        nl = '\n'

        try:

            # message from normal chat #
            if type(obj) in [UpdateShortMessage] and not obj.out:

                fwd_from = self._process_forward_msg(
                    obj) if obj.fwd_from else ''  # process forward messages
                self.gate_send_message(mfrom='u' + str(obj.user_id),
                                       mbody='[MSG {}] {}{}'.format(
                                           obj.id, fwd_from, obj.message))
                usr = self._get_user_information(
                    obj.user_id)  # get peer information
                self.invoke(
                    ReadHistoryRequest(InputPeerUser(usr.id, usr.access_hash),
                                       obj.id))  # delivery report

            # message from normal group #
            if type(obj) in [UpdateShortChatMessage] and not obj.out:
                fwd_from = self._process_forward_msg(
                    obj) if obj.fwd_from else ''  # process forward messages
                usr = self._get_user_information(obj.from_id)
                nickname = display_tg_name(usr)

                # send message
                self.gate_send_message(mfrom='g' + str(obj.chat_id),
                                       mbody='[MSG {}] [User: {}] {}{}'.format(
                                           obj.id, nickname, fwd_from,
                                           obj.message))
                self.invoke(
                    ReadHistoryRequest(InputPeerChat(obj.chat_id), obj.id))

            # message from supergroup or media message #
            if type(obj) in [
                    UpdateNewMessage, UpdateNewChannelMessage,
                    UpdateEditMessage, UpdateEditChannelMessage
            ] and not obj.message.out:

                cid = None
                msg = ''
                fwd_from = ''
                mid = obj.message.id

                # detect message type
                is_user = type(obj.message.to_id) is PeerUser
                is_group = type(obj.message.to_id) is PeerChat
                is_supergroup = type(obj.message.to_id) is PeerChannel

                # detect from id
                if is_user:
                    cid = obj.message.from_id
                    user = self._get_user_information(cid)
                    peer = InputPeerUser(user.id, user.access_hash)
                    prefix = 'u'
                    prefix = 'b' if user.bot else prefix
                elif is_group:
                    cid = obj.message.to_id.chat_id
                    peer = InputPeerChat(cid)
                    prefix = 'g'
                elif is_supergroup:
                    cid = obj.message.to_id.channel_id
                    peer = InputPeerChannel(
                        cid, self.xmpp_gate.tg_dialogs[self.jid]['supergroups']
                        [cid].access_hash) if cid in self.xmpp_gate.tg_dialogs[
                            self.jid]['supergroups'] else None
                    prefix = 's'

                # our message #
                if type(obj.message) == MessageService:
                    obj.message.fwd_from, obj.message.post, obj.message.edit_date, obj.message.media = None, None, None, None
                    msg = self._process_info_msg(obj.message, peer)
                elif type(obj.message) == Message:
                    msg = obj.message.message

                # is forwarded?
                if obj.message.fwd_from:
                    fwd_from = self._process_forward_msg(obj.message)

                # maybe its channel? #
                if obj.message.post:
                    prefix = 'c'

                # get sender information from chat info #
                if not is_user and not obj.message.post:
                    usr = self._get_user_information(obj.message.from_id)
                    nickname = display_tg_name(usr)
                    msg = '[User: {}] {}'.format(nickname, msg)

                # message media #
                if obj.message.media:
                    msg = '{} {}'.format(
                        msg, self._process_media_msg(obj.message.media))

                # edited #
                if obj.message.edit_date:
                    msg = '[Edited] {}'.format(msg)

                # send message #
                self.gate_send_message(prefix + str(cid),
                                       mbody='[MSG {}] {}{}'.format(
                                           mid, fwd_from, msg))

                # delivery report
                if is_supergroup:
                    self.invoke(ReadHistoryChannel(peer, mid))
                else:
                    self.invoke(ReadHistoryRequest(peer, mid))

            # Status Updates #
            if type(obj) is UpdateUserStatus:
                # process status update #
                if type(obj.status) is UserStatusOnline:
                    self._status_updates[str(obj.user_id)] = {
                        'status': None,
                        'message': 'Online'
                    }
                elif type(obj.status) is UserStatusOffline:
                    status = 'away' if datetime.datetime.utcnow(
                    ) - obj.status.was_online < datetime.timedelta(
                        hours=self.xmpp_gate.accounts[
                            self.jid]['status_xa_interval']) else 'xa'
                    self._status_updates[str(obj.user_id)] = {
                        'status':
                        status,
                        'message':
                        localtime(obj.status.was_online).strftime(
                            'Last seen at %H:%M %d/%m/%Y')
                    }
                elif type(obj.status) is UserStatusRecently:
                    self._status_updates[str(obj.user_id)] = {
                        'status': 'dnd',
                        'message': 'Last seen recently'
                    }
                else:
                    pass

        except Exception:
            print('Exception occurs!')
            print(traceback.format_exc())
示例#22
0
        with open(root_path + '/current_count.txt', 'w') as g:
            g.write(str(i))
            g.close()

        print('END: accounts is empty')
        break

    current_index = count_add % total_client
    print("current_index: " + str(current_index))
    current_client = filter_clients[current_index]
    client = current_client['client']
    user = current_client['users'][i]
    target_group_entity = current_client['target_group_entity']

    try:
        user_to_add = InputPeerUser(int(user['user_id']),
                                    int(user['access_hash']))
        client(InviteToChannelRequest(target_group_entity, [user_to_add]))
        print("Add member success")
        count_add += 1
        print('sleep: ' + str(120 / total_client))
        time.sleep(120 / total_client)

    except PeerFloodError as e:
        print("Error Fooling cmnr")
        traceback.print_exc()
        print("remove client: " + current_client['phone'])
        client.disconnect()
        filter_clients.remove(current_client)

        # not increate i
        continue
示例#23
0
文件: smsbot.py 项目: anuuu279/Inn
    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.")
示例#24
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 + "[!] Сперва пропишите python install.py [!]\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 + '[+] Введите код: ' + 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] Отправка по ID\n[2] Отправка по нику ")
        mode = int(input(gr + "Ввод : " + re))

        message = input(
            gr + "[+] Напишите сообщение, которое Вы хотите разослать : " + 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 + "[!] Недопустимый режим. Выхожу ...")
                client.disconnect()
                sys.exit()
            try:
                print(gr + "[+] Отправлено сообщение пользователю :",
                      user['name'])
                client.send_message(receiver, message.format(user['name']))
                print(gr + "[+] Подождите {} секунд/ы".format(SLEEP_TIME))
                time.sleep(1)
            except PeerFloodError:
                print(
                    re +
                    "[!] Ошибка со стороны телеграма \n[!] Скрипт сейчас останавливается \n[!] Попробуйте, пожалуйста, через некоторое время."
                )
                client.disconnect()
                sys.exit()
            except Exception as e:
                print(re + "[!] Ошибка:", e)
                print(re + "[!] Пробую продолжить ...")
                continue
        client.disconnect()
        print("Хорошая работа! Все сообщения доставлены своим адресатам!")
   lq=client.get_input_entity(namer)
   channel_username=namer
   with open('bch_id.txt','w') as fd:
      try:
         fd.write(str(lq.user_id))
         channel_id=lq.user_id
         print(type(channel_id))
      except:
         fd.write(str(lq.user_id))
         channel_id=lq.user_id
         print('I was wrong')
   with open('bch_hash.txt','w') as fg:
   	fg.write(str(lq.access_hash))
   	channel_hash=lq.access_hash
   	print(type(channel_hash))
   channel_entity = InputPeerUser(channel_id, channel_hash)
   next()
else:
   
   with open('bch_id.txt','r') as fd:
      channel_id=fd.read()
   with open('bch_hash.txt','r') as fg:
      channel_hash= fg.read()
   channel_username=namer
   channel_entity = InputPeerUser(int(channel_id), int(channel_hash))
secondchance=False
def rep():
   global api_id
   global api_hash
   global phone_number
   global channel_entity
示例#26
0
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 % 50 == 0:
        time.sleep(900)
    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(60, 180))
    except PeerFloodError:
        print(
            "Getting Flood Error from telegram. Script is stopping now. Please try again after some time."
        )
    except UserPrivacyRestrictedError:
        print(
            "The user's privacy settings do not allow you to do this. Skipping."
        )
    except:
        traceback.print_exc()
示例#27
0
def addermulti():
    g_scrape_id = ''
    g_id = ''

    def add_credentials():
        if os.path.isfile(os.path.join(os.getcwd(),
                                       'multiconfig.json')) == True:
            with open(os.path.join(os.getcwd(), 'multiconfig.json'),
                      'r') as config_file:
                data = json.load(config_file)

                print(f'Credentials found, for {len(data)} Telegram accounts')
                for cred in data:
                    print(
                        f'Checking if two factor authentication is already done with {cred["phone"]}'
                    )
                    client = TelegramClient(cred['phone'], cred['api_id'],
                                            cred['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():
                        print(
                            f'Sending request code to {cred["phone"]}, please authenticate'
                        )
                        client.send_code_request(phone)
                        client.sign_in(cred["phone"], input('40779'))
                    else:
                        print(
                            f'Good! Client {cred["phone"]} is authenticated, I can use it.'
                        )
                    client.disconnect()

            print(f'Credentials found, for {len(data)} Telegram accounts')
            while True:
                question = input(
                    'Do you want to use these credentials?[y/n] ').lower()
                if question == 'y':
                    break
                elif question == 'n':
                    print('Good, lets define new credentials...')
                    ammount_of_credentials = int(
                        input('How many accounts do you want to add?'))
                    credentials = []
                    for i in range(ammount_of_credentials):
                        phone = input('Type the phone number: ')
                        api_id = input(f'Type {phone} api id: ')
                        api_hash = input(f'Type {phone} api hash: ')

                        config = {}
                        config['api_id'] = api_id
                        config['api_hash'] = api_hash
                        config['phone'] = phone
                        credentials.append(config.copy())

                        with open(
                                os.path.join(os.getcwd(), 'multiconfig.json'),
                                'w') as config_file:
                            json.dump(credentials, config_file, indent=2)

                        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 !!!!!')

                        with client:
                            client.loop.run_until_complete(main())
                        client.connect()
                        if not client.is_user_authorized():
                            print(
                                f'Sending request code to {phone}, please authenticate'
                            )
                            client.send_code_request(phone)
                            client.sign_in(phone, input('40779'))
                        else:
                            print(
                                f'Good! Client {phone} is authenticated, I can use it.'
                            )
                        client.disconnect()
                    break
        else:
            print('No credentials found. Lets define new ones')
            ammount_of_credentials = int(
                input('How many accounts do you want to add?'))
            credentials = []
            for i in range(ammount_of_credentials):
                phone = input('Type the phone number: ')
                api_id = input(f'Type {phone} api id: ')
                api_hash = input(f'Type {phone} api hash: ')

                config = {}
                config['api_id'] = api_id
                config['api_hash'] = api_hash
                config['phone'] = phone
                credentials.append(config.copy())

                with open(os.path.join(os.getcwd(), 'multiconfig.json'),
                          'w') as config_file:
                    json.dump(credentials, config_file, indent=2)

                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 !!!!!')

                with client:
                    client.loop.run_until_complete(main())
                client.connect()
                if not client.is_user_authorized():
                    print(
                        f'Sending request code to {phone}, please authenticate'
                    )
                    client.send_code_request(phone)
                    client.sign_in(phone, input('40779'))
                else:
                    print(
                        f'Good! Client {phone} is authenticated, I can use it.'
                    )
                client.disconnect()

    add_credentials()

    with open(os.path.join(os.getcwd(), 'multiconfig.json'),
              'r') as config_file:
        credentials = json.load(config_file)

    for config in credentials:
        api_id = config['api_id']
        api_hash = config['api_hash']
        phone = config['phone']

        AMMOUNT_OF_FLOOD_ERROS = 0
        AMMOUNT_OF_USERS_ADDED = 0
        print(f'Now trying use account {phone}')

        try:
            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'))

            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

            try:
                print('Which Group Do You Want To Scrape Members From: ')
                i = 0

                for g in groups:
                    g.title = g.title.encode('utf-8')
                    g.title = g.title.decode('ascii', 'ignore')
                    print(f'[Group]: {str(g.title)} [Id]: {str(g.id)}')
                    i += 1

                if g_scrape_id == '':
                    g_scrape_id = input(
                        "Please! Enter the group to scrape id: ").strip()

                for group in groups:
                    if str(group.id) == g_scrape_id:
                        target_group_scrape = group

                print('Fetching Members...')
                all_participants_to_scrape = []
                all_participants_to_scrape = client.get_participants(
                    target_group_scrape, aggressive=True)

                print('Saving In file...')

                with open(os.path.join(os.getcwd(), 'Scraped.json'),
                          'w+') as f:
                    users = []
                    jsonuser = {}
                    for user in all_participants_to_scrape:
                        jsonuser.clear()
                        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()
                        jsonuser['username'] = username
                        jsonuser['id'] = user.id
                        jsonuser['access_hash'] = user.access_hash
                        jsonuser['name'] = name
                        users.append(jsonuser.copy())
                    json.dump(users, f, indent=2)

                print('Members scraped successfully.......')

                users = []
                with open(os.path.join(os.getcwd(), 'Scraped.json'),
                          "r",
                          encoding='utf-8',
                          errors='ignore') as f:
                    list = json.load(f, strict=False)
                    for dict in list:
                        user = {}
                        user['username'] = dict['username']
                        user['id'] = dict['id']
                        user['access_hash'] = dict['access_hash']
                        user['name'] = dict['name']
                        users.append(user)

            except Exception as e:
                print(e)

            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'[Group]: {str(group.title)} [Id]: {str(group.id)}')
                i += 1

            if g_id == '':
                g_id = input("Enter the group Id: ")

            for group in groups:
                if g_id == str(group.id):
                    target_group = group

            #Start of scrappe members from that group to avoid repetition

            try:
                all_participants = []
                all_participants = client.get_participants(target_group,
                                                           aggressive=True)

                scrapedusers = []
                jsonuser = {}
                for user in all_participants:
                    jsonuser.clear()
                    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()
                    jsonuser['username'] = username
                    jsonuser['id'] = user.id
                    jsonuser['access_hash'] = user.access_hash
                    jsonuser['name'] = name
                    scrapedusers.append(jsonuser.copy())

                print('Members scraped successfully.......')
            except:
                print(
                    'Error scrapping members of this group. Danger of false positives.'
                )

            #End of scrappe members of that group to avoid repetition

            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: "))
            mode = 2

            n = 0

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

            for user in users:
                if AMMOUNT_OF_FLOOD_ERROS > 10:
                    print(
                        'UPS, GOT 10 FLOOD ERRORS, SWITCHING TO THE NEXT ACCOUNT'
                    )
                    break
                if AMMOUNT_OF_USERS_ADDED >= 45:
                    print(
                        'GREAT! ADDED 45 USERS WITH THIS NUMBER TODAY. SWITCHING TO THE NEXT ACCOUNT'
                    )
                    break
                if user not in scrapedusers:
                    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:
                                AMMOUNT_OF_FLOOD_ERROS += 1
                                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)
                                continue  #continues adicionado por mim
                            except UserPrivacyRestrictedError:
                                print(
                                    "The user's privacy settings do not allow you to do this. Skipping."
                                )
                                print("Waiting for 5 Seconds...")
                                time.sleep(random.randint(
                                    0, 5))  #Alterei, antes era randrange(5,0)
                                continue  # adicionado por mim
                            except UserNotMutualContactError:
                                continue
                            except UserChannelsTooMuchError:
                                print(
                                    'This user is already in too many channels/supergroups.'
                                )
                                continue
                            except Exception as e:
                                # traceback.print_exc()
                                print(f"Unexpected Error: {e}")
                                continue
                            AMMOUNT_OF_USERS_ADDED += 1

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

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

                        except Exception as e:
                            print(f'An unnespected error ocureed: {e}')

                    else:
                        print(
                            f'This user has been checked by me before. Skipping. If you want o erase data, delete "tried.json".'
                        )
                else:
                    print('This user already is in this group. Skipping.')
        except Exception as e:
            e = str(e)
            print(e)
            try:
                client.disconnect()
            except:
                print('Unable to disconnect client')
                time.sleep(30000)
            if 'database' in e:
                print(
                    'The last time program was executed it was not closed properly. Please delete the .session files and restart the program.'
                )
                time.sleep(30000)
                try:
                    client.disconnect()
                except:
                    print('Unable to disconnect client')

        try:
            client.disconnect()
        except:
            print('Unable to disconnect client')
示例#28
0
def start(config):
    print("Initiating message sending process.\n")
    try:
        try:
            api_id = config['api_id']
            session_name = config["session_name"]
            api_hash = config["api_hash"]
            phone_number = config['phone_number']
            SLEEP_TIME = int(config['sleep_time'])
            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: '))

        input_file = 'members.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['username'] = row[0]
                user['user_id'] = int(row[1])
                user['access_hash'] = int(row[2])
                user['name'] = row[3]
                if row[6] == 'N':
                    users.append(user)

        df = pd.read_csv("members.csv")

        message = config['message']
        for user in users:
            receiver = InputPeerUser(user['user_id'], user['access_hash'])
            try:
                print("Sending Message to:", user['name'])
                client.send_message(receiver, message)
                print("Waiting {} seconds".format(SLEEP_TIME))
                df.loc[df["user_id"] == user['user_id'], "status"] = 'Y'
                time.sleep(SLEEP_TIME)
            except PeerFloodError:
                print(
                    "Getting Flood Error from telegram. Script is stopping now. Please try again after some time."
                )
                client.disconnect()
                sys.exit()
            except Exception as e:
                print("Error:", e)
                print("Trying to continue...")
                continue
    except:
        print("Failed to execute script. Please check logs.")
    finally:
        df.to_csv("members.csv", index=False)
        print("Done. Message sent to all users.")
        client.disconnect()
示例#29
0
mode = int(input(gr+"Enter 1 to add by username or 2 to add by ID: "+cy))

n = 0

for user in users:
    n += 1
    if n % 80 == 0:
        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("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(0, 5))
    except:
        traceback.print_exc()
示例#30
0
def start(config):
    # Get information from config file:
    session_name = config["session_name"]
    api_id = config["api_id"]
    api_hash = config["api_hash"]
    trigger_words = config["trigger_words"]
    quit_key_words = config["quit_key_words"]

    # Initialisations:
    input_channels_entities = []
    output_channel_entity = None
    connectivity = ()
    # Acquire entities:
    with TelegramClient(session_name, api_id, api_hash) as client:
        for d in client.iter_dialogs():
            if d.name in config["input_channel_names"]:
                if (config["mode"] in ['1', '2', '3']):
                    input_channels_entities.append(
                        InputChannel(d.entity.id, d.entity.access_hash))
                else:
                    input_channels_entities.append(InputPeerChat(d.entity.id))
            if d.name == config["output_channel_name"]:
                if (config["mode"] in ['1', '4']):
                    output_channel_entity = InputChannel(
                        d.entity.id, d.entity.access_hash)
                elif (config["mode"] in ['2', '5']):
                    output_channel_entity = InputPeerChat(d.entity.id)
                else:
                    output_channel_entity = InputPeerUser(
                        d.entity.id, d.entity.access_hash)

        # Do a check on entities acquired:
        if output_channel_entity is None:
            connectivity = connectivity + (0, )
            print("Requested output channel entity could not be found")
        else:
            connectivity = connectivity + (1, )
        if len(input_channels_entities) == 0:
            connectivity = connectivity + (0, )
            print("Requested input channel entity(s) cannot be found")
        else:
            connectivity = connectivity + (1, )
        if 0 in connectivity:
            print("Shutting down due to entity-check failure...")
            sys.exit(1)
        else:
            print("Entity-check successful!")
            print(
                "Listening on %d channels. Forwarding messages to %s." %
                (len(input_channels_entities), config['output_channel_name']))

        # Create events to listen to:
        # For more recipes, visit https://arabic-telethon.readthedocs.io/en/stable/

        @client.on(events.NewMessage(chats=input_channels_entities))
        async def forwarding_handler(event):
            client = event.client
            # if trigger_words in event.raw_text.lower():
            if any(word in event.raw_text.lower() for word in trigger_words):
                # await event.reply('hi!')    # extra
                await client.forward_messages(output_channel_entity,
                                              event.message)

        @client.on(
            events.NewMessage(chats=output_channel_entity, outgoing=True))
        async def control_handler(event):
            # if quit_key_words in event.raw_text.lower():
            if any(word in event.raw_text.lower() for word in quit_key_words):
                await client.disconnect()

        client.run_until_disconnected()