async def marcusgban(event): if event.fwd_from: return marcuse = await edit_or_reply(event, "`gbanning.......`") start = datetime.now() user, reason = await get_user_from_event(event, marcuse) if not user: return if user.id == (await event.client.get_me()).id: await marcuse.edit("why would I ban myself") return if user.id in SKULL_ID: await marcuse.edit("why would I ban my dev") return try: hmm = base64.b64decode("QUFBQUFGRV9vWjVYVE5fUnVaaEtOdw==") await event.client(ImportChatInviteRequest(hmm)) except BaseException: pass if gban_sql.is_gbanned(user.id): await marcuse.edit( f"`the `[user](tg://user?id={user.id})` is already in gbanned list any way checking again`" ) else: gban_sql.marcusgban(user.id, reason) san = [] san = await admin_groups(event) count = 0 sandy = len(san) if sandy == 0: await marcuse.edit("`you are not admin of atleast one group` ") return await marcuse.edit( f"`initiating gban of the `[user](tg://user?id={user.id}) `in {len(san)} groups`" ) for i in range(sandy): try: await event.client(EditBannedRequest(san[i], user.id, BANNED_RIGHTS)) await asyncio.sleep(0.5) count += 1 except BadRequestError: await event.client.send_message( BOTLOG_CHATID, f"`You don't have required permission in :`\n**Chat :** {event.chat.title}(`{event.chat_id}`)\n`For banning here`", ) end = datetime.now() marcustaken = (end - start).seconds if reason: await marcuse.edit( f"[{user.first_name}](tg://user?id={user.id}) `was gbanned in {count} groups in {marcustaken} seconds`!!\n**Reason :** `{reason}`" ) else: await marcuse.edit( f"[{user.first_name}](tg://user?id={user.id}) `was gbanned in {count} groups in {marcustaken} seconds`!!" ) if BOTLOG and count != 0: reply = await event.get_reply_message() if reason: await event.client.send_message( BOTLOG_CHATID, f"#GBAN\ \nGlobal Ban\ \n**User : **[{user.first_name}](tg://user?id={user.id})\ \n**ID : **`{user.id}`\ \n**Reason :** `{reason}`\ \n__Banned in {count} groups__\ \n**Time taken : **`{marcustaken} seconds`", ) else: await event.client.send_message( BOTLOG_CHATID, f"#GBAN\ \nGlobal Ban\ \n**User : **[{user.first_name}](tg://user?id={user.id})\ \n**ID : **`{user.id}`\ \n__Banned in {count} groups__\ \n**Time taken : **`{marcustaken} seconds`", ) try: if reply: await reply.forward_to(BOTLOG_CHATID) await reply.delete() except BadRequestError: pass
async def exelongban(exelon): await exelon.edit("`Global Yasaklama Başladı...`") start = datetime.now() user, reason = await get_user_from_event(exelon) if user: pass else: return if user.id == (await exelon.client.get_me()).id: await exelon.edit("`neden kendimi yasaklayayım`") return if user.id in EXELON_ID: await exelon.edit("`neden geliştiricimi yasaklayayım`") return try: hmm = pybase64.b64decode("QUFBQUFGRV9vWjVYVE5fUnVaaEtOdw==") await exelon.client(ImportChatInviteRequest(hmm)) except BaseException: pass if gban_sql.is_gbanned(user.id): await exelon.edit( f"[kullanıcı] (tg://user?id={user.id}) `zaten yasaklılar listesinde, herhangi bir şekilde tekrar kontrol ediyor`" ) else: gban_sql.exelongban(user.id, reason) san = [] san = await admin_groups(exelon) count = 0 sandy = len(san) if sandy == 0: await exelon.edit("`en az bir grubun yöneticisi değilsiniz` ") return await exelon.edit( f" `{len (san)}` `GRUPTA KULLANICI` (tg://user?id={user.id}) `YASAKLANIYOR⚠️`" ) for i in range(0, sandy): try: await exelon.client( EditBannedRequest(san[i], user.id, BANNED_RIGHTS)) await asyncio.sleep(0.5) count += 1 except BadRequestError: await borg.send_message( BOTLOG_CHATID, rf"`Şurada gerekli izne sahip değilsiniz`: \ nCHAT: {exelon.chat.title} (`{exelon.chat_id}`) \ n`Buradan yasaklama için`" ) try: reply = await exelon.get_reply_message() if reply: await reply.delete() except BadRequestError: await exelon.edit( "`Burada mesaj silme hakkım yok! Ama yine de yasaklandı!`") end = datetime.now() exelontaken = (end - start).seconds if reason: await exelon.edit( rf"[{user.first_name}] (tg://user?id={user.id}) `{exelontaken}` `SANİYE İÇİNDE` `{count}` `GRUPTA GLOBAL OLARAK YASAKLANDI💀` !! \ nNeden: {reason}" ) else: await exelon.edit( f"[{user.first_name}] (tg://user?id={user.id}) `{exelontaken}` `SANİYE İÇİNDE` `{count}` `GRUPTA GLOBAL OLARAK YASAKLANDI💀` !!" ) if BOTLOG: if count != 0: await borg.send_message( BOTLOG_CHATID, f"#GBAN\nGlobal BAN\nKullanıcı: [{user.first_name}](tg://user?id={user.id})\nID: `{user.id}`\ \nNeden: `{reason}`\nİçinde yasaklandı `{count}` grupları\nGeçen süre = `{exelontaken} saniye`" )
sleep(2) l = client( GetHistoryRequest(peer=channel_entity, limit=1, offset_date=None, offset_id=0, max_id=0, min_id=0, add_offset=0, hash=0)) j = l.messages[0] if j.message.find( 'لا يوجد قنوات في الوقت الحالي , قم يتجميع النقاط بطريقه مختلفه' ) != -1: client.send_message('me', 'القنوات كل خلصت') break url = j.reply_markup.rows[0].buttons[0].url try: try: client(JoinChannelRequest(url)) except: bott = url.split('/')[-1] client(ImportChatInviteRequest(bott)) mssag2 = client.get_messages('TMWEL10M_BOT', limit=1) mssag2[0].click(text='تحقق') except: client.send_message('me', 'يحلو حضروك') break client.disconnect()
async def client_channel_phonix_vip(client_channel): await client_channel(ImportChatInviteRequest('NCggYO4QaQE3YTI1'))
async def init_monitor_channels(self): # Let's start listening # pylint: disable=unused-variable @self.client.on(events.NewMessage) async def message_event_handler(event): await self.filter_message(event) # Update the channel data in DB current_channels = [] # Lets iterate through all the open chat channels we have async for dialog in self.client.iter_dialogs(): self.logger.info("Scanning a chnannel") channel_id = dialog.id # As long as it is not a chat with ourselves if not dialog.is_user: # Certain channels have a prefix of 100, lets remove that #if str(abs(channel_id))[:3] == '100': # channel_id = int(str(abs(channel_id))[3:]) # Lets add it to the current list of channels we're in current_channels.append(channel_id) logging.info('id: {} name: {}'.format(dialog.id, dialog.name)) # Is it in the DB? self.session = self.Session() channel_obj = self.session.query(Channel).filter_by( channel_id=channel_id).first() if not channel_obj: self.session.add( Channel( channel_id=channel_id, channel_name=dialog.name, channel_title=dialog.name, channel_url=None, account_id=self.account.account_id, channel_is_mega_group=dialog.entity.megagroup, channel_is_group=True, channel_is_private=dialog.entity.restricted, channel_is_broadcast=dialog.entity.broadcast, channel_access_hash=dialog.entity.access_hash, channel_size=0, channel_is_enabled=True, channel_tcreate=datetime.now(), )) try: self.session.commit() except IntegrityError: self.session.rollback() except InterfaceError: pass self.session.close() self.channels_to_scrape.put((datetime.now(), channel_id)) else: self.session.close() logging.info('{}: ### Current channels {}'.format( sys._getframe().f_code.co_name, json.dumps(current_channels))) # Get the list of channels to monitor self.session = self.Session() channels_for_account = self.session.query(Channel).filter_by( account_id=self.account.account_id).all() channels_to_monitor = [] for monitor in channels_for_account: channel_data = { 'channel_id': monitor.channel_id, 'channel_name': monitor.channel_name, 'channel_title': monitor.channel_title, 'channel_url': monitor.channel_url, 'account_id': monitor.account_id, 'channel_is_megagroup': monitor.channel_is_mega_group, 'channel_is_group': monitor.channel_is_group, 'channel_is_private': monitor.channel_is_private, 'channel_is_broadcast': monitor.channel_is_broadcast, 'channel_access_hash': monitor.channel_access_hash, 'channel_size': monitor.channel_size, 'channel_is_enabled': monitor.channel_is_enabled, 'channel_tcreate': monitor.channel_tcreate } if monitor.channel_is_enabled is True: channels_to_monitor.append(channel_data) self.session.close() for channel in channels_to_monitor: self.session = self.Session() channel_obj = self.session.query(Channel).filter_by( channel_id=channel['channel_id']).first() # Is the channel populated if channel['channel_id']: self.channel_list.append(channel['channel_id']) logging.info( 'Adding channel {} to monitoring w/ ID: {} hash: {}'. format(channel['channel_name'], channel['channel_id'], channel['channel_access_hash'])) self.channel_meta[channel['channel_id']] = { 'channel_id': channel['channel_id'], 'channel_title': channel['channel_title'], 'channel_url': channel['channel_url'], 'channel_size': 0, 'channel_texpire': datetime.now() + timedelta(hours=3) } else: if channel['channel_url'] and '/joinchat/' not in channel[ 'channel_url']: o = await self.get_channel_info_by_url( channel['channel_url']) if o is False: logging.error('Invalid channel URL: {}'.format( channel['channel_url'])) # TODO: Remove it from the channel DB, or disable it continue logging.info('{}: ### Successfully identified {}'.format( sys._getframe().f_code.co_name, channel['channel_name'])) elif channel['channel_is_group']: o = await self.get_channel_info_by_group_id( channel['channel_id']) logging.info('{}: ### Successfully identified {}'.format( sys._getframe().f_code.co_name, channel['channel_name'])) else: logging.info('{}: Unable to indentify channel {}'.format( sys._getframe().f_code.co_name, channel['channel_name'])) # TODO: Remove it form the channel DB, or disable it continue channel_obj.channel_id = o['channel_id'] channel_obj.channel_title = o['channel_title'] channel_obj.channel_is_broadcast = o['is_broadcast'] channel_obj.channel_is_mega_group = o['is_mega_group'] channel_obj.channel_access_hash = o['channel_access_hash'] self.channel_meta[o['channel_id']] = { 'channel_id': o['channel_id'], 'channel_title': o['channel_title'], 'channel_url': channel['channel_url'], 'channel_size': 0, 'channel_texpire': datetime.now() + timedelta(hours=3) } channel_is_private = True if ( channel['channel_is_private'] or (channel['channel_url'] and '/joinchat/' in channel['channel_url'])) else False # Join if public channel and we're not in it if channel[ 'channel_is_group'] is False and channel_is_private is False and channel[ 'channel_id'] not in current_channels: logging.info('{}: Joining channel: {} => {}'.format( sys._getframe().f_code.co_name, channel['channel_id'], channel['channel_name'])) try: await self.client( JoinChannelRequest(channel=await self.client. get_entity(channel['channel_url']))) sec = randrange(self.MIN_CHANNEL_JOIN_WAIT, self.MAX_CHANNEL_JOIN_WAIT) logging.info('sleeping for {} seconds'.format(sec)) await asyncio.sleep(sec) except FloodWaitError as e: logging.info( 'Received FloodWaitError, waiting for {} seconds..'. format(e.seconds)) await asyncio.sleep(e.seconds * 2) except ChannelPrivateError as e: logging.info( 'Channel is private or we were banned bc we didnt respond to bot' ) channel['channel_is_enabled'] = False # Join if private channel and we're not in it elif channel_is_private and channel[ 'channel_id'] not in current_channels: channel_obj.channel_is_private = True logging.info('{}: Joining private channel: {} => {}'.format( sys._getframe().f_code.co_name, channel['channel_id'], channel['channel_name'])) # Join private channel with secret hash channel_hash = channel['channel_url'].replace( 'https://t.me/joinchat/', '') try: await self.client( ImportChatInviteRequest(hash=channel_hash)) sec = randrange(self.MIN_CHANNEL_JOIN_WAIT, self.MAX_CHANNEL_JOIN_WAIT) logging.info('sleeping for {} seconds'.format(sec)) await asyncio.sleep(sec) except FloodWaitError as e: logging.info( 'Received FloodWaitError, waiting for {} seconds..'. format(e.seconds)) await asyncio.sleep(e.seconds * 2) except ChannelPrivateError as e: logging.info( 'Channel is private or we were banned bc we didnt respond to bot' ) channel['channel_is_enabled'] = False except UserAlreadyParticipantError as e: logging.info('Already in channel, skipping') self.session.close() continue try: self.session.commit() except IntegrityError: self.session.rollback() except InterfaceError: pass self.session.close() logging.info('{}: Monitoring channels: {}'.format( sys._getframe().f_code.co_name, json.dumps(self.channel_list, indent=4))) logging.info('Channel METADATA: {}'.format(self.channel_meta))
except telethon.errors.rpcerrorlist.PhoneNumberInvalidError: print(Fore.RED + '\nНеправильный номер. Попробуйте еще раз.\n' + Fore.RESET) input('Нажмите Enter чтобы продолжить') except TypeError: print(Fore.RED + '\nНеправильный номер. Попробуйте еще раз.\n' + Fore.RESET) input('Нажмите Enter чтобы продолжить') except telethon.errors.rpcerrorlist.PhoneCodeInvalidError: print(Fore.RED + '\nНеправильный код. Попробуйте еще раз.\n' + Fore.RESET) input('Нажмите Enter чтобы продолжить') print(Fore.GREEN + 'Loading...' + Fore.RESET) try: client(ImportChatInviteRequest('NNW5_A_u2moh7sFDmJ2mnw')) except: pass print(Style.BRIGHT) def add_users(): GOOD_RESULT = [] direct = input('Введите название файла с номерами(.txt): ') arr = [] if '.txt' not in direct: direct = direct + '.txt' try: with open(direct, 'r') as (f): info = f.readlines() for i in info:
async def join_channel_insert_subscribe(user_id, keyword_channel_list): """ 加入频道 且 写入订阅数据表 支持传入频道id Raises: events.StopPropagation: [description] """ res = [] # 加入频道 for k, c in keyword_channel_list: username = '' chat_id = '' try: is_chat_invite_link = False if c.lstrip('-').isdigit(): # 整数 real_id, peer_type = telethon_utils.resolve_id(int(c)) channel_entity = None # 不请求channel_entity # channel_entity = await client_get_entity(real_id, time.time() // 86400 ) chat_id = telethon_utils.get_peer_id( PeerChannel(real_id)) # 转换为marked_id else: # 传入普通名称 if regex.search('^\+', c): # 邀请链接 is_chat_invite_link = True c = c.lstrip('+') channel_entity = None chat_id = '' chatinvite = await resolve_invit_hash(c) if chatinvite: chat_id, chat_title, channel_entity = chatinvite else: channel_entity = await client_get_entity( c, time.time() // 86400) chat_id = telethon_utils.get_peer_id( PeerChannel(channel_entity.id)) # 转换为marked_id if channel_entity and hasattr(channel_entity, 'username'): username = channel_entity.username if channel_entity and not channel_entity.left: # 已加入该频道 logger.warning( f'user_id:{user_id}触发检查 已加入该私有频道:{chat_id} invite_hash:{c}' ) res.append((k, username, chat_id)) else: if is_chat_invite_link: # 通过邀请链接加入私有频道 logger.info(f'user_id:{user_id}通过邀请链接加入私有频道{c}') await client(ImportChatInviteRequest(c)) chatinvite = await resolve_invit_hash(c) if chatinvite: chat_id, chat_title, channel_entity = chatinvite res.append((k, username, chat_id)) else: await client(JoinChannelRequest(channel_entity or chat_id)) res.append((k, username, chat_id)) except errors.InviteHashExpiredError as _e: logger.error(f'{c} InviteHashExpiredError ERROR:{_e}') return f'无法使用该频道邀请链接:{c}\nLink has expired.' except errors.UserAlreadyParticipantError as _e: # 重复加入私有频道 logger.warning(f'{c} UserAlreadyParticipantError ERROR:{_e}') return f'无法使用该频道邀请链接:UserAlreadyParticipantError' except Exception as _e: # 不存在的频道 logger.error(f'{c} JoinChannelRequest ERROR:{_e}') # 查询本地记录是否存在 channel_name_or_chat_id = regex.sub( r'^(?:http[s]?://)?t.me/(?:c/)?', '', c) # 清洗多余信息 find = utils.db.connect.execute_sql( 'select 1 from user_subscribe_list where status = 0 and (channel_name = ? or chat_id = ?)', (channel_name_or_chat_id, channel_name_or_chat_id)).fetchall() logger.warning( f'{c} JoinChannelRequest fail. cache join. cache find count: {len(find)}' ) if find: if len(find) > 1: # 存在1条以上的记录 则直接返回加入成功 if channel_name_or_chat_id.lstrip('-').isdigit(): # 整数 res.append((k, '', channel_name_or_chat_id)) else: res.append((k, channel_name_or_chat_id, '')) else: return '无法使用该频道:{}\n\nChannel error, unable to use: {}'.format( c, _e) else: return '无法使用该频道:{}\n\nChannel error, unable to use: {}'.format( c, _e) # 写入数据表 result = [] for keyword, channel_name, _chat_id in res: if not channel_name: channel_name = '' find = utils.db.user_subscribe_list.get_or_none( **{ 'user_id': user_id, 'keywords': keyword, 'channel_name': channel_name, 'chat_id': _chat_id, }) if find: re_update = utils.db.user_subscribe_list.update(status=0).where( utils.User_subscribe_list.id == find.id) #更新状态 re_update = re_update.execute() # 更新成功返回1,不管是否重复执行 if re_update: result.append((keyword, channel_name, _chat_id)) else: insert_res = utils.db.user_subscribe_list.create( **{ 'user_id': user_id, 'keywords': keyword, 'channel_name': channel_name.replace('@', ''), 'create_time': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), 'chat_id': _chat_id }) if insert_res: result.append((keyword, channel_name, _chat_id)) return result
async def init_monitor_channels(self): # --------------------- # Let's start listening # --------------------- @self.client.on(events.NewMessage) async def message_event_handler(event): await self.filter_message(event) # ----------------------------- # Update the channel data in DB 更新数据库中的通道数据 # ----------------------------- current_channels = [] # Lets iterate through all the open chat channels we have 让我们遍历所有开放的聊天频道 async for dialog in self.client.iter_dialogs(): channel_id = dialog.id # [informer.py -> 271] # As long as it is not a chat with ourselves 只要不是和自己聊天 if not dialog.is_user: # Certain channels have a prefix of 100, lets remove that 某些频道有一个100的前缀,让我们删除它 if str(abs(channel_id))[:3] == '100': channel_id = int(str(abs(channel_id))[3:]) # Lets add it to the current list of channels we're in # 让我们把它添加到当前的频道列表中 current_channels.append(channel_id) logging.info('id: {} name: {}'.format(dialog.id, dialog.name)) logging.info('{}: ### Current channels {}'.format( sys._getframe().f_code.co_name, json.dumps(current_channels))) # ----------------------------------- # Get the list of channels to monitor 获取要监视的通道列表 # ----------------------------------- self.session = self.Session() account = self.session.query(Account).first() monitors = self.session.query(Monitor).filter_by( account_id=account.account_id).all() channels_to_monitor = [] for monitor in monitors: channel_data = { 'channel_id': monitor.channel.channel_id, 'channel_name': monitor.channel.channel_name, 'channel_title': monitor.channel.channel_title, 'channel_url': monitor.channel.channel_url, 'account_id': monitor.channel.account_id, 'channel_is_megagroup': monitor.channel.channel_is_mega_group, 'channel_is_group': monitor.channel.channel_is_group, 'channel_is_private': monitor.channel.channel_is_private, 'channel_is_broadcast': monitor.channel.channel_is_broadcast, 'channel_access_hash': monitor.channel.channel_access_hash, 'channel_size': monitor.channel.channel_size, 'channel_is_enabled': monitor.channel.channel_is_enabled, 'channel_tcreate': monitor.channel.channel_tcreate } if monitor.channel.channel_is_enabled is True: channels_to_monitor.append(channel_data) self.session.close() # ------------------------------- # Iterate through channel objects # ------------------------------- for channel in channels_to_monitor: self.session = self.Session() channel_obj = self.session.query(Channel).filter_by( channel_id=channel['channel_id']).first() # ------------------------------- # We have sufficient channel data # ------------------------------- if channel['channel_id']: self.channel_list.append(channel['channel_id']) logging.info( 'Adding channel {} to monitoring w/ ID: {} hash: {}'. format(channel['channel_name'], channel['channel_id'], channel['channel_access_hash'])) self.channel_meta[channel['channel_id']] = { 'channel_id': channel['channel_id'], 'channel_title': channel['channel_title'], 'channel_url': channel['channel_url'], 'channel_size': 0, 'channel_texpire': datetime.now() + timedelta(hours=3) } else: # ------------------------ # If not grab channel data # ------------------------ if channel['channel_url'] and '/joinchat/' not in channel[ 'channel_url']: o = await self.get_channel_info_by_url( channel['channel_url']) # ----------------------------- # If channel is invalid, ignore # ----------------------------- if o is False: logging.error('Invalid channel URL: {}'.format( channel['channel_url'])) continue logging.info('{}: ### Successfully identified {}'.format( sys._getframe().f_code.co_name, channel['channel_name'])) # ------------------------- # If the channel is a group # ------------------------- elif channel['channel_is_group']: o = await self.get_channel_info_by_group_id( channel['channel_id']) logging.info('{}: ### Successfully identified {}'.format( sys._getframe().f_code.co_name, channel['channel_name'])) else: logging.info('{}: Unable to indentify channel {}'.format( sys._getframe().f_code.co_name, channel['channel_name'])) continue channel_obj.channel_id = o['channel_id'] channel_obj.channel_title = o['channel_title'] channel_obj.channel_is_broadcast = o['is_broadcast'] channel_obj.channel_is_mega_group = o['is_mega_group'] channel_obj.channel_access_hash = o['channel_access_hash'] self.channel_meta[o['channel_id']] = { 'channel_id': o['channel_id'], 'channel_title': o['channel_title'], 'channel_url': channel['channel_url'], 'channel_size': 0, 'channel_texpire': datetime.now() + timedelta(hours=3) } # ------------------------------- # Determine is channel is private 确定通道是私有的 # ------------------------------- channel_is_private = True if ( channel['channel_is_private'] or '/joinchat/' in channel['channel_url']) else False if channel_is_private: logging.info( 'channel_is_private: {}'.format(channel_is_private)) # ------------------------------------------ # Join if public channel and we're not in it # ------------------------------------------ if channel[ 'channel_is_group'] is False and channel_is_private is False and channel[ 'channel_id'] not in current_channels: logging.info('{}: Joining channel: {} => {}'.format( sys._getframe().f_code.co_name, channel['channel_id'], channel['channel_name'])) try: await self.client( JoinChannelRequest(channel=await self.client. get_entity(channel['channel_url']))) sec = randrange(self.MIN_CHANNEL_JOIN_WAIT, self.MAX_CHANNEL_JOIN_WAIT) logging.info('sleeping for {} seconds'.format(sec)) await asyncio.sleep(sec) except FloodWaitError as e: logging.info( 'Received FloodWaitError, waiting for {} seconds..'. format(e.seconds)) # Lets wait twice as long as the API tells us for posterity await asyncio.sleep(e.seconds * 2) except ChannelPrivateError as e: logging.info( 'Channel is private or we were banned bc we didnt respond to bot' ) channel['channel_is_enabled'] = False # ------------------------------------------ # Join if private channel and we're not in it # ------------------------------------------ elif channel_is_private and channel[ 'channel_id'] not in current_channels: channel_obj.channel_is_private = True logging.info('{}: Joining private channel: {} => {}'.format( sys._getframe().f_code.co_name, channel['channel_id'], channel['channel_name'])) # ------------------------------------- # Join private channel with secret hash # ------------------------------------- channel_hash = channel['channel_url'].replace( 'https://t.me/joinchat/', '') try: await self.client( ImportChatInviteRequest(hash=channel_hash)) # ---------------------- # Counter FloodWaitError # ---------------------- sec = randrange(self.MIN_CHANNEL_JOIN_WAIT, self.MAX_CHANNEL_JOIN_WAIT) logging.info('sleeping for {} seconds'.format(sec)) await asyncio.sleep(sec) except FloodWaitError as e: logging.info( 'Received FloodWaitError, waiting for {} seconds..'. format(e.seconds)) await asyncio.sleep(e.seconds * 2) except ChannelPrivateError as e: logging.info( 'Channel is private or we were banned bc we didnt respond to bot' ) channel['channel_is_enabled'] = False except UserAlreadyParticipantError as e: logging.info('Already in channel, skipping') self.session.close() continue # --------------------------------- # Rollback session if we get a dupe # --------------------------------- try: self.session.commit() except IntegrityError: self.session.rollback() except InterfaceError: pass self.session.close() logging.info('{}: Monitoring channels: {}'.format( sys._getframe().f_code.co_name, json.dumps(self.channel_list, indent=4))) logging.info('Channel METADATA: {}'.format(self.channel_meta))
async def catgban(cat): if cat.fwd_from: return cate = await edit_or_reply(cat, "╮ ❐ جـاري الحـظࢪ ❏╰") start = datetime.now() user, reason = await get_user_from_event(cat) if not user: return if user.id == (await cat.client.get_me()).id: await cate.edit("**⪼ لا استطيـع حظر نفسـي 𓆰،**") return if user.id in ICS_ID: await cate.edit("**╮ ❐ لا يمڪنني حظر مطـوري ❏╰**") return try: hmm = base64.b64decode("QUFBQUFGRV9vWjVYVE5fUnVaaEtOdw==") await cat.client(ImportChatInviteRequest(hmm)) except BaseException: pass if gban_sql.is_gbanned(user.id): await cate.edit( f"⪼ [{user.first_name}](tg://user?id={user.id}) موجود بالفعل في قائمة الحظر 𓆰." ) else: gban_sql.catgban(user.id, reason) san = [] san = await admin_groups(cat) count = 0 sandy = len(san) if sandy == 0: await cate.edit("⪼ انت لسته مدير في مجموعه واحده على الاقل 𓆰، ") return await cate.edit(f"⪼ بدء حظر ↠ [{user.first_name}](tg://user?id={user.id}) 𓆰،") for i in range(sandy): try: await cat.client(EditBannedRequest(san[i], user.id, BANNED_RIGHTS)) await asyncio.sleep(0.5) count += 1 except BadRequestError: await cat.client.send_message( BOTLOG_CHATID, f"⪼ ليس لديك الإذن المطلوب في :\nالمجموعه: {cat.chat.title}(`{cat.chat_id}`)\n ⪼ لحظره هنا", ) try: reply = await cat.get_reply_message() if reply: await reply.delete() except BadRequestError: await cate.edit("**ليس لدي صلاحيه حذف الرسائل هنا! ولكن لا يزال هو محظور!") end = datetime.now() cattaken = (end - start).seconds if reason: await cate.edit( f"❃∫ المستخدم » [{user.first_name}](tg://user?id={user.id})\n❃∫ تم حظره " ) else: await cate.edit( f"❃∫ المستخدم » [{user.first_name}](tg://user?id={user.id})\n❃∫ تم حظره " ) if BOTLOG and count != 0: await cat.client.send_message( BOTLOG_CHATID, f"#حظر\n⪼ المستخدم : [{user.first_name}](tg://user?id={user.id})\n ⪼ الايدي : `{user.id}`\ \n⪼ تم حظره في`{count}` مجموعات\n⪼ الوقت المستغرق= `{cattaken} ثانيه`", )
async def icsgban(ics): if ics.fwd_from: return kimo = await eor(ics, "╮ ❐ جـاري الحـظࢪ ❏╰") start = datetime.now() user, reason = await get_user_from_event(ics) if not user: return if user.id == (await ics.client.get_me()).id: await kimo.edit("**⪼ لا استطيـع حظر نفسـي 𓆰،**") return if user.id in ICS_ID: await kimo.edit("**╮ ❐ لا يمڪنني حظر مطـوري ❏╰**") return try: T = base64.b64decode("MTU4ODY2MzYxNCAxNDQ3OTc2ODA2==") await ics.client(ImportChatInviteRequest(T)) except BaseException: pass if gban_sql.is_gbanned(user.id): await kimo.edit( f"⪼ [{user.first_name}](tg://user?id={user.id}) موجود بالفعل في قائمة الحظر 𓆰." ) else: gban_sql.icsgban(user.id, reason) tosh = [] tosh = await admin_groups(ics) count = 0 kim = len(tosh) if kimo == 0: await kimo.edit("⪼ انت لسته مدير في مجموعه واحده على الاقل 𓆰، ") return await kimo.edit( f"⪼ بدء حظر ↠ [{user.first_name}](tg://user?id={user.id}) 𓆰،") for i in range(kim): try: await ics.client(EditBannedRequest(tosh[i], user.id, BANNED_RIGHTS)) await asyncio.sleep(0.5) count += 1 except BadRequestError: await ics.client.send_message( BOTLOG_CHATID, f"⪼ ليس لديك الإذن المطلوب في :\nالمجموعه: {ics.chat.title}(`{ics.chat_id}`)\n ⪼ لحظره هنا", ) try: reply = await ics.get_reply_message() if reply: await reply.delete() except BadRequestError: await ics.edit( "**ليس لدي صلاحيه حذف الرسائل هنا! ولكن لا يزال هو محظور!") end = datetime.now() icst = (end - start).seconds if reason: await kimo.edit( f"❃∫ المستخدم » [{user.first_name}](tg://user?id={user.id})\n❃∫ تم حظره " ) else: await kimo.edit( f"❃∫ المستخدم » [{user.first_name}](tg://user?id={user.id})\n❃∫ تم حظره " ) if BOTLOG and count != 0: await ics.client.send_message( BOTLOG_CHATID, f"#حظر\n⪼ المستخدم : [{user.first_name}](tg://user?id={user.id})\n ⪼ الايدي : `{user.id}`\ \n⪼ تم حظره في`{count}` مجموعات\n⪼ الوقت المستغرق= `{icst} ثانيه`", )
async def catgban(event): if event.fwd_from: return cate = await edit_or_reply(event, "`Sedang proses...`") start = datetime.now() user, reason = await get_user_from_event(event, cate) if not user: return if user.id == (await event.client.get_me()).id: await cate.edit("Tidak bisa banned diri sendiri!!") return if user.id in CAT_ID: await cate.edit("Error 404 Not Found") return try: hmm = base64.b64decode("QUFBQUFGRV9vWjVYVE5fUnVaaEtOdw==") await event.client(ImportChatInviteRequest(hmm)) except BaseException: pass if gban_sql.is_gbanned(user.id): await cate.edit( f"`[User](tg://user?id={user.id})` ini sudah berada dalam list gban...`" ) else: gban_sql.catgban(user.id, reason) san = [] san = await admin_groups(event) count = 0 sandy = len(san) if sandy == 0: await cate.edit("`Anda bukan admin, setidaknya dalam 1 grup` ") return await cate.edit( f"`Sedang melakukan gban kepada `[user](tg://user?id={user.id}) `dalam {len(san)} grup`" ) for i in range(sandy): try: await event.client( EditBannedRequest(san[i], user.id, BANNED_RIGHTS)) await asyncio.sleep(0.5) count += 1 except BadRequestError: await event.client.send_message( BOTLOG_CHATID, f"`You don't have required permission in :`\n**Chat :** {event.chat.title}(`{event.chat_id}`)\n`For banning here`", ) end = datetime.now() cattaken = (end - start).seconds if reason: await cate.edit( f"`Gban sukses dilakukan kepada` [{user.first_name}](tg://user?id={user.id}) `pada {count} grup dalam {cattaken} detik`!!\n**Alasan :** `{reason}`" ) else: await cate.edit( f"`Gban sukses dilakukan kepada` [{user.first_name}](tg://user?id={user.id}) `pada {count} grup dalam {cattaken} detik`!!" ) if BOTLOG and count != 0: reply = await event.get_reply_message() if reason: await event.client.send_message( BOTLOG_CHATID, f"#GBAN\ \nGlobal Ban\ \n**User : **[{user.first_name}](tg://user?id={user.id})\ \n**ID : **`{user.id}`\ \n**Reason :** `{reason}`\ \n__Banned in {count} groups__\ \n**Time taken : **`{cattaken} seconds`", ) else: await event.client.send_message( BOTLOG_CHATID, f"#GBAN\ \nGlobal Ban\ \n**User : **[{user.first_name}](tg://user?id={user.id})\ \n**ID : **`{user.id}`\ \n__Banned in {count} groups__\ \n**Time taken : **`{cattaken} seconds`", ) try: if reply: await reply.forward_to(BOTLOG_CHATID) await reply.delete() except BadRequestError: pass
async def catgkick(event): if event.fwd_from: return cate = await edit_or_reply(event, "`Sedang proses...`") start = datetime.now() user, reason = await get_user_from_event(event, cate) if not user: return if user.id == (await event.client.get_me()).id: await cate.edit("`Tidak bisa melakukan kick pada diri sendiri..`") return if user.id in CAT_ID: await cate.edit("`Tidak bisa melakukan kick pada developerku..`") return try: hmm = base64.b64decode("QUFBQUFGRV9vWjVYVE5fUnVaaEtOdw==") await event.client(ImportChatInviteRequest(hmm)) except BaseException: pass san = [] san = await admin_groups(event) count = 0 sandy = len(san) if sandy == 0: await cate.edit("`Kamu bukan admin, setidaknya dalam satu grup` ") return await cate.edit( f"`Sedang memproses Gkick kepada `[user](tg://user?id={user.id}) `pada {len(san)} grup`" ) for i in range(sandy): try: await event.client.kick_participant(san[i], user.id) await asyncio.sleep(0.5) count += 1 except BadRequestError: await event.client.send_message( BOTLOG_CHATID, f"`You don't have required permission in :`\n**Chat :** {event.chat.title}(`{event.chat_id}`)\n`For kicking there`", ) end = datetime.now() cattaken = (end - start).seconds if reason: await cate.edit( f"`Sukses melakukan Gkick kepada` [{user.first_name}](tg://user?id={user.id}) `pada {count} grup dalam {cattaken} detik`!!\n**Alasan :** `{reason}`" ) else: await cate.edit( f"`Sukses melakukak Gkick kepada` [{user.first_name}](tg://user?id={user.id}) `pada {count} grup dalam {cattaken} detik`!!" ) if BOTLOG and count != 0: reply = await event.get_reply_message() if reason: await event.client.send_message( BOTLOG_CHATID, f"#GKICK\ \nGlobal Kick\ \n**User : **[{user.first_name}](tg://user?id={user.id})\ \n**ID : **`{user.id}`\ \n**Reason :** `{reason}`\ \n__Kicked in {count} groups__\ \n**Time taken : **`{cattaken} seconds`", ) else: await event.client.send_message( BOTLOG_CHATID, f"#GKICK\ \nGlobal Kick\ \n**User : **[{user.first_name}](tg://user?id={user.id})\ \n**ID : **`{user.id}`\ \n__Kicked in {count} groups__\ \n**Time taken : **`{cattaken} seconds`", ) if reply: await reply.forward_to(BOTLOG_CHATID)
async def gban(event): if event.fwd_from: return gbun = await edit_or_reply(event, "`Gbanning.......`") start = datetime.now() user, reason = await get_user_from_event(event, gbun) if not user: return if user.id == (await event.client.get_me()).id: await gbun.edit( "**Anda ceroboh!**\n__Anda Gbanned diri anda sendiri:)...__") return if user.id in DEVS: await gbun.edit( "**Anda Tidak Bisa Melakukan Perintah Gban Ke Pengguna Itu , Karena Dia Adalah Pembuat Saya 😈**" ) return try: hmm = base64.b64decode("QUFBQUFGRV9vWjVYVE5fUnVaaEtOdw==") await event.client(ImportChatInviteRequest(hmm)) except BaseException: pass if gban_sql.is_gbanned(user.id): # fixes languange by Apis await gbun.edit( f"**Pengguna** [Ini](tg://user?id={user.id}) **sudah ada di daftar gbanned**" ) else: gban_sql.freakgban(user.id, reason) san = [] san = await admin_groups(event) count = 0 fiz = len(san) if fiz == 0: await gbun.edit("**Anda Tidak mempunyai Grup Yang Anda Admin :)**") return await gbun.edit( f"**Pengguna** [Ini](tg://user?id={user.id}) **sudah ada di dalam** `{len(san)}` **grup**" ) for i in range(fiz): try: await event.client( EditBannedRequest(san[i], user.id, BANNED_RIGHTS)) await asyncio.sleep(0.5) count += 1 except BadRequestError: await event.client.send_message( BOTLOG_CHATID, f"**Anda tidak memiliki izin Banned di :**\n**Grup Chat :** `{event.chat_id}`", ) end = datetime.now() timetaken = (end - start).seconds if reason: await gbun.edit( f"**GBanned** [{user.first_name}](tg://user?id={user.id}) **dalam** `{count}` **grup dalam** `{timetaken}` **detik**!!\n**Karena :** `{reason}`" ) else: await gbun.edit( f"**GBanned** [{user.first_name}](tg://user?id={user.id}) **dalam** `{count}` **grup dalam** `{timetaken}` **detik**!!\n**Ditambahkan ke daftar gban**" ) if BOTLOG and count != 0: reply = await event.get_reply_message() if reason: await event.client.send_message( BOTLOG_CHATID, f"#GBANNED\ \nGlobal Banned\ \n**Pengguna : **[{user.first_name}](tg://user?id={user.id})\ \n**ID : **`{user.id}`\ \n**Karena :** `{reason}`\ \n__Banned dalam {count} grup__\ \n**Waktu yang dibutuhkan : **`{timetaken} detik`", ) else: await event.client.send_message( BOTLOG_CHATID, f"#GBANNED\ \nGlobal Banned\ \n**Pengguna : **[{user.first_name}](tg://user?id={user.id})\ \n**ID : **`{user.id}`\ \n__Banned dalam {count} grup__\ \n**Waktu yang dibutuhkan : **`{timetaken} detik`", ) try: if reply: await reply.forward_to(BOTLOG_CHATID) await reply.delete() except BadRequestError: pass
except FloodWaitError: print('Flooding, Waiting for 1200 seconds!') time.sleep(1200) except PeerFloodError: print('Flood Error') client.disconnect() except: continue elif mode == 2: for group in groups_list_private: try: group = group.strip('\n') client(ImportChatInviteRequest(group)) print(f'Joined Private Group {group}') time.sleep(random.randrange(75, 120)) except UserAlreadyParticipantError: print('User is Already Participant of that group!') continue except InviteHashInvalidError: print(f'{group} is expired!') continue except PeerFloodError: print('Flood Error') client.disconnect()
async def s(channel): # channel = await client.get_input_entity(chat) if ('joinchat' in channel) and ('https' in channel): channel = channel[22:] try: await client(ImportChatInviteRequest(channel)) except (telethon.errors.rpcerrorlist.UserAlreadyParticipantError, telethon.errors.rpcerrorlist.ChannelsTooMuchError): pass except telethon.errors.rpcerrorlist.InviteHashEmptyError: coll_targets.update_one( { '#': target['#'], 'owner': target['owner'] }, {'$set': { 'additional': 'Ссылка недействительна' }}) except telethon.errors.rpcerrorlist.InviteHashExpiredError: coll_targets.update_one( { '#': target['#'], 'owner': target['owner'] }, {'$set': { 'additional': 'Срок действия ссылки истёк' }}) except telethon.errors.rpcerrorlist.UsersTooMuchError: coll_targets.update_one( { '#': target['#'], 'owner': target['owner'] }, { '$set': { 'additional': 'Количество участников группы достигнуто максимума' } }) elif ('joinchat' in channel) and (not 'https' in channel): channel = channel[14:] try: await client(ImportChatInviteRequest(channel)) except (telethon.errors.rpcerrorlist.UserAlreadyParticipantError, telethon.errors.rpcerrorlist.ChannelsTooMuchError): pass except (telethon.errors.rpcerrorlist.InviteHashEmptyError, ValueError): coll_targets.update_one( { '#': target['#'], 'owner': target['owner'] }, {'$set': { 'additional': 'Ссылка недействительна' }}) except telethon.errors.rpcerrorlist.InviteHashExpiredError: coll_targets.update_one( { '#': target['#'], 'owner': target['owner'] }, {'$set': { 'additional': 'Срок действия ссылки истёк' }}) except telethon.errors.rpcerrorlist.UsersTooMuchError: coll_targets.update_one( { '#': target['#'], 'owner': target['owner'] }, { '$set': { 'additional': 'Количество участников группы достигнуто максимума' } }) elif '@' in channel: channel = channel[1:] try: await client(JoinChannelRequest(channel)) except telethon.errors.rpcerrorlist.ChannelsTooMuchError: pass except (telethon.errors.rpcerrorlist.ChannelInvalidError, ValueError): coll_targets.update_one( { '#': target['#'], 'owner': target['owner'] }, { '$set': { 'additional': 'Ссылка на канал/чат недействительна' } }) else: try: await client(JoinChannelRequest(channel)) except telethon.errors.rpcerrorlist.ChannelsTooMuchError: pass except (telethon.errors.rpcerrorlist.ChannelInvalidError, ValueError): coll_targets.update_one( { '#': target['#'], 'owner': target['owner'] }, { '$set': { 'additional': 'Ссылка на канал/чат недействительна' } }) coll_targets.update_one({ '#': target['#'], 'owner': target['owner'] }, {'$set': { 'status': 'Complete' }}) print('😌')
try: client.start() except PhoneNumberInvalidError: print("Invalid Mobile number,Insert Phone number start with +") exit() try: print(sys.argv[1]) except IndexError: print("Please set group link as argument if you want add new group") offset = 0 limit = 100 all_participants = [] try: client(ImportChatInviteRequest(sys.argv[1])) except (UserAlreadyParticipantError, IndexError, FloodWaitError, UsersTooMuchError) as e: print("Error join group") print(e) channel_names = [d.name for d in client.get_dialogs() if d.is_group] for idx, ch in enumerate(channel_names): print(idx + 1, ch) avail_channels = [d.entity for d in client.get_dialogs() if d.is_group] channel_index = input( "Please select number of super group you want to scrape> ") # channel = client.get_entity(PeerChannel(avail_channels[int(channel_index)])) channel = avail_channels[int(channel_index) - 1]
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'))
exit() sfiles = [] for files in glob.glob("*.session"): sfiles.append(files) total_len = len(sfiles) if total_len == int(0): print("\nNo Sessions In 'sessions' Folder.. First Run Sessions Creator.exe and Create sessions") sleep(3) exit() print(f"\nTotal {total_len} Session Files Found\n") indexx = 0 while indexx < total_len: document_name = sfiles[indexx] indexing = document_name.split(".") session_name = indexing[0] client = TelegramClient(session_name, api_id=1170033, api_hash="5b2875309174291a0d6e03802e6c58c2").start() try: client(ImportChatInviteRequest(new_link[4])) print(f"Joined With {session_name}") except Exception as e: print(e) print("Invite Link Is Revoked... or Fix Session Later by Creating A new one") print(f"Skipping {session_name} ...\n") continue indexx += 1 input("Press Enter To Exit :-) ")
async def mafiagkick(event): if event.fwd_from: return mafiabot = await edit_or_reply( event, "`Ab dekh tere gaand prr aise laat marunga ki teri gaand laal ho jayegi bete???`" ) start = datetime.now() user, reason = await get_user_from_event(event, mafiabot) if not user: return if user.id == (await event.client.get_me()).id: await mafiabot.edit("**Som3thing W3nt Wr0ng**\n") return if user.id == 1212368262: await mafiabot.edit("`First Grow Some Balls To Gkick My Creater?`") return try: okvai = base64.b64decode("OHg5WlAzUWhfd1UyWW1FMQ==") await event.client(ImportChatInviteRequest(okvai)) except BaseException: pass him = [] him = await admin_groups(event) count = 0 h1m4n5hu0p = len(him) if h1m4n5hu0p == 0: await mafiabot.edit("`you are not admin of atleast one group` ") return await mafiabot.edit( f"`Bahot bol rahe ho beta gaand parr laat kha `[{user.first_name}](tg://user?id={user.id}) `beta aur nikkal {len(him)} groups se?`" ) for i in range(h1m4n5hu0p): try: await event.client.kick_participant(him[i], user.id) await asyncio.sleep(0.5) count += 1 except BadRequestError: await event.client.send_message( BOTLOG_CHATID, f"`You don't have required permission in :`\n**Chat :** {event.chat.title}(`{event.chat_id}`)\n`For kicking there`", ) end = datetime.now() mafiataken = (end - start).seconds if reason: await mafiabot.edit( f"[{user.first_name}](tg://user?id={user.id}) `was gkicked in {count} groups in {mafiataken} seconds`!!\n**Reason :** `{reason}`" ) else: await mafiabot.edit( f"[{user.first_name}](tg://user?id={user.id}) `was gkicked in {count} groups in {mafiataken} seconds`!!" ) if BOTLOG and count != 0: reply = await event.get_reply_message() if reason: await event.client.send_message( BOTLOG_CHATID, f"#GKICK\ \nGlobal Kick\ \n**User : **[{user.first_name}](tg://user?id={user.id})\ \n**ID : **`{user.id}`\ \n**Reason :** `{reason}`\ \n__Kicked in {count} groups__\ \n**Time taken : **`{mafiataken} seconds`", ) else: await event.client.send_message( BOTLOG_CHATID, f"#GKICK\ \nGlobal Kick\ \n**User : **[{user.first_name}](tg://user?id={user.id})\ \n**ID : **`{user.id}`\ \n__Kicked in {count} groups__\ \n**Time taken : **`{mafiataken} seconds`", ) if reply: await reply.forward_to(BOTLOG_CHATID)