def eventHandlerCallback(update): msglog.debug('{}'.format(update)) if isinstance(update, UpdateShortMessage) and not update.out: user = client(GetUsersRequest([InputUser(update.user_id, 0)])) msglog.debug('{}'.format(user[0])) msglog.info('Recieved message from {}_{} ({}) user_id={}: {}'.format( user[0].first_name, user[0].last_name, user[0].phone, update.user_id, update.message)) client(ReadHistoryRequest(InputUser(update.user_id, 0), update.id))
def contact_del(): log.debug('{}'.format(request.form)) input_user = InputUser(int(request.form['userid']), 0) try: user = client(GetUsersRequest([input_user])) log.debug('{}'.format(user)) if user[0].photo: filename = 'app/contacts/static/tmp/{}.jpg'.format( user[0].photo.photo_id) if Path(filename).is_file(): log.info('Removing profile photo {}_{} to {}'.format( user[0].first_name, user[0].last_name, filename)) os.remove(filename) result = client(DeleteContactRequest(input_user)) log.debug('{}'.format(result)) session['error'] = 'Контакт {}_{} успешно удален.'.format( result.user.first_name, result.user.last_name) except Exception as e: session['error'] = 'Ошибка удаления контакта {}'.format(e) return redirect(url_for('contacts.contact_list'))
def invite_to_channel(self): """ This definition adding contact to group, do not use it without def_channel() and def_usernames(). You can invite to channel from 1 session max 15 people after that you are at risk. You can be banned because too many requests from 1 session. """ if self.flag_channel and self.flag_user: for i in range(len(self.usernames)): try: if self.usernames[i][0]: sleep(31) self.client( InviteToChannelRequest( InputChannel(self.channel.id, self.channel.access_hash), [ InputUser(self.usernames[i][0].id, self.usernames[i][0].access_hash) ])) print('Successfully added ' + str(self.usernames[i][0]) + ' to ' + str(self.channel)) print('Успешно добавлен ' + str(self.usernames[i][0]) + ' в ' + str(self.channel)) print('------------------------') sleep(5) except Exception as err: print(err) print('------------------------') else: print( 'You don\'t define channel and users to add, please try again' 'Вы не определили канал и/или ползователей')
def _parse_url(self, url: str, args: Dict[str, Any] ) -> Tuple[Optional[Type[TypeMessageEntity]], Optional[str]]: mention = self.mention_regex.match(url) if mention: mxid = mention.group(1) user = (pu.Puppet.get_by_mxid(mxid) or u.User.get_by_mxid(mxid, create=False)) if not user: return None, None if user.username: return MessageEntityMention, f"@{user.username}" elif user.tgid: args["user_id"] = InputUser(user.tgid, 0) return InputMessageEntityMentionName, user.displayname or None else: return None, None room = self.room_regex.match(url) if room: username = po.Portal.get_username_from_mx_alias(room.group(1)) portal = po.Portal.find_by_username(username) if portal and portal.username: return MessageEntityMention, f"@{portal.username}" if url.startswith("mailto:"): return MessageEntityEmail, url[len("mailto:"):] elif self.get_starttag_text() == url: return MessageEntityUrl, url else: args["url"] = url return MessageEntityTextUrl, None
def from_group_ten_first_persons(group, togroup): flag = True if group == '-': flag = False return flag elif togroup == '-': flag = False return flag users = client.get_participants(group) channel = client.get_entity(togroup) for i in range(10): try: contact = InputPhoneContact(client_id=user[i].id, phone=user[i].phone, first_name=user[i].first_name, last_name=user[i].last_name) result = client.invoke(ImportContactsRequest([contact])) client( InviteToChannelRequest( InputChannel(channel.id, channel.access_hash), [InputUser(users[i].id, users[i].access_hash)])) except errors.rpcerrorlist.UserPrivacyRestrictedError as err: print('>>>>0. UserPrivacyRestrictedError...') print(err) except errors.rpcerrorlist.ChatAdminRequiredError as err: print('>>>>1. ChatAdminRequiredError...') print(err) except errors.rpcerrorlist.ChatIdInvalidError as err: print('>>>>2. ChatIdInvalidError...') print(err) except errors.rpcerrorlist.InputUserDeactivatedError as err: print('>>>>3. InputUserDeactivatedError...') print(err) except errors.rpcerrorlist.PeerIdInvalidError as err: print('>>>>4. PeerIdInvalidError...') print(err) except errors.rpcerrorlist.UserAlreadyParticipantError as err: print('>>>>5. UserAlreadyParticipantError...') print(err) except errors.rpcerrorlist.UserIdInvalidError as err: print('>>>>6. UserIdInvalidError...') print(err) except errors.rpcerrorlist.UserNotMutualContactError as err: print('>>>>>7. UserNotMutualContactError...') print(err) except errors.rpcerrorlist.UsersTooMuchError as err: print('>>>>>8. UsersTooMuchError...') print(err) except errors.rpcerrorlist.PeerFloodError as err: print( '>>>>>9. PeerFloodError try again in 24 Hours...Yes, you in spam' ) print(err) return flag
async def token_listen(request: web.Request): print("Got token") access_token = request.rel_url.query['access_token'] user_id = int(request.rel_url.query['state']) user = await get_user(user_id) user.mosreg_token = access_token await user.push_changes() await bot.send_message( InputUser(user.user_id, user.access_hash), "✅Аккаунт привязан!✅\nОтправь /start чтобы " "открыть меню") return web.Response(status=200)
def _get_full_user(self, user_id): if user_id in GLOBAL_USERS_CACHE: return GLOBAL_USERS_CACHE['user_id'] try: response = self._client.invoke(GetFullUserRequest(InputUser(user_id, 0))) except Exception as e: return None print('Cannot get full user data for user', user_id) user = getattr(response, 'user', None) if user and getattr(user, 'id', None) == user_id: GLOBAL_USERS_CACHE['id'] = user return user return None
def replacer(match): puppet = pu.Puppet.find_by_displayname(match.group(2)) if puppet: offset = match.start() length = match.end() - offset if puppet.username: entity = MessageEntityMention(offset, length) text = f"@{puppet.username}" else: entity = InputMessageEntityMentionName(offset, length, user_id=InputUser(puppet.tgid, 0)) text = puppet.displayname entities.append(entity) return text return "".join(match.groups())
def set_admin(self, owner_client, sender, owner_channel): owner_client( EditAdminRequest(channel=owner_channel, user_id=InputUser(sender.id, sender.access_hash), admin_rights=ChannelAdminRights( change_info=True, post_messages=True, edit_messages=True, delete_messages=True, ban_users=True, invite_users=True, invite_link=True, pin_messages=True, add_admins=True, )))
async def find_bots(app, channel: str): with open('ids_db') as fp: CURRENT_USERS = fp.read().strip().split('\n') fp = open('ids_db', 'a') async for user in app.iter_participants(channel): print('pp') user_id, access_hash = user.id, user.access_hash add_user_to_base(fp, CURRENT_USERS, user_id, access_hash) input_user = InputUser(user_id, access_hash) full_user = await app(GetFullUserRequest(input_user)) about = full_user.about user_string = f'{user.first_name} {user.last_name} ({about})' if check_AL(user_string): yield user_id, user_string fp.close()
def add_users_2_channel_fun(user_group_id: int, tag_id: int): print('start add users 2 channel.') try: global id_add_users_2_channel user_group = db.session.query(UserGroup).filter( UserGroup.group_id == user_group_id).scalar() if user_group is None: print('user group is none.') else: inputChannel = InputChannel(channel_id=user_group.group_id, access_hash=user_group.access_hash) user_tag_infos = db.session.query(UserTAGInfo).filter( UserGroup.tag_id == tag_id).all() if user_tag_infos is None: print("user tag infos is none.") else: inputUsers = [] all_count = len(user_tag_infos) count = 1 for user_tag_info in user_tag_infos: inputUser = InputUser(user_id=int(user_tag_info.user_id), access_hash=int( user_tag_info.user_hash)) try: user_1( InviteToChannelRequest(inputChannel, [inputUser])) except: print("invite to channel error.userId=" + str(user_tag_info.user_id) + ";userHash=" + str(user_tag_info.user_hash)) # inputUsers.append(inputUser) # if count % 100 == 0 or all_count == count: # print('add users 2 channel.') # try: # client(InviteToChannelRequest(inputChannel, inputUsers)) # except: # print("invite to channel error." + str(user_tag_info.user_id)) # inputUsers.clear() # count += 1 # print('all_count=' + str(all_count) + ';count=' + str(count)) id_add_users_2_channel = False print('add users 2 channel finish.') except: id_add_users_2_channel = False print('add users 2 channel get error.')
async def main(): await client.connect() if not await client.is_user_authorized(): client.send_code_request(phone_number) me = client.sign_in(phone_number, input('Enter code: ')) channel = await client.get_entity( 'https://t.me/qwertyuiop1234567890' ) #channel_ id https://t.me/bloXrouteLabsCommunity users_in_channel = await client.get_participants( 'https://t.me/qwertyuiop1234567890') #channel id or https://t.me/ncent print(users_in_channel) def is_in_group(username): if username in users_in_channel: return True else: return False with open('im.txt', 'r') as f: # file with list of usernames for line in f: print(line) tmp = line[1:].replace('\n', '') print(tmp) try: user = client.get_input_entity( tmp) # (ResolveUsernameRequest(tmp)) print(user) except UsernameInvalidError as err: print(err) continue if user: try: sleep(301) client.invoke( InviteToChannelRequest( InputChannel(channel.id, channel.access_hash), [InputUser(user.user_id, user.access_hash)])) except UserNotMutualContactError as err: print(err) except UserIdInvalidError as err: print(err) else: continue await client.disconnect()
def do_delete_contact(self, phone): user_phone_norm = phone_norm(phone) isContactExist = TLContact.objects.filter( owner=self.user_phone, phone=user_phone_norm).exists() if isContactExist: contactModel = TLContact.objects.get(owner=self.user_phone, phone=user_phone_norm) inputUser = InputUser(int(contactModel.user_id), int(contactModel.access_hash)) result = self.invoke(DeleteContactRequest(inputUser)) # logging.info(result) self.contact_lock.acquire() try: contactModel.delete() finally: self.contact_lock.release() else: logging.error('Contact does not exist {} - {}'.format( self.user_phone, phone=user_phone_norm))
def start(config): client = TelegramClient(config["session_name"], config["api_id"], config["api_hash"]) client.start() input_entities = [] output_channel_entities = [] for d in client.iter_dialogs(): if 'User' == type( d.entity ).__name__ and d.entity.username in config["input_user_usernames"]: input_entities.append(InputUser(d.entity.id, d.entity.access_hash)) if 'Channel' == type( d.entity).__name__ and d.name in config["input_channel_names"]: input_entities.append( InputChannel(d.entity.id, d.entity.access_hash)) if 'Channel' == type( d.entity ).__name__ and d.name in config["output_channel_names"]: output_channel_entities.append( InputChannel(d.entity.id, d.entity.access_hash)) if not output_channel_entities: logger.error( f"Could not find any output channels in the user's dialogs") sys.exit(1) if not input_entities: logger.error( f"Could not find any input channels or users in the user's dialogs" ) sys.exit(1) logging.info( f"Listening on {len(input_entities)} input channels/users. Forwarding messages to {len(output_channel_entities)} channels." ) @client.on(events.NewMessage(chats=input_entities)) async def handler(event): for output_channel in output_channel_entities: await client.forward_messages(output_channel, event.message) client.run_until_disconnected()
async def find_inactive(app, max_days_ago: int): with open('ids_db') as fp: CURRENT_USERS = fp.read().strip().split('\n') USERS = [] for user in CURRENT_USERS: user_id, access_hash = user.split() user = InputUser(int(user_id), int(access_hash)) USERS.append(user) users = await app(GetUsersRequest(USERS)) for user in users: try: was_online = user.status.to_dict().get('was_online') time_diff = is_inactive(was_online, max_days_ago) if time_diff: user_string = f'{user.first_name} {user.last_name}' yield user.id, user_string, time_diff except: pass
def get_saving_group(): # user = client.get_entity("@Jude12") # print(user) # channel = client.get_entity("@mktesttttttttttt") # print(channel) # channel_id = channel.id # channel_hash = channel.access_hash # user_id = user.id # user_hash = user.access_hash channel_id = 1247985828 channel_hash = -8866180916535177199 user_id = 490342664 user_hash = -7707849152056625292 inputChannel = InputChannel(channel_id=channel_id, access_hash=channel_hash) print(inputChannel) inputUser = InputUser(user_id=user_id, access_hash=user_hash) print(inputUser) test = user_1(InviteToChannelRequest(inputChannel, [inputUser])) print(test) return "saving group is:" + saving_group
def inviteToChannel(client, channel, id_list): #Checking for not existing try: resolve = client(ResolveUsernameRequest(channel)) except UsernameInvalidError: print("Incorrect name of channel! Try again.") return False except UsernameNotOccupiedError: print("Incorrect name of channel! Try again.") return False chat_id = resolve.chats[0].id access_hash = resolve.chats[0].access_hash input_channel = InputChannel(chat_id, access_hash) for id in id_list: input_user = InputUser(id, 0) InviteToChannelRequest(input_channel, input_user) return True
def add_users(client, file_name): dialogs, entities = client.get_dialogs(100) avail_channels = {} channel = None channel_id = None channel_access_hash = None for i, entity in enumerate(entities): if not isinstance(entity, User) and not isinstance(entity, Chat): avail_channels[str(i)] = [ entity, entity.id, entity.access_hash, entity.title ] for k, v in avail_channels.items(): print(k, v[3]) channel_index = input( "Please select number of supergroup where you want to add users> ") #participants = client.invoke(GetParticipantsRequest(avail_channels[channel_index][0], ChannelParticipantsSearch(''), 0, 0)) #count_of_members_before_adding = len(participants.users) users = None try: with open(file_name, 'r') as f: users = json.load(f) except Exception: print( 'Invalid file name, make sure you have added extension or if file even exists, if not, run scrape_channel_users.py to create one!' ) sys.exit() count = int( input('Do you want to add only subset of users(' + str(len(users)) + ')? if so, enter the number of users to be added: ')) users_to_save_back = users[ count:] # only users, which didnt be used, will be saved to file again print( str(len(users_to_save_back)) + ' users to be saved back to json file!') users = users[:count] # users to be added print(str(len(users)) + ' users to be removed from list!') print() with open(file_name, 'w') as f: json.dump(users_to_save_back, f, indent=4) input_users = [] for item in users: input_users.append(InputUser(item['id'], item['access_hash'])) user_chunks = list(chunks(input_users, 40)) for item in user_chunks: try: client( InviteToChannelRequest( InputChannel(avail_channels[channel_index][1], avail_channels[channel_index][2]), item)) print('Adding chunk of ' + str(len(item)) + ' users...') time.sleep(2) except Exception as e: print(str(e)) print('some error occurred, skipping to next chunk.') time.sleep(2) print('There was attempt to add ' + str(len(input_users)) + ' users in total.') #participants = client.invoke(GetParticipantsRequest(avail_channels[channel_index][0], ChannelParticipantsSearch(''), 0, 0)) #count_of_members_after_adding = len(participants.users) #print('Count of members before adding: ' + str(count_of_members_before_adding)) #print('Count of members after adding: ' + str(count_of_members_after_adding)) print() #print('True number of added users: ' + str(count_of_members_after_adding - count_of_members_before_adding)) print('added')
def get_input_user(uid): """ create telegram user instance """ return InputUser(uid, 0)
def add_users(client, file_name): dialogs, entities = client.get_dialogs(100) avail_channels = {} channel = None channel_id = None channel_access_hash = None channel_index = '' for i, entity in enumerate(entities): if not isinstance(entity, User) and not isinstance(entity, Chat): avail_channels[str(i)] = [ entity, entity.id, entity.access_hash, entity.title ] if entity.id == 1342112858: #username = StockAceGroup channel_index = str(i) # for k,v in avail_channels.items(): # print(k, v[3]) # channel_index = input("Please select number of supergroup where you want to add users> ") #participants = client.invoke(GetParticipantsRequest(avail_channels[channel_index][0], ChannelParticipantsSearch(''), 0, 0)) #count_of_members_before_adding = len(participants.users) if channel_index == '': print('Can\'t add users because can\'t find StockAce group!') return else: print('Selectetd {0} {1}'.format(channel_index, avail_channels[channel_index][3])) users = None try: with open(file_name, 'r') as f: users = json.load(f) except Exception: print( 'Invalid file name, make sure you have added extension or if file even exists, if not, run scrape_channel_users.py to create one!' ) return # count = int(input('Do you want to add only subset of users('+ str(len(users)) +')? if so, enter the number of users to be added: ')) count = len(users) users_to_save_back = users[ count:] # only users, which didnt be used, will be saved to file again # print(str(len(users_to_save_back)) + ' users to be saved back to json file!') users = users[:count] # users to be added # print(str(len(users)) + ' users to be removed from list!') # print() with open(file_name, 'w') as f: json.dump(users_to_save_back, f, indent=4) input_users = [] for item in users: input_users.append(InputUser(item['id'], item['access_hash'])) user_chunks = list(chunks(input_users, 1)) add_user_count = 0 for item in user_chunks: if add_user_count >= 50: break try: result = client( InviteToChannelRequest( InputChannel(avail_channels[channel_index][1], avail_channels[channel_index][2]), item)) if len(result.users) > 0: add_user_count = add_user_count + 1 print('---Adding chunk of 1 users...') # print(result.stringify()) time.sleep(2) except Exception as e: print(str(e)) print('some error occurred, skipping to next chunk.') time.sleep(2) print('--**' + str(add_user_count) + ' users are added')
def main(): flag = False client.connect() if not client.is_user_authorized(): client.send_code_request(phone_number) me = client.sign_in(phone_number, input('Enter code: ')) while True: channel_name = input( 'Link of channel pls, example: https://t.me/qwertyuiop1234567890, or \'-\'(without \'\') ' 'if you need to convert 10 persons from other group (10 first persons)' ) is_correct = re.search(r'(http?s:\/\/)(t\.me)(\/[A-Za-z0-9]+)', channel_name) if channel_name == is_correct: channel = client.get_entity(channel_name) # channel_ id or name users_in_channel = client.get_participants( channel_name) # channel id or name print(users_in_channel) break elif channel_name == '-': flag = True break continue def from_group_ten_first_persons(group, togroup): flag = True if group == '-': flag = False return flag elif togroup == '-': flag = False return flag users = client.get_participants(group) channel = client.get_entity(togroup) for i in range(10): try: contact = InputPhoneContact(client_id=user[i].id, phone=user[i].phone, first_name=user[i].first_name, last_name=user[i].last_name) result = client.invoke(ImportContactsRequest([contact])) client( InviteToChannelRequest( InputChannel(channel.id, channel.access_hash), [InputUser(users[i].id, users[i].access_hash)])) except errors.rpcerrorlist.UserPrivacyRestrictedError as err: print('>>>>0. UserPrivacyRestrictedError...') print(err) except errors.rpcerrorlist.ChatAdminRequiredError as err: print('>>>>1. ChatAdminRequiredError...') print(err) except errors.rpcerrorlist.ChatIdInvalidError as err: print('>>>>2. ChatIdInvalidError...') print(err) except errors.rpcerrorlist.InputUserDeactivatedError as err: print('>>>>3. InputUserDeactivatedError...') print(err) except errors.rpcerrorlist.PeerIdInvalidError as err: print('>>>>4. PeerIdInvalidError...') print(err) except errors.rpcerrorlist.UserAlreadyParticipantError as err: print('>>>>5. UserAlreadyParticipantError...') print(err) except errors.rpcerrorlist.UserIdInvalidError as err: print('>>>>6. UserIdInvalidError...') print(err) except errors.rpcerrorlist.UserNotMutualContactError as err: print('>>>>>7. UserNotMutualContactError...') print(err) except errors.rpcerrorlist.UsersTooMuchError as err: print('>>>>>8. UsersTooMuchError...') print(err) except errors.rpcerrorlist.PeerFloodError as err: print( '>>>>>9. PeerFloodError try again in 24 Hours...Yes, you in spam' ) print(err) return flag def is_in_group(username): if username in users_in_channel: return True else: return False with open('im.txt') as f: # file with list of usernames for line in f: print(line) tmp = line[1:].replace('\n', '') print(tmp) if not flag: try: user = client.get_entity( tmp) # (ResolveUsernameRequest(tmp)) print(user) except UsernameInvalidError as err: print(err) continue if user: try: contact = InputPhoneContact(client_id=user.id, phone=user.phone, first_name=user.first_name, last_name=user.last_name) result = client.invoke(ImportContactsRequest([contact ])) sleep(31) client( InviteToChannelRequest( InputChannel(channel.id, channel.access_hash), [InputUser(user.id, user.access_hash)])) except errors.rpcerrorlist.UserPrivacyRestrictedError as err: print('>>>>0. UserPrivacyRestrictedError...') print(err) except errors.rpcerrorlist.ChatAdminRequiredError as err: print('>>>>1. ChatAdminRequiredError...') print(err) except errors.rpcerrorlist.ChatIdInvalidError as err: print('>>>>2. ChatIdInvalidError...') print(err) except errors.rpcerrorlist.InputUserDeactivatedError as err: print('>>>>3. InputUserDeactivatedError...') print(err) except errors.rpcerrorlist.PeerIdInvalidError as err: print('>>>>4. PeerIdInvalidError...') print(err) except errors.rpcerrorlist.UserAlreadyParticipantError as err: print('>>>>5. UserAlreadyParticipantError...') print(err) except errors.rpcerrorlist.UserIdInvalidError as err: print('>>>>6. UserIdInvalidError...') print(err) except errors.rpcerrorlist.UserNotMutualContactError as err: print('>>>>>7. UserNotMutualContactError...') print(err) except errors.rpcerrorlist.UsersTooMuchError as err: print('>>>>>8. UsersTooMuchError...') print(err) except errors.rpcerrorlist.PeerFloodError as err: print( '>>>>>9. PeerFloodError try again in 24 Hours...Yes, you in spam' ) print(err) # sleep(86400) elif from_group_ten_first_persons( input('From group get partisipants or - '), input('To group or - ')): break else: continue client.disconnect()
def get_full_user(self, ID, access_hash): result = self.invoke(GetFullUserRequest(InputUser(ID, access_hash))) if result: return result else: return "Cannot get full user. Ensure provided ID is valid."
client = TelegramClient(phone, api_id, api_hash) client.session.report_errors = False client.connect() if not client.is_user_authorized(): client.send_code_request(phone_number) client.sign_in(phone_number, input('Enter the code: ')) channel = client(ResolveUsernameRequest('MY_CHANNEL')) # Your channel username user = client( ResolveUsernameRequest('Username')) # Your channel admin username admins = [ InputUserSelf(), InputUser(user.users[0].id, user.users[0].access_hash) ] # admins admins = [] # No need admins for join and leave and invite filters filter = None # All events filter = ChannelAdminLogEventsFilter(True, False, False, False, True, True, True, True, True, True, True, True, True, True) cont = 0 list = [0, 100, 200, 300] for num in list: result = client( GetParticipantsRequest( InputChannel(channel.chats[0].id, channel.chats[0].access_hash), filter, num, 100)) for _user in result.users: