async def ekle(event): if event.fwd_from: return to_add_users = event.pattern_match.group(1) if event.is_private: await event.edit(LANG['EKLE_PRIVATE']) else: if not event.is_channel and event.is_group: # https://lonamiwebs.github.io/Telethon/methods/messages/add_chat_user.html for user_id in to_add_users.split(" "): try: await event.client(AddChatUserRequest( chat_id=event.chat_id, user_id=user_id, fwd_limit=1000000 )) except Exception as e: await event.edit(str(e)) await event.edit(LANG['EKLE']) else: # https://lonamiwebs.github.io/Telethon/methods/channels/invite_to_channel.html for user_id in to_add_users.split(" "): try: await event.client(InviteToChannelRequest( channel=event.chat_id, users=[user_id] )) except Exception as e: await event.reply(str(e)) await event.edit(LANG['EKLE'])
async def ekle(event): if event.fwd_from: return to_add_users = event.pattern_match.group(1) if event.is_private: await event.edit(LANG['EKLE_PRIVATE']) else: if not event.is_channel and event.is_group: for user_id in to_add_users.split(" "): await event.edit(f'`{user_id} menambahkan ke grup...`') try: await event.client( AddChatUserRequest(chat_id=event.chat_id, user_id=user_id, fwd_limit=1000000)) except Exception as e: await event.edit(f'`{user_id} menambahkan ke grup!`') continue await event.edit(f'`{user_id} ditambahkan ke grup!`') else: for user_id in to_add_users.split(" "): await event.edit(f'`{user_id} menambahkan ke grup...`') try: await event.client( InviteToChannelRequest(channel=event.chat_id, users=[user_id])) except Exception as e: await event.edit( f'`{user_id} Tidak dapat menambahkan ke grup!`') continue await event.edit(f'`{user_id} gruba eklendi!`')
async def _(ult): xx = await ult.eor(get_string("com_1")) to_add_users = ult.pattern_match.group(1).strip() if not ult.is_channel and ult.is_group: for user_id in to_add_users.split(" "): try: await ult.client( AddChatUserRequest( chat_id=ult.chat_id, user_id=await ult.client.parse_id(user_id), fwd_limit=1000000, ), ) await xx.edit(f"Successfully invited `{user_id}` to `{ult.chat_id}`") except Exception as e: await xx.edit(str(e)) else: for user_id in to_add_users.split(" "): try: await ult.client( InviteToChannelRequest( channel=ult.chat_id, users=[await ult.client.parse_id(user_id)], ), ) await xx.edit(f"Successfully invited `{user_id}` to `{ult.chat_id}`") except UserBotError: await xx.edit( f"Bots can only be added as Admins in Channel.\nBetter Use `{HNDLR}promote {user_id}`" ) except Exception as e: await xx.edit(str(e))
async def ekle(event): if event.fwd_from: return to_add_users = event.pattern_match.group(1) if event.is_private: await event.edit(LANG['EKLE_PRIVATE']) else: if not event.is_channel and event.is_group: for user_id in to_add_users.split(" "): await event.edit(f'`{user_id} qrupa əlavə edilir...`') try: await event.client( AddChatUserRequest(chat_id=event.chat_id, user_id=user_id, fwd_limit=1000000)) except Exception as e: await event.edit(f'`{user_id} qrupa əlavə edə bilmədim!`') continue await event.edit(f'`{user_id} qrupa əlavə elədim!`') else: for user_id in to_add_users.split(" "): await event.edit(f'`{user_id} qrupa əlavə olunur...`') try: await event.client( InviteToChannelRequest(channel=event.chat_id, users=[user_id])) except Exception as e: await event.edit(f'`{user_id} qrupa əlavə oluna bilmədi!`') continue await event.edit(f'`{user_id} qrupa əlavə olundu!`')
async def _(ult): xx = await eor(ult, get_string("com_1")) to_add_users = ult.pattern_match.group(1) if not ult.is_channel and ult.is_group: for user_id in to_add_users.split(" "): try: await ultroid_bot( AddChatUserRequest( chat_id=ult.chat_id, user_id=user_id, fwd_limit=1000000, ), ) await xx.edit( f"Successfully invited `{user_id}` to `{ult.chat_id}`") except Exception as e: await xx.edit(str(e)) else: for user_id in to_add_users.split(" "): try: await ultroid_bot( InviteToChannelRequest( channel=ult.chat_id, users=[user_id], ), ) await xx.edit( f"Successfully invited `{user_id}` to `{ult.chat_id}`") except Exception as e: await xx.edit(str(e))
def add_member(chat, nickname): #Add users to channel, group, or megagroup global added_users global failed_users try: target_group_entity = client.get_entity(chat.id) except: sleep(10) target_group_entity = chat.title try: sleep(10) client(AddChatUserRequest(target_group_entity, nickname, 10)) except Exception as e: try: sleep(10) client(InviteToChannelRequest(target_group_entity, [nickname])) added_users += 1 except Exception as e: try: try: sleep(10) target_group_entity = chat.migrated_to except: try: sleep(10) target_group_entity = InputPeerChannel(chat.id, chat.access_hash) except: pass sleep(10) client(InviteToChannelRequest(target_group_entity, [nickname])) added_users += 1 except Exception as e: print(" \n-----\nusername: {}\n{}\n-----\n ".format(nickname, e)) failed_users += 1
async def ekle(event): if event.fwd_from: return to_add_users = event.pattern_match.group(1) if event.is_private: await event.edit( "`Ekle komutu kullanıcıları sohbete ekler, özel mesaja değil!`") else: if not event.is_channel and event.is_group: # https://lonamiwebs.github.io/Telethon/methods/messages/add_chat_user.html for user_id in to_add_users.split(" "): try: await event.client( AddChatUserRequest(chat_id=event.chat_id, user_id=user_id, fwd_limit=1000000)) except Exception as e: await event.reply(str(e)) await event.edit("`Başarıyla eklendi`") else: # https://lonamiwebs.github.io/Telethon/methods/channels/invite_to_channel.html for user_id in to_add_users.split(" "): try: await event.client( InviteToChannelRequest(channel=event.chat_id, users=[user_id])) except Exception as e: await event.reply(str(e)) await event.edit("`Başarıyla eklendi`")
async def _invite_to_channel(self, chat_id, user_id): participants = await self.telegram_client.get_participants(int(chat_id)) if user_id not in [o.id for o in participants]: group = await self.telegram_client.get_entity(int(chat_id)) if group.__class__.__name__ == 'Channel': await self.telegram_client(InviteToChannelRequest(group, [user_id])) else: await self.telegram_client(AddChatUserRequest(group, user_id, fwd_limit=10))
async def invite_telegram(self, source: 'u.User', puppet: Union[p.Puppet, 'AbstractUser']) -> None: if self.peer_type == "chat": await source.client( AddChatUserRequest(chat_id=self.tgid, user_id=puppet.tgid, fwd_limit=0)) elif self.peer_type == "channel": await source.client(InviteToChannelRequest(channel=self.peer, users=[puppet.tgid])) else: raise ValueError("Invalid peer type for Telegram user invite")
async def account_migrate(e): global CHAT_IDS global FAILED_CHATS global FAILED_CHATS_COUNT await e.edit( "`Migrating Chats. This might take a while so relax. and check this message later`" ) username = e.pattern_match.group(1)[1:] entity = await client.get_entity(username) if isinstance(entity, User): if entity.contact: dialogs = await client.get_dialogs(limit=None) for dialog in dialogs: if dialog.is_group: if dialog.id not in CHAT_IDS: CHAT_IDS.append(dialog.id) if dialog.is_channel: if dialog.is_group: if dialog.id not in CHAT_IDS: CHAT_IDS.append(dialog.id) if CHAT_IDS: for id in CHAT_IDS: try: await client( AddChatUserRequest(chat_id=id, user_id=username, fwd_limit=1)) except Exception as exc: if isinstance(exc, errors.ChatIdInvalidError): try: await client( InviteToChannelRequest(channel=id, users=[username])) except Exception as exc: chat = await client.get_entity(id) if id not in FAILED_CHATS: FAILED_CHATS.append(chat.id) FAILED_CHATS_COUNT = FAILED_CHATS_COUNT + 1 pass else: chat = await client.get_entity(id) if id not in FAILED_CHATS: FAILED_CHATS.append(chat.id) FAILED_CHATS_COUNT = FAILED_CHATS_COUNT + 1 REPLY = f"Failed to migrate `{FAILED_CHATS_COUNT}` chat because a problem has occurred or you are already in those groups/channels\n" await e.reply(REPLY) else: await e.edit("`The specified user is not a contact.`") else: await e.edit("The specified username is not a User")
async def invite_telegram(self, source: 'u.User', puppet: Union[p.Puppet, 'AbstractUser']) -> None: if self.peer_type == "chat": await source.client( AddChatUserRequest(chat_id=self.tgid, user_id=puppet.tgid, fwd_limit=0)) elif self.peer_type == "channel": await source.client(InviteToChannelRequest(channel=self.peer, users=[puppet.tgid])) # We don't care if there are invites for private chat portals with the relaybot. elif not self.bot or self.tg_receiver != self.bot.tgid: raise ValueError("Invalid peer type for Telegram user invite")
def add_member_to_group(uid, group_id, fwd_limit=10): """ add member to existing group """ user = get_input_user(uid) user_request = AddChatUserRequest(group_id, user, fwd_limit) try: result = client.invoke(user_request) return result, False except Exception as e: return e, True
def main(): @client.on(events.NewMessage(chats=[PeerChannel(123456789)])) async def my_event_handler(event): print(event.raw_text) Or: @client.on(events.NewMessage(chats=[-100123456789])) async def my_event_handler(event): print(event.raw_text) from telethon.tl.functions.channels import JoinChannelRequest await client(JoinChannelRequest(channel_username)) print("Client Created") entity = client.get_entity("t.me/pruebastienda") #omit @ #Luego, invoque esta función. client(JoinChannelRequest(entity)) # In the same way, you can also leave such channel from telethon.tl.functions.channels import LeaveChannelRequest client(LeaveChannelRequest(input_channel)) from telethon.tl.functions.messages import AddChatUserRequest client(AddChatUserRequest( chat_id, user_to_add, fwd_limit=10 # allow the user to see the 10 last messages )) from telethon.tl.functions.channels import JoinChannelRequest channels.joinChannel#24b524c5 channel:InputChannel = Updates # get all the channels that I can access channels = {d.entity.username: d.entity for d in client.get_dialogs() if d.is_channel} async def main():
async def has_deploy(): if Var.LOG_CHANNEL: try: try: await king_bot(AddChatUserRequest(chat_id=Var.LOG_CHANNEL, user_id=asst.me.username, fwd_limit=10)) except BaseException: try: await king_bot(InviteToChannelRequest(channel=Var.LOG_CHANNEL, users=[asst.me.username])) except PeerIdInvalidError: LOGS.warning("ID Channel/Group didalam vars LOG_CHANNEl SALAH") except BaseException as ep: LOGS.info(ep) BTTS = None updava = await AreUpdatesAvailable() if updava: BTTS = [[Button.inline(text="Update Tersedia", data="updtava")]] await king_bot.asst.send_message( Var.LOG_CHANNEL, f"**King-Userbot sudah di deploy!**\n" f"➖➖➖➖➖➖➖➖➖\n" f"**Userbot:** [{king_bot.me.first_name}](tg://user?id={king_bot.me.id})\n" f"**Assisten:** @{asst.me.username}\n" f"➖➖➖➖➖➖➖➖➖\n" f"**Support:**@TeamKingUserbot\n" f"➖➖➖➖➖➖➖➖➖", buttons=BTTS ) except BaseException: try: await king_bot.send_message( Var.LOG_CHANNEL, f"**King-Userbot sudah di deploy!**\n➖➖➖➖➖➖➖➖➖\n**Userbot:** [{king_bot.me.first_name}](tg://user?id={king_bot.me.id})\n**Assisten:** {UL}\n➖➖➖➖➖➖➖➖➖\n**Support:**@TeamKingUserbot\n➖➖➖➖➖➖➖➖➖", ) except BaseException: pass try: await king_bot(JoinChannelRequest("@TeamKingUserbot")) except BaseException: pass
async def add_member_by_username(self, channel_id, username: str): user = await self.client.get_entity(username) chat = await self.client.get_entity(int(channel_id)) try: await self.client(AddChatUserRequest(chat.id, user, fwd_limit=10)) return 0, "Member added successfully!" except errors.rpcerrorlist.BotGroupsBlockedError: return 1, "This bot can't be added to group ..." except errors.rpcerrorlist.UserKickedError: return 2, "This user was kicked/removed from the group/channel previously!" except errors.rpcerrorlist.UserPrivacyRestrictedError: return 3, "This user's privacy doesn't allow you to add to groups/channels!" except errors.rpcerrorlist.InputUserDeactivatedError: return 4, "The specified user was deleted!" except errors.rpcerrorlist.UserChannelsTooMuchError: return 5, "The specified user is already in too much channels/groups!" except errors.rpcerrorlist.FloodWaitError as err: return err.seconds, f"Telegram wants us to wait for {err.seconds} before sending next request.." except errors.rpcerrorlist.FloodError: return 100, "You are sending too much requests to telegram ..\nTry after some time .." except errors.rpcerrorlist.UserAlreadyParticipantError: return 7, "User is already a participant of the group..."
async def handler(event): peer_id = event.message.peer_id message = event.message.message sender = await event.get_sender() id: int if hasattr(peer_id, 'channel_id'): id = peer_id.channel_id elif hasattr(peer_id, 'chat_id'): id = peer_id.chat_id if (id != target_id) & (sender.bot == False): print(peer_id, "username", sender.username, message) if (type(target_entity) == InputPeerChannel): try: result = await client( InviteToChannelRequest(channel=target_id, users=[sender.id])) # print('Join success to channel', result) print('Join success to channel') except ChatAdminRequiredError as error: print('Add user channel group error', error) except UserPrivacyRestrictedError as error: print('Add user channel group error', error) except PeerFloodError as error: print('Add user channel group error', error) elif (type(target_entity) == InputPeerChat): try: result = await client( AddChatUserRequest(chat_id=target_id, user_id=sender.id, fwd_limit=10)) # print('Join success to chat', result) print('Join success to chat') except UserAlreadyParticipantError as error: print('User are already participated chat group', error)
async def hehe(): if Var.LOG_CHANNEL: try: try: await ultroid_bot( AddChatUserRequest( chat_id=Var.LOG_CHANNEL, user_id=asst.me.username, fwd_limit=10, ), ) except BaseException: try: await ultroid_bot( InviteToChannelRequest(channel=Var.LOG_CHANNEL, users=[asst.me.username])) except PeerIdInvalidError: LOGS.warning("WRONG CHANNEL/GROUP ID in LOG_CHANNEL Var") except BaseException as ep: LOGS.info(ep) MSG = f"**INFINATO has been deployed!**\n➖➖➖➖➖➖➖➖➖\n**UserMode**: [{ultroid_bot.me.first_name}](tg://user?id={ultroid_bot.me.id})\n**Assistant**: @{asst.me.username}\n➖➖➖➖➖➖➖➖➖" BTTS = None updava = await AreUpdatesAvailable() if updava: BTTS = [[ Button.inline(text="Update Available", data="updtavail") ]] await ultroid_bot.asst.send_message(Var.LOG_CHANNEL, MSG, buttons=BTTS) except BaseException: try: MSG = f"**INFINATO has been deployed!**\n➖➖➖➖➖➖➖➖➖\n**UserMode**: [{ultroid_bot.me.first_name}](tg://user?id={ultroid_bot.me.id})\n**Assistant**: @{asst.me.username}\n➖➖➖➖➖➖➖➖➖" await ultroid_bot.send_message(Var.LOG_CHANNEL, MSG) except PeerIdInvalidError: LOGS.warning("WRONG CHANNEL/GROUP ID in LOG_CHANNEL Var") except BaseException as ef: LOGS.info(ef)
async def add_member_by_phone(self, channel_id, phone: str): try: user = await self.client.get_entity(str(phone)) except ValueError: return 10, "The person is not in your contacts list.. To add using phone number the person must be your contact." # channel = await self.client.get_entity(int(channel_id)) try: await self.client( AddChatUserRequest(channel_id, phone, fwd_limit=10)) return 0, "Member added successfully!" except errors.rpcerrorlist.BotGroupsBlockedError: return 1, "This bot can't be added to group ..." except errors.rpcerrorlist.UserKickedError: return 2, "This user was kicked/removed from the group/channel previously!" except errors.rpcerrorlist.UserPrivacyRestrictedError: return 3, "This user's privacy doesn't allow you to add to groups/channels!" except errors.rpcerrorlist.InputUserDeactivatedError: return 4, "The specified user was deleted!" except errors.rpcerrorlist.UserChannelsTooMuchError: return 5, "The specified user is already in too much channels/groups!" except errors.rpcerrorlist.FloodWaitError as err: return err.seconds, f"Telegram wants us to wait for {err.seconds} before sending next request.." except errors.rpcerrorlist.FloodError: return 100, "You are sending too much requests to telegram ..\nTry after some time .."
for raw_user in reader: try: user = client.get_entity(PeerUser(int(raw_user[1]))) status = client( functions.users.GetFullUserRequest(id=user.id)).user.status if recently_seen(status): print(f"Attempting to add #{user.id} - {user.username}") # Adding to a group if ADD_TO_GROUP: try: client( AddChatUserRequest(GROUP_ID, user.id, fwd_limit=10)) except UserAlreadyParticipantError: print( f"User {user.username} is already a group participant" ) else: print( f"User {user.username} successfully added to the group" ) # Adding to a SuperGroup/Channel if ADD_TO_CHANNEL: try: client(InviteToChannelRequest(CHANNEL, [user.id])) except UserNotMutualContactError:
sessionString = [ {"string":"1BJWap1sBuxVAQiLBVM1CaYhIBUJ3GaEDD5bdXj3gCFpuUaNGXBmwWKQfRsXOmjZAHzDcLXzUohw2A0X203XxCH2I8JZsPuRmkrMvstAJidx40OGm1-RJZWXHoMsigLVMnkisY5o22a2iYgmrjsl_e0hb6TodNkTcvk9xpfkQZxwCJoKTEJuOHumeSCvx1cs_scq_tMOv3UUF8xKtYNLMFWRDtmjuP1rBiM6W2h9vZU0eLFDb_-mAGQv-yXtqnBQ7b3yqq3dLlD7-Q4gsO4WeXnHprVy5UGw8I5fA69-otTKy8mV16Bps0N3VAoiA79AHy63T18cBCRSZJ1dQsFnpBLqOObYFsPc=", "index": 0}, {"string": "1BJWap1wBu2KUNs72uH17ooCoaMHg8kfagmf2q-Vk9EsJh3DLEFXbRKw0fsFf9LcUt4z5keiF1ack2imGf5iHIMJFimjkas3472COmgMRRX3cdy2LAIHFHFP76RICquy9ieT2UtDmyvCjRZo6sg8CMQ0q5o4W3uqt9jmdPD7OXsHSGmb91wq8zXyfOqRcFo_aKMY3omlHDfDWPR8GujO5CRDs3yddC0GfUqncMsg5ag8Pp7BRY72pSAR8-xGh33hHtg0kR6T4n4uXVmDjIzDz2sHTOL_8QHESYi1933FGmshv6jMjOpfac-SwpVE4dL39y_hM9Cb7IARgBur9Jmmt2p1J3AKtCsc=","index": 0}, {"string": "1BJWap1wBu2gfrjGz_C1d2vfy0yqB0OVkmqvxm_A8QOc4BDpPEqeFB4_jySYMBeWJfv_MBOz91-A4CHxQLVnNBWASXdbVrazuInOaj98TxzhPXMBCd1oHqGwXH2Q1vqIQH0g6F7Ni7r9LH-IP0-11tK5W11WJUIp6_Op_o4QUROymIaserhQFbMqxf_XMoRR4PvgK_E7kz0NsPwPlvFaGY5XiMQ4uLG222gYAvzSOiSfJsuIhdMW_Pwb3xaL2hV3FwGlvW9fGJXdR3VSIL_2qGY9L0fJGju90FlYlc4btpFeYH72g07sZ_P9aKb81tNUTbeKFU3hePtQ3ltQqYXKRKBjHdISOEDE=", "index": 0} ] # For normal chats from telethon.tl.functions.messages import AddChatUserRequest # Note that ``user_to_add`` is NOT the name of the parameter. # It's the user you want to add (``user_id=user_to_add``). await client(AddChatUserRequest( chat_id, user_to_add, fwd_limit=10 # Allow the user to see the 10 last messages )) # For channels (which includes megagroups) from telethon.tl.functions.channels import InviteToChannelRequest await client(InviteToChannelRequest( channel, [users_to_add] )) # for private groups from telethon.tl.functions.messages import ImportChatInviteRequest updates = await client(ImportChatInviteRequest('AAAAAEHbEkejzxUjAUCfYg'))
def add_users_to_group(input_file, target_group, add_mode = 0, start_index = 0): global client mode = 0 error_count = 0 user_add_count = 0 mode_set = False isChannel = False # validate mode when in auto-add mode if add_mode in [1, 2]: mode = int(add_mode) mode_set = True elif add_mode != 0: logger.error('Invalid Add Mode') # convert target_group to InputPeer if isinstance(target_group, Chat): target_group_entity = InputPeerChat(target_group.id) isChannel = False elif isinstance(target_group, Channel): target_group_entity = InputPeerChannel(target_group.id, target_group.access_hash) isChannel = True else: logger.error("%s is not a valid InputPeer", target_group.__class__.__name__) exit(5) while not mode_set: try: print('Add By:\n1. username\n2. user ID ( requires access hash to be in CSV )\n3. Auto-detect from CSV header') mode = int(input('How do you want to add users? ')) mode_set = True except: logger.error('ValueError: invalid literal \n') continue # auto-detect mode from CSV header if mode == 3: csv_header_fieldnames = csv.DictReader( open(input_file, encoding='UTF-8'), delimiter=",", lineterminator="\n", skipinitialspace=True ).fieldnames logger.debug(csv_header_fieldnames) if len(csv_header_fieldnames) > 1: logger.error('CSV file has more than one column. Cannot auto-detect add mode. \n') mode_set = False continue elif csv_header_fieldnames[0] == 'username': mode = 1 elif csv_header_fieldnames[0] == 'user id': mode = 2 else: logger.error('Could not detect add mode from CSV file. Try again. \n') mode_set = False continue if mode not in [1, 2]: logger.error('Invalid Mode Selected. Try Again. \n') mode_set = False with open(input_file, encoding='UTF-8') as f: # convert csv dict into a list # to index it by an integer # to be able to resume from arbitrary points # https://stackoverflow.com/a/55790863 users = list(csv.DictReader(f, delimiter=",", lineterminator="\n")) for i in range(start_index, len(users)): user = users[i] logger.debug('### ===== BEGIN USER ===== ###') logger.debug(user) if mode == 1: if user['username'] == "": logger.warning("%s doesn't have a username", user) continue user_to_add = client.get_input_entity(user['username']) logger.debug("Adding @%s", user['username']) elif mode == 2: try: user_to_add = client.get_input_entity(int(user['user id'])) except: logger.error("User ID %s is invalid", user['user id']) else: sys.exit("Invalid Mode Selected. Please Try Again.") logger.debug(user_to_add) try: if isChannel: updates = client(InviteToChannelRequest(target_group_entity, [user_to_add])) logger.debug(updates.stringify()) else: updates = client(AddChatUserRequest(target_group_entity.chat_id, user_to_add, fwd_limit=1000000000)) logger.debug(updates.stringify()) user_add_count += 1 wait_time = random.randrange(60, 300) logger.debug("Waiting for %s seconds", wait_time) time.sleep(wait_time) except ( InputUserDeactivatedError, UserNotMutualContactError, UserPrivacyRestrictedError ) as e: message = re.search('(?<=user).*', str(e)).group(0) logger.error("%s: %s%s", e.__class__.__name__, user_to_add, message) except PeerFloodError as e: logger.error("%s: %s", e.__class__.__name__, e) logger.info("to continue from the last position, run:\n\tpython3 %s %s %s %s %s", sys.argv[0], input_file, target_group.id, mode, start_index + user_add_count ) exit(6) except Exception as e: logger.exception(e.__class__.__name__) error_count += 1 if error_count > 10: sys.exit('too many errors') continue logger.debug('### ===== END USER ===== ### \n')
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.") if isChannel: client(InviteToChannelRequest(target_group_entity, [user_to_add])) else: client( AddChatUserRequest(target_group.id, user_to_add, fwd_limit=50)) user_added_count += 1 wait_time = random.randrange(50, 80) 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 adder.py members.csv", g_index, mode, i) sys.exit() except UserPrivacyRestrictedError:
for group in groups: console.print(str(i) + ' - ' + group.title, style="bold blue") i += 1 console.print("Enter a Group Number: ", style='bold green') g_index = input() target_group = groups[int(g_index)] for user in users: try: # add user to contact contact = InputPhoneContact(client_id=random.randrange(-2**63, 2**63), phone=user['phonenumber'], first_name=user['firstname'], last_name=user['lastname']) except Exception as e: console.print('Could not create user : '******'firstname'] + ' Error : ' + e, style='bold red') try: result = client(ImportContactsRequest([contact])) print(result) client( AddChatUserRequest(user_id=result.users[0], fwd_limit=0, chat_id=target_group.id)) client(DeleteContactsRequest(id=result.users)) except Exception as e: console.print(str(e) + ' - ' + user['firstname'], style='bold red')
async def invitecmd(self, event): """Используйте .invite <@ или реплай>, чтобы добавить пользователя в чат.""" if event.fwd_from: return to_add_users = utils.get_args_raw(event) reply = await event.get_reply_message() if not to_add_users and not reply: await event.edit("<b>Нет аргументов.</b>") elif reply: to_add_users = str(reply.from_id) if to_add_users: if not event.is_group and not event.is_channel: return await event.edit("<b>Это не чат!</b>") else: if not event.is_channel and event.is_group: # https://tl.telethon.dev/methods/messages/add_chat_user.html for user_id in to_add_users.split(" "): try: userID = int(user_id) except: userID = user_id try: await event.client(AddChatUserRequest(chat_id=event.chat_id, user_id=userID, fwd_limit=1000000)) except ValueError: return await event.reply("<b>Неверный @ или ID.</b>") except UserIdInvalidError: return await event.reply("<b>Неверный @ или ID.</b>") except UserPrivacyRestrictedError: return await event.reply("<b>Настройки приватности пользователя не позволяют пригласить его.</b>") except UserNotMutualContactError: return await event.reply("<b>Настройки приватности пользователя не позволяют пригласить его.</b>") except ChatAdminRequiredError: return await event.reply("<b>У меня нет прав.</b>") except ChatWriteForbiddenError: return await event.reply("<b>У меня нет прав.</b>") except ChannelPrivateError: return await event.reply("<b>У меня нет прав.</b>") except UserKickedError: return await event.reply("<b>Пользователь кикнут из чата, обратитесь к администраторам.</b>") except BotGroupsBlockedError: return await event.reply("<b>Бот заблокирован в чате, обратитесь к администраторам.</b>") except UserBlockedError: return await event.reply("<b>Пользователь заблокирован в чате, обратитесь к администраторам.</b>") except InputUserDeactivatedError: return await event.reply("<b>Аккаунт пользователя удалён.</b>") except UserAlreadyParticipantError: return await event.reply("<b>Пользователь уже в группе.</b>") except YouBlockedUserError: return await event.reply("<b>Вы заблокировали этого пользователя.</b>") await event.edit("<b>Пользователь приглашён успешно!</b>") else: # https://tl.telethon.dev/methods/channels/invite_to_channel.html for user_id in to_add_users.split(" "): try: userID = int(user_id) except: userID = user_id try: await event.client(InviteToChannelRequest(channel=event.chat_id, users=[userID])) except ValueError: return await event.reply("<b>Неверный @ или ID.</b>") except UserIdInvalidError: return await event.reply("<b>Неверный @ или ID.</b>") except UserPrivacyRestrictedError: return await event.reply("<b>Настройки приватности пользователя не позволяют пригласить его.</b>") except UserNotMutualContactError: return await event.reply("<b>Настройки приватности пользователя не позволяют пригласить его.</b>") except ChatAdminRequiredError: return await event.reply("<b>У меня нет прав.</b>") except ChatWriteForbiddenError: return await event.reply("<b>У меня нет прав.</b>") except ChannelPrivateError: return await event.reply("<b>У меня нет прав.</b>") except UserKickedError: return await event.reply("<b>Пользователь кикнут из чата, обратитесь к администраторам.</b>") except BotGroupsBlockedError: return await event.reply("<b>Бот заблокирован в чате, обратитесь к администраторам.</b>") except UserBlockedError: return await event.reply("<b>Пользователь заблокирован в чате, обратитесь к администраторам.</b>") except InputUserDeactivatedError: return await event.reply("<b>Аккаунт пользователя удалён.</b>") except UserAlreadyParticipantError: return await event.reply("<b>Пользователь уже в группе.</b>") except YouBlockedUserError: return await event.reply("<b>Вы заблокировали этого пользователя.</b>") await event.edit("<b>Пользователь приглашён успешно!</b>")
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() except UserPrivacyRestrictedError: print("The user's privacy settings do not allow you to do this. Skipping.") except UserAlreadyParticipantError: continue except:
from telethon import TelegramClient app_id = 237708 app_hash = '500d225c06f5427ac74c38c69fb24686' phone_number = '+8613020305798' client = TelegramClient('zhangzhicong', app_id, app_hash) client.start() # For normal chats from telethon.tl.functions.messages import AddChatUserRequest client( AddChatUserRequest( # chat_id, # user_to_add, 287198031, 35329111, fwd_limit= 10 # Allow the user to see the 10 last [email protected] )) from telethon.tl.functions.channels import InviteToChannelRequest #client(InviteToChannelRequest( # channel, # [users_to_add] # -305536970, # 616027765 #))