def run(self): """ Dumps all desired chat messages into a file """ # Resolve chat name into id peer = self(ResolveUsernameRequest(self.settings.chat_name)) if peer.chats is None or not peer.chats: raise ValueError('Error: failed to resolve chat name into chat_id') chat = peer.chats[0] sprint('Chat name @{} resolved into channel id={}'.format( self.settings.chat_name, chat.id)) # Dump history to file count = self.dump_messages_in_file(chat) if self.settings.is_clean: try: # TODO self.log_out() sprint('Session data cleared.') # pylint: disable=broad-except except Exception: sprint('Error: failed to log-out.') sprint( '{} messages were successfully written in resulting file. Done!'. format(count))
def run(self): # Resolve chat name into id peer = self(ResolveUsernameRequest(self.settings.chat_name)) if (peer.chats is None or len(peer.chats) == 0) and (peer.users is None or len(peer.users) == 0): raise ValueError( 'Error: failed to resolve chat name into chat_id or user') if len(peer.chats) == 0: chat = peer.users[0] else: chat = peer.chats[0] sprint('Chat name @{} resolved into id={}'.format( self.settings.chat_name, chat.id)) # Dump history to file count = self.dump_messages_in_file(chat) if self.settings.is_clean: # noinspection PyBroadException try: self.log_out() sprint('Session data cleared.') except: sprint('Error: failed to log-out.') sprint( '{} messages were successfully written in resulting file. Done!'. format(count))
def checkCurChat(chatname, client): print("\n") try: int_chat = int(chatname) except: int_chat = 0 if int_chat != 0: input_channel = client(GetFullChannelRequest(int_chat)) channel_id = input_channel.full_chat.id channel = int_chat print("<<<Fast checking: " + input_channel.chats[0].title + " (" + str(int_chat) + ">>>") else: response = client.invoke(ResolveUsernameRequest(chatname)) channel_id = response.peer.channel_id channel = chatname print("<<<Fast checking: " + response.chats[0].title + " (" + response.chats[0].username + ") >>>") for msg in client.get_messages(channel_id, limit=1): if (msg != '') and not (msg is None): if not hasattr(msg, 'text'): msg.text = None if msg.text is None and hasattr(msg, 'entities'): msg.text = markdown.unparse(msg.message, msg.entities or []) if msg.text is None and msg.message: msg.text = msg.message textCheck(msg.text, False, 1, client) return channel
def isUserJoined(self, userID, channelName): try: LIMIT = 200 channel = self.client(ResolveUsernameRequest(channelName)).chats[0] offset = 0 output = [] while True: participants = self.client( GetParticipantsRequest(channel, ChannelParticipantsSearch(''), offset, LIMIT, hash=0)) if not participants.users: break offset += len(participants.users) for user in participants.users: if userID == user.id: return True return False except Exception as e: return 0
def add(bot, update, args): chat_id = update.message.chat_id bot.sendChatAction(chat_id, "TYPING") if args[0] not in channel_list: channel_list.append(args[0]) try: response_add = client.invoke(ResolveUsernameRequest(args[0])) messages_add = client.get_messages(response_add.peer, limit=3000) for message in messages_add: this_url = 't.me/' + args[0] + '/' + str(message.id) try: splitted = re.split(r"[\W']+", str(message.message)) for word in splitted: if word.lower() in dictionary: dictionary[word.lower()].append(this_url) else: dictionary[word.lower()] = this_url.split() except AttributeError: pass except: bot.sendMessage(chat_id, 'آدرس کانال وارد شده اشتباه می باشد.لطفا نام کانال را بدون @ وارد کنید.') else: bot.sendMessage(chat_id, 'کانال درخواستی شما به ربات اضافه گردید.') else: bot.sendMessage(chat_id, 'کانال مورد نظر در مخازن ربات موجود می باشد.')
def t_member_leech(request, username=None): if username: t_client = TinClient.getConnection(type=TinClient.TELEGRAM) result = t_client(ResolveUsernameRequest( username[1:].strip())) if username.startswith("@") else t_client( ResolveUsernameRequest(username.strip())) if len(result.users) > 0: user = result.users[0] return JsonResponse({ 'msg': 'success', 'tuser': { "first_name": user.first_name, "id": user.id, "username": user.username, "last_name": user.last_name } }) else: return JsonResponse({'msg': 'Invalid Username'}, safe=False) elif request.method == "POST": member = Member.objects.filter(member_id=request.POST['member_id'], type=Member.TELEGRAM).first() log.warning(member) if member is None: member = Member.objects.update_or_create( member_id=request.POST['member_id'], first_name=request.POST['first_name'], last_name=request.POST['last_name'], username=request.POST['username'], type=Member.TELEGRAM, is_blacklisted=False) try: Leech.objects.create(member=member, group=Group(id=request.POST['group_id'])) Defaulter.objects.filter( member=member, group=Group(id=request.POST['group_id'])).delete() except IntegrityError as err: return JsonResponse({'msg': 'Something went wrong'}, safe=False) return JsonResponse({ 'msg': 'success', }) return JsonResponse({'msg': 'Invalid Username'}, safe=False)
def removeUser(client, username, channel_id=DEFAULT_CHANNEL): try: msg = removeUser_by_user(client, user=client(ResolveUsernameRequest(username)).users[0], channel_id=channel_id) except Exception as err: msg = "Attempt to kicked user @{} from channel ({}) failed. Confirm the username is valid".format(username, channel_id) log.error(msg) log.error(err) return msg
def addUser(client, username, channel_id=DEFAULT_CHANNEL): try: user = client(ResolveUsernameRequest(username)) return add_user_by_id(client, user_id=user.users[0].id, channel_id=channel_id) except Exception as err: msg = "Add User @{} attempt to channel ({}) failed. Confirm the username is valid".format(username, channel_id) log.error(msg) log.error(err) return msg
async def run(self): await self.tg_client.connect() await self.tg_client.start() for ch_id in self.config["telegram"]["channels"]: result = await self.tg_client(ResolveUsernameRequest(ch_id)) channel = InputChannel(result.peer.channel_id, result.chats[0].access_hash) await self.tg_client(JoinChannelRequest(channel)) self.tg_client.add_event_handler(self._tg_event_handler) logging.info("Bot has been started") await self.tg_client.run_until_disconnected()
async def get_group_from_link(self, link): link_id = link.split("/")[-1] chat_grp = None if "joinchat" in link: chat_grp = await self.client(CheckChatInviteRequest(hash=link_id)) else: chat_grp = await self.client( ResolveUsernameRequest(username=link_id)) chat_grp = chat_grp.chats[0] return chat_grp
def get_tg(): client = TelegramClient('fetcher-session', config.api_id, config.api_hash) client.connect() if not client.is_user_authorized(): client.sign_in(phone=config.phone) client.sign_in(code=int(input('Enter code: '))) channel = client(ResolveUsernameRequest(config.channel)).chats[0] return client, channel
def get_chat_info(username, client): try: chat = client(ResolveUsernameRequest(username)) except UsernameNotOccupiedError: print('Chat/channel not found!') sys.exit() result = { 'chat_id': chat.peer.channel_id, 'access_hash': chat.chats[0].access_hash } return result
def get_users(group_username): users_list = [] channel = client(ResolveUsernameRequest(group_username)) offset_counter = 0 while True: users = client(GetParticipantsRequest(InputChannel(channel.peer.channel_id, channel.chats[0].access_hash), limit=200, offset=offset_counter, filter=ChannelParticipantsRecent())) if len(users.participants) == 0: break offset_counter += 200 users_list.extend(users.users) time.sleep(5) return users_list
def get_telegram_usernames(write_results=True): print('Fetching telegram followers... This may take a few minutes') api_id = config['TELEGRAM']['ID'] # Your api_id api_hash = config['TELEGRAM']['HASH'] # Your api_hash phone_number = config['TELEGRAM']['PHONE'] # Your phone number client = TelegramClient(phone_number, api_id, api_hash) client.session.report_errors = False client.connect() # will need to enter code from message if session is not active if not client.is_user_authorized(): client.send_code_request(phone_number) client.sign_in(phone_number, input('Enter the code: ')) channel = client(ResolveUsernameRequest( config['TELEGRAM']['CHANNEL'])) # Your channel input_channel = InputChannel(channel.chats[0].id, channel.chats[0].access_hash) offset = 0 limit = 100 all_participants = [] # Can pull up to 10000 participants in one shot. Will need to filter if you have more users than that. while True: participants = client( GetParticipantsRequest(input_channel, ChannelParticipantsSearch(''), offset, limit, 0)) if not participants.users: break all_participants.extend(participants.users) offset += len(participants.users) print(offset) telegram_usernames = [] for participant in all_participants: if participant.username: telegram_usernames.append(participant.username.lower()) # telegram_usernames = [_user.username.lower() for _user in all_participants] if write_results: telegram_file = open('telegram_usernames.csv', 'w') telegram_writer = csv.writer(telegram_file, quoting=csv.QUOTE_ALL) for username in telegram_usernames: telegram_writer.writerow([username]) return telegram_usernames
def checkCurchan(channel, client, signals_limit): chantitle = channel.title if not chantitle: chantitle = channel.name if not chantitle: chantitle = str(channel.id) global log if log: log.write("\n\n") log.write("------------------------------\n") log.write("BEGIN CHECKING CHANNEL: "+channel.title+" - " + channel.name +" - " + str(channel.id) + "\n") log.write("------------------------------\n") log.write("\n\n") channame = channel.name if not channame and channel.id != 0: int_chan = int(channel.id) else: int_chan = 0 if int_chan != 0: try: input_channel = client(GetFullChannelRequest(int_chan)) channel_id = input_channel.full_chat.id except Exception as e: print(str(e)) return None else: try: response = client.invoke(ResolveUsernameRequest(channame)) channel_id = response.peer.channel_id except Exception as e: print(str(e)) return None if signals_limit > 0: for msg in client.get_messages(channel_id, limit=signals_limit): if (msg != '') and not (msg is None): if not hasattr(msg, 'text'): msg.text = None if msg.text is None and hasattr(msg, 'entities'): msg.text = markdown.unparse(msg.message, msg.entities or []) if msg.text is None and msg.message: msg.text = msg.message separateCheck(msg.text, chantitle, channel.rating, dateFix(msg.date), client) return client.get_input_entity(channel_id)
def getId(client, chatName, limit, debug=False): #Checking for not existing try: resolve = client(ResolveUsernameRequest(chatName)) except UsernameInvalidError: print("Incorrect name of chat! Try again.") return False except UsernameNotOccupiedError: print("Incorrect name of chat! Try again.") return False #Checking for chat or no try: access_hash = resolve.chats[0].access_hash chat_id = resolve.chats[0].id except IndexError: print("It's not a chat!") return False input_channel = InputChannel(chat_id, access_hash) filter = ChannelParticipantsSearch('') offset = 0 hash = 0 allId = [] #Checking for channel/private chat try: client( GetParticipantsRequest(input_channel, filter, offset, limit, hash)) except ChatAdminRequiredError: print('It is channel/private chat!') return False count = 0 while True: if count == limit: break part = client( GetParticipantsRequest(input_channel, filter, offset, limit, hash), ) if not part.users: break allId.append(part.users[count].id) count += 1 offset += 1 print('{}/{}'.format(count, limit), end='\r') if debug: print(part.users[count].id) return allId
def get_chat_info(self, username): """ Функция для получения информации о чате :param username: имя пользователя :return: словарь c chat_id и access_hash """ try: chat = self.client(ResolveUsernameRequest(username)) except UsernameNotOccupiedError: print('Chat/channel not found!') sys.exit() result = { 'chat_id': chat.peer.channel_id, 'access_hash': chat.chats[0].access_hash } return result
async def async_get_channel_msgs(channel_name, limit=3, offset_id=0, offset_date=None, max_id=0, min_id=0): channel = redis_utils.get_channel(channel_name) if not channel: channel = await client(ResolveUsernameRequest(channel_name)) redis_utils.save_channel(channel_name, channel) result = await client( messages.GetHistoryRequest(peer=channel, limit=limit, offset_id=offset_id, offset_date=offset_date, add_offset=0, max_id=max_id, min_id=min_id, hash=0)) return result
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
# Bot settings token = "<botapi_token>" bot_id = token.split(":")[0] chat_username = "******" sorry_message = "Hello, {}! You were excluded from the conversation due to {} daytime inactivity. If you still want to be in the group, come back: @{}. You can here apply for disabling auto-kick you." admin_id = <admin_id> time_by = 1 # days bot = telebot.TeleBot(token) while not client.is_user_authorized(): client.send_code_request(telethon_account) bot.send_message(admin_id, "Read-only filtering bot waiting authorization. Enter confirmation code in bot console.") # TODO: Make less security by entering code in bot client.sign_in(telethon_account, input("CODE: ")) # Chat id chat_id = client(ResolveUsernameRequest(chat_username)).peer.channel_id if not os.path.isfile("messages.db"): conn = sqlite3.connect('messages.db', check_same_thread=False, timeout=2) cursor = conn.cursor() cursor.execute('CREATE TABLE messages (id INTEGER PRIMARY KEY, last_date DATETIME, ignore BOOL)') conn.commit() print("[i] Create database.") else: conn = sqlite3.connect('messages.db', check_same_thread=False, timeout=2) cursor = conn.cursor() def bot_chat_id(chat_id): return int("-100" + str(chat_id)) def check_chat(message):
from telethon import TelegramClient from telethon.tl.functions.contacts import ResolveUsernameRequest #this fields should be provided from my.telgram.com api_id = api_hash = client = TelegramClient('session_name', api_id, api_hash) client.start() print('started') # print(client.get_me().stringify()) dictionary = {} channel_list = ['ebookonline', 'YarAmoozan', 'eng_books', 'bestsellers_book', 'dl_ketab', 'ketabkhanichanel'] for channel_name in channel_list: response = client.invoke(ResolveUsernameRequest(channel_name)) messages = client.get_messages(response.peer, limit=3000) # print(messages[0].stringify()) for message in messages: this_url = 't.me/' + channel_name + '/' + str(message.id) try: splitted = re.split(r"[\W']+", str(message.message)) for word in splitted: if word.lower() in dictionary: dictionary[word.lower()].append(this_url) else: dictionary[word.lower()] = this_url.split() except AttributeError: pass
from telethon.tl.types import ChannelAdminLogEventsFilter from telethon.tl.types import InputUserSelf from telethon.tl.types import InputUser api_id = 1135557 api_hash = 'b00c96e8406d2d404d353394cd90f05a' phone = '+918299446752' 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]
def get_channel_users(channel_name): result = [] offset = 0 limit = 100 channel = client(ResolveUsernameRequest(channel_name)) while True: participants = client( GetParticipantsRequest(channel, ChannelParticipantsSearch(''), offset, limit, hash=0)) if not participants.users: break for _user in participants.users: if type(_user.status) is UserStatusOffline: result.append({ 'id': _user.id, 'bot': _user.bot, 'status': _user.status.was_online.isoformat() }) elif type(_user.status) is UserStatusLastWeek: result.append({ 'id': _user.id, 'bot': _user.bot, 'status': 'week' }) elif type(_user.status) is UserStatusLastMonth: result.append({ 'id': _user.id, 'bot': _user.bot, 'status': 'month' }) elif type(_user.status) is UserStatusOffline: result.append({ 'id': _user.id, 'bot': _user.bot, 'status': 'offline' }) elif type(_user.status) is UserStatusOnline: result.append({ 'id': _user.id, 'bot': _user.bot, 'status': 'online' }) elif type(_user.status) is UserStatusRecently: result.append({ 'id': _user.id, 'bot': _user.bot, 'status': 'recently' }) else: result.append({ 'id': _user.id, 'bot': _user.bot, 'status': 'empty' }) offset += len(participants.users) return result
def handle(self, *args, **options): print("Started:", datetime.now()) telegram_api = TelegramApi() sys_sender_client = telegram_api.get_sys_sender_client() for user in User.objects.all(): print("user:"******"collection:", collection) try: sources = collection.source_set.all() sleep(1) destination_chan = telegram_api.get_dest_channel( user_client, sys_sender_client, collection.destination_data['id'], sources) except: continue for source in sources: try: try: src = Source.objects.get( id=source.id, last_fm_time__gt=datetime.now().timestamp() - 30, are_collecting=True) if src.are_collecting: continue else: source.are_collecting = True source.save() except: source.are_collecting = True source.save() print("source:", source) try: channel = telegram_api.get_channel( sys_sender_client, source.source_data['id']) except ValueError: sys_sender_client( ResolveUsernameRequest( source.source_data['username'])) channel = telegram_api.get_channel( sys_sender_client, source.source_data['id']) sleep(1) try: total, messages, senders = user_client.get_message_history( channel, limit=20) except ChannelInvalidError: try: print("ChannelInvalidError:", source.source_data['username']) user_client( ResolveUsernameRequest( source.source_data['username'])) total, messages, senders = user_client.get_message_history( channel, limit=20) except: source.are_collecting = False source.save() continue messages = messages[:: -1] # reversing list to be asc (because telegram desc mid) for msg in messages: if type(msg) is Message: if msg.date.timestamp( ) > source.last_fm_time.timestamp(): print("msg:", msg.id) sys_sender_client( ForwardMessagesRequest( from_peer=channel, id=[msg.id], to_peer=destination_chan, silent=True)) source.last_fm_time = msg.date source.last_fm_id = msg.id source.save() source.are_collecting = False source.save() except: source.are_collecting = False source.save() self.stdout.write("End of work!")
def resolve_username(self, username): result = self.invoke(ResolveUsernameRequest(username)) if result: return result else: return "Cannot resolve given username. Ensure provided username is valid."
def join_channel(channel_name): channel = client(ResolveUsernameRequest(channel_name)) client(JoinChannelRequest(channel)) return 0
async def EVENTER(event): event.original_update=event.original_update if type(event.original_update)is not UpdateShortMessage: if hasattr(event.original_update.message,'reply_markup')and type(event.original_update.message.reply_markup)is ReplyInlineMarkup: RQForm=MUFilter(event.original_update.message.reply_markup) if RQForm is not None: if MUFilterT(event.original_update.message.reply_markup) is None: if RFORMER2(RQForm).find('/vc/')>0: await event.message.click(2) else: print (num+"..rewarding\r") #ScreenMessage(Fore.GREEN+' Requesting reward') UravxBuCwNMpYWTzKhcy=20 CompteurSUC=0 while True: (RQCode,RQText)=RFORMER(RQForm) MFINDER=BeautifulSoup(RQText,'html.parser') cc=MFINDER.find('div',{'class':'g-recaptcha'}) tt=MFINDER.find('div',{'id':'headbar'}) if RQCode==302: print(num+"..ok\r") #sys.stdout.write(Fore.MAGENTA+'[%s] STATUS: %s (%d)\r'%(datetime.datetime.now().strftime("%H:%M:%S"),'FALSE' if cc is not None else 'TRUE',CompteurSUC)) break elif RQCode==200 and cc is None and tt is not None: TTCode=tt.get('data-code') TTime=tt.get('data-timer') TToken=tt.get('data-token') await event.message.click(2) #requests.post('http://bch.dogeclick.com/reward',data={'code':TTCode,'token':TToken},headers=BROWSER,allow_redirects=False) break elif RQCode==200 and cc is not None: await event.message.click(2) time.sleep(10) print(num+"..ok\r") #sys.stdout.write(Fore.MAGENTA+'[%s] STATUS: %s (%d)\r'%(datetime.datetime.now().strftime("%H:%M:%S"),'FALSE' if cc is not None else 'TRUE',CompteurSUC)) CompteurSUC+=1 time.sleep(3) elif MUFilterT(event.original_update.message.reply_markup) is True: print(num) if RFORMER2(RQForm).find('/jc/') >0: await event.message.click(3) else: username = RFORMER2(RQForm).replace('https://telegram.me/', '') try: papa = await event.client(ResolveUsernameRequest(username)) except FloodWaitError as e : await PROFILER.send_message('BitcoinClick_bot','/visit') return time.sleep(3) #VWate(e.seconds,num) except UsernameNotOccupiedError: await event.message.click(3) except UsernameInvalidError: await event.message.click(3) #papa = await event.client(ResolveUsernameRequest(username)) #ScreenMessage(Fore.BLUE+username) #sys.stdout.write(Fore.GREEN+'[%s]: %s (%s)\r'%(datetime.datetime.now().strftime("%H:%M:%S"),'Wait joining Channel', username)) try: await event.client(JoinChannelRequest(InputPeerChannel(papa.chats[0].id, papa.chats[0].access_hash))) except FloodWaitError as e: await PROFILER.send_message('BitcoinClick_bot','/visit') #VWate(e.seconds,num) #await event.client(JoinChannelRequest(InputPeerChannel(papa.chats[0].id, papa.chats[0].access_hash))) except ChannelsTooMuchError as c: await main() try: await event.client(JoinChannelRequest(InputPeerChannel(papa.chats[0].id, papa.chats[0].access_hash))) except ChannelsTooMuchError: await PROFILER.send_message('BitcoinClick_bot','/visit') except ChannelPrivateError: await event.message.click(1) await event.message.click(1) time.sleep(2) elif MUFilterT(event.original_update.message.reply_markup) is False: try: print(num+"..ok\r") #print(RFORMER2(RQForm)) await boter(RFORMER2(RQForm)) except UsernameNotOccupiedError: await event.message.click(2) except ChatWriteForbiddenError: await event.message.click(2) except StartParamInvalidError: await event.message.click(2) except ValueError: await event.message.click(2) time.sleep(2)
async def EVENTER(event): event.original_update = event.original_update if type(event.original_update) is not UpdateShortMessage: if (hasattr(event.original_update.message, 'reply_markup') and type(event.original_update.message.reply_markup) is ReplyInlineMarkup): RQForm = MUFilter( event.original_update.message.reply_markup) if RQForm is not None: if (MUFilterT( event.original_update.message.reply_markup) is None): ScreenMessage(Fore.GREEN + ' Requesting reward') UravxBuCwNMpYWTzKhcy = 20 CompteurSUC = 0 while True: (RQCode, RQText) = RFORMER(RQForm) MFINDER = BeautifulSoup(RQText, 'html.parser') cc = MFINDER.find('div', {'class': 'g-recaptcha'}) tt = MFINDER.find('div', {'id': 'headbar'}) if RQCode == 302: sys.stdout.write( Fore.MAGENTA + '[%s] STATUS: %s (%d)\r' % ( datetime.datetime.now().strftime( "%H:%M:%S"), 'FALSE' if cc is not None else 'TRUE', CompteurSUC, )) break elif RQCode == 200 and cc is None and tt is not None: TTCode = tt.get('data-code') TTime = tt.get('data-timer') TToken = tt.get('data-token') await event.message.click(2) break elif RQCode == 200 and cc is not None: await event.message.click(2) time.sleep(10) sys.stdout.write( Fore.MAGENTA + '[%s] STATUS: %s (%d)\r' % ( datetime.datetime.now().strftime( "%H:%M:%S"), 'FALSE' if cc is not None else 'TRUE', CompteurSUC, )) CompteurSUC += 1 time.sleep(3) elif (MUFilterT( event.original_update.message.reply_markup) is True): username = RQForm.replace('https://t.me/', '') papa = await event.client( ResolveUsernameRequest(username)) ScreenMessage(Fore.BLUE + username) sys.stdout.write(Fore.GREEN + '[%s]: %s (%s)\r' % ( datetime.datetime.now().strftime("%H:%M:%S"), 'Wait joining Channel', username, )) try: await event.client( JoinChannelRequest( InputPeerChannel( papa.chats[0].id, papa.chats[0].access_hash))) except FloodWaitError as e: VWate(e.seconds) await event.client( JoinChannelRequest( InputPeerChannel( papa.chats[0].id, papa.chats[0].access_hash))) except ChannelsTooMuchError as c: await main() await event.client( JoinChannelRequest( InputPeerChannel( papa.chats[0].id, papa.chats[0].access_hash))) except ChannelPrivateError: await event.message.click(1) await event.message.click(1) time.sleep(2) elif (MUFilterT( event.original_update.message.reply_markup) is False): try: await boter() except UsernameNotOccupiedError: await event.message.click(2) except ChatWriteForbiddenError: await event.message.click(2) except StartParamInvalidError: await event.message.click(2) except ValueError: await event.message.click(2) time.sleep(2)
def _get_channel(self): """ Returns telethon.tl.types.Channel object resolved from chat_name at Telegram server """ name = self.settings.chat_name # For private channels try to resolve channel peer object from its invitation link # Note: it will only work if the login user has already joined the private channel. # Otherwise, get_entity will throw ValueError if name.startswith(JOIN_CHAT_PREFIX_URL): self.logger.debug('Trying to resolve as invite url.') try: peer = self.get_entity(name) if peer: sprint('Invitation link "{}" resolved into channel id={}'. format(name, peer.id)) return peer except ValueError as ex: self.logger.debug( 'Failed to resolve "%s" as an invitation link. %s', self.settings.chat_name, ex, exc_info=self.logger.level > logging.INFO) if name.startswith('@'): name = name[1:] self.logger.debug('Trying ResolveUsernameRequest().') try: peer = self(ResolveUsernameRequest(name)) if peer.chats is not None and peer.chats: sprint('Chat name "{}" resolved into channel id={}'.format( name, peer.chats[0].id)) return peer.chats[0] if peer.users is not None and peer.users: sprint('User name "{}" resolved into channel id={}'.format( name, peer.users[0].id)) return peer.users[0] except (UsernameNotOccupiedError, UsernameInvalidError) as ex: self.logger.debug('Failed to resolve "%s" as @-chat-name. %s', self.settings.chat_name, ex, exc_info=self.logger.level > logging.INFO) # Search in dialogs first, this way we will find private groups and # channels. self.logger.debug('Fetch logged in user`s dialogs') dialogs_count = self.get_dialogs(0).total self.logger.info('%s user`s dialogs found', dialogs_count) dialogs = self.get_dialogs(limit=None) self.logger.debug('%s dialogs fetched.', len(dialogs)) for dialog in dialogs: if dialog.name == name: sprint('Dialog title "{}" resolved into channel id={}'.format( name, dialog.entity.id)) return dialog.entity if hasattr(dialog.entity, 'username') and dialog.entity.username == name: sprint( 'Dialog username "{}" resolved into channel id={}'.format( name, dialog.entity.id)) return dialog.entity if name.startswith('@') and dialog.entity.username == name[1:]: sprint( 'Dialog username "{}" resolved into channel id={}'.format( name, dialog.entity.id)) return dialog.entity self.logger.debug('Specified chat name was not found among dialogs.') raise ValueError( 'Failed to resolve dialogue/chat name "{}".'.format(name))
sys.exit(1) print(total) print(len(messages)) print(len(senders)) for i, m in enumerate(messages): print(m.stringify()) print(senders[i].stringify()) print(m.id) break # sys.exit(1) from telethon.tl.functions.contacts import ResolveUsernameRequest result = client(ResolveUsernameRequest('mp3downloads1')) print(result.stringify()) found_chats = result.chats found_users = result.users #print(found_chats) #print(found_users) # from telethon.tl.functions.messages import GetDialogsRequest # from telethon.tl.types import InputPeerEmpty # from time import sleep # dialogs = [] # users = [] # chats = []