"""Safe Print (handle UnicodeEncodeErrors on some terminals)""" try: print(string, *args, **kwargs) except UnicodeEncodeError: string = string.encode('utf-8', errors='ignore')\ .decode('ascii', errors='ignore') print(string, *args, **kwargs) #print(result) import codecs import pprint import sys import re messages = client.get_messages(client.get_input_entity(channel_name), limit=100) with codecs.open(file_name, "w", "utf-8") as stream: # or utf-8 stream.write(u"\n === \n") for msg in reversed(messages): try: found_media = {} content = "qwer" name = 'noname' if getattr(msg, 'media', None): found_media[msg.id] = msg content = '<{}> {}'.format(type(msg.media).__name__, msg.message) elif hasattr(msg, 'message'):
i = 0 print(len(adding_users)) while True: if idx >= len(adding_users): break if (i != 0) and (i % 50 == 0): client.disconnect() break adding_user = adding_users[idx] idx += 1 try: print("Adding {} {}".format(adding_user['id'], adding_user['username'])) if mode == 1: if adding_user['username'] == "": continue user_to_add = client.get_input_entity(adding_user['username']) # result = client(CheckUsernameRequest( # target_group_entity, # adding_user['username'] # )) # print("[CheckUsernameRequest]={}".format(result)) elif mode == 2: user_to_add = InputPeerUser(adding_user['id'], adding_user['access_hash']) else: sys.exit("Invalid Mode Selected. Please Try Again.") result = client(InviteToChannelRequest(target_group_entity, [user_to_add])) if len(result.users) > 0: i = i + 1 print(" *Adding success=[{}]".format(adding_user['username'])) else: print(" *Already exist or not added=[{}]".format(adding_user['username']))
args.session = args.session_file[:-8] tg = TelegramClient(args.session_file, args.api_id, args.api_hash, update_workers=0) ok = tg.connect() if not ok: raise SystemExit('Telegram connection error') if not tg.is_user_authorized(): raise SystemExit('You are not authorized') if args.channel_name: print('* subscribing to channel %s' % args.channel_name) try: entity = tg.get_input_entity(args.channel_name) tg(JoinChannelRequest(entity)) except Exception as ex: print('* Subscription error: %s' % ex) while True: try: print('* Waitng channels messages...') update = tg.updates.poll() if not update: continue if type(update) == UpdateNewChannelMessage: msg = update.message print('\n--- Channel Message ---') channel_id = msg.to_id.channel_id print('Channel:', tg.get_entity(PeerChannel(channel_id)).title)
messaggio = update.message.message if any(ord(char) > 127 for char in messaggio): client.delete_messages(update.message.to_id, [update.message.id]) if (isinstance(update.message, MessageService)): client.delete_messages(update.message.to_id, [update.message.id]) if (isinstance(update.message.action, MessageActionChatAddUser)): for boto in update.message.action.users: if (client.get_entity(boto).bot == True): client( EditBannedRequest( update.message.to_id, boto, banned_rights=ChannelBannedRights( until_date=0, view_messages=True))) client( DeleteUserHistoryRequest( client.get_input_entity( update.message.to_id), client.get_input_entity(boto))) print('I received', update) except KeyboardInterrupt: break while 1: time.sleep(10)
class BotChecker(object): def __init__(self, session_name, api_id, api_hash, phone_number, updater=None): self.phone_number = phone_number self.client = TelegramClient(session_name, api_id, api_hash, update_workers=4, spawn_read_thread=True, timeout=datetime.timedelta(seconds=15)) self.client.connect() self._pinged_bots = [] self._responses = {} self.botbuilders = [] if not self.client.is_user_authorized(): log.info("Sending code request...") self.client.send_code_request(phone_number) if updater: updater.bot.send_message(settings.ADMINS[0], CONFIRM_PHONE_CODE, reply_markup=ForceReply()) updater.dispatcher.add_handler(MessageHandler( Filters.reply & Filters.user(settings.ADMINS[0]), lambda bot, update: authorization_handler( bot, update, self)), group=3) self.pending_authorization = True else: self.client.send_code_request(phone_number) self.client.sign_in(phone_number, input('Enter code: ')) else: self._initialize() def reset(self): self._pinged_bots = [] self._responses = {} def authorize(self, code): self.client.sign_in(self.phone_number, code) self._initialize() def _initialize(self): self.pending_authorization = False self.client.add_update_handler(self._update_handler) def _update_handler(self, update): if update is None: log.error("Received `None` update.") return try: uid = update.message.from_id except AttributeError: try: uid = update.user_id except AttributeError: return # try: # entity = self.client.get_entity(uid) # log.debug("Received response from @{}".format(entity.username)) # except: if uid in self._pinged_bots: log.debug("Received update from pinged bot {}: {}".format( uid, type(update))) message_text = None try: message_text = update.message.message except AttributeError: try: message_text = update.message except AttributeError: pass self._responses[uid] = message_text def _init_thread(self, target, *args, **kwargs): thr = Thread(target=target, args=args, kwargs=kwargs) thr.start() def schedule_conversation_deletion(self, peer, delay=5): def inner(): time.sleep(delay) entity = self.client.get_input_entity(peer) self.client(DeleteHistoryRequest(entity, max_id=999999999)) log.debug("Deleted conversation with {}".format(entity)) thr = threading.Thread(target=inner, args=()) thr.start() def delete_all_conversations(self): all_peers = [ utils.resolve_id(x[0]) for x in self.client.session.entities.get_input_list() ] for peer in all_peers: log.debug("Deleting conversation with {}...".format(peer)) try: input_entity = self.client.session.entities.get_input_entity( peer[0]) self.client( DeleteHistoryRequest(input_entity, max_id=9999999999999999)) except: log.error("Couldn't find {}".format(peer[0])) def get_bot_entity(self, username) -> User: entity = self.client.get_entity(username) if not hasattr(entity, 'bot'): raise NotABotError("This user is not a bot.") time.sleep(45) # ResolveUsernameRequests are expensive return entity def get_bot_entity_by_id(self, chat_id) -> User: entity = self.client.get_entity(chat_id) if not hasattr(entity, 'bot'): raise NotABotError("This user is not a bot.") return entity def _response_received(self, bot_user_id): return bot_user_id in [k for k in self._responses.keys()] def _delete_response(self, bot_user_id): del self._responses[bot_user_id] def ping_bot(self, entity, timeout=30): input_entity = utils.get_input_peer(entity) time.sleep(1) bot_user_id = input_entity.user_id self._pinged_bots.append(bot_user_id) log.debug('Pinging @{username}...'.format(username=entity.username)) self.client.send_message(input_entity, '/start') start = datetime.datetime.now() help_attempted = False while not self._response_received(bot_user_id): if datetime.datetime.now() - start > datetime.timedelta(seconds=5) and \ not help_attempted: # Try sending /help if /start didn't work self.client.send_message(input_entity, '/help') help_attempted = True if datetime.datetime.now() - start > datetime.timedelta( seconds=timeout): # No response self._pinged_bots.remove(bot_user_id) log.debug('@{} did not respond after {} seconds.'.format( entity.username, timeout)) return False time.sleep(0.3) response_text = self._responses[bot_user_id] self._delete_response(bot_user_id) self._pinged_bots.remove(bot_user_id) if isinstance(response_text, str): if 'Use /off to pause your subscription.' in response_text \ or 'Use /stop to unsubscribe.' in response_text: self.botbuilders.append(entity) # Evaluate WJClub's ParkMeBot flags reserved_username = ZERO_CHAR1 + ZERO_CHAR1 + ZERO_CHAR1 + ZERO_CHAR1 parked = ZERO_CHAR1 + ZERO_CHAR1 + ZERO_CHAR1 + ZERO_CHAR2 maintenance = ZERO_CHAR1 + ZERO_CHAR1 + ZERO_CHAR2 + ZERO_CHAR1 if zero_width_encoding(response_text) in (reserved_username, parked, maintenance): return False return True def get_bot_last_activity(self, entity): entity = self.get_bot_entity(entity) _, messages, _ = self.client.get_message_history(entity, limit=5) peer_messages = [m for m in messages if m.from_id == entity.id] if len(peer_messages) == 0: return None last_peer_message = peer_messages[-1] return last_peer_message.date def disconnect(self): self.client.disconnect()
print(str(p.id) + ": " + p.title) if p.id == channel_id: channel_name = p.title print(p.stringify()) chan_type = 'channel' for u in result.users: print(str(u.id) + ": " + u.first_name) if u.id == channel_id: channel_name = u.first_name print(u.stringify()) chan_type = 'user' # for d in result.dialogs: # print(d.stringify()) if chan_type == 'channel': channelEnt = tclient.get_input_entity(PeerChannel(channel_id)) else: channelEnt = tclient.get_input_entity(PeerUser(channel_id)) try: logger.info( "\nListening for messages from channel '{}' with ID '{}'".format( channel_name, channel_id)) except: logger.error("Whoops! Couldn't find channel ID '{}'".format(channel_id)) history = tclient( GetHistoryRequest(peer=channelEnt, offset_date=last_date, offset_id=0, add_offset=0,
def send_sms(): try: api = open("API.txt","r") api_id = api.read() api.close() hash = open("hash.txt","r") api_hash = hash.read() hash.close() tel = open("tel.txt","r") phone = tel.read() tel.close() client = TelegramClient(phone, api_id, api_hash) except KeyError: main.banner() sys.exit(1) client = TelegramClient(phone, api_id, api_hash) client.connect() if not client.is_user_authorized(): client.send_code_request(phone) main.banner() client.sign_in(phone, input('[+] введите код из смс: ')) main.banner() input_file = "members.csv" users = [] with open(input_file, encoding='UTF-8') as f: rows = csv.reader(f,delimiter=",",lineterminator="\n") next(rows, None) for row in rows: user = {} user['username'] = row[0] user['id'] = int(row[1]) user['access_hash'] = int(row[2]) user['name'] = row[3] users.append(user) print("[1] отправить смс по идентификатору ID\n[2] отправить смс username ") mode = int(input("Выбор : ")) reklama = open("reklama.txt", "r", encoding='UTF-8') message = reklama.read() reklama.close() for user in users: if mode == 2: if user['username'] == "": continue receiver = client.get_input_entity(user['username']) elif mode == 1: receiver = InputPeerUser(user['id'],user['access_hash']) else: print("[!] Неверный режим. Выход.") client.disconnect() sys.exit() try: print("[+] Отправка сообщения на:", user['name']) client.send_message(receiver, message.format(user['name'])) print("[+] Ожидание {} секунд".format(random.randint(15, 100))) time.sleep(random.randint(15, 100)) except PeerFloodError: print("[!] Получение сообщения об ошибке из телеграммы. \n[!] Скрипт останавливается сейчас. \n[!] Пожалуйста, попробуйте еще раз через некоторое время.") client.disconnect() sys.exit() except Exception as e: print("[!] ошибка:", e) print("[!] Пытаясь продолжить...") continue client.disconnect() print("Выполнено. Сообщение отправлено всем пользователям.")
class BaseTelegramClient(AioThing): def __init__( self, app_id: Union[int, str], app_hash: str, database: dict, bot_token: Optional[str] = None, mtproxy: Optional[dict] = None, flood_sleep_threshold: int = 60, ): super().__init__() if not app_id or not app_hash: raise ValueError( 'Your API ID or Hash cannot be empty or None. Set up telegram.app_id and/or telegram.app_hash' ) self._telegram_client = TelegramClient( self._get_session(database), app_id, app_hash, flood_sleep_threshold=flood_sleep_threshold, **self._get_proxy(mtproxy=mtproxy), ) self.bot_token = bot_token def _get_session(self, database): if database.get('drivername') == 'postgresql': self.container = AlchemySessionContainer( f"{database['drivername']}://" f"{database['username']}:" f"{database['password']}@" f"{database['host']}:" f"{database['port']}/" f"{database['database']}", session=False, manage_tables=False, ) return self.container.new_session(database['session_id']) else: return sessions.SQLiteSession(session_id=database['session_id']) def _get_proxy(self, mtproxy=None): if mtproxy and mtproxy.get('enabled', True): proxy_config = mtproxy return { 'connection': connection.tcpmtproxy. ConnectionTcpMTProxyRandomizedIntermediate, 'proxy': (proxy_config['url'], proxy_config['port'], proxy_config['secret']) } return {} @retry(retry=retry_if_exception_type(ConnectionError), wait=wait_fixed(5)) async def start(self): await self._telegram_client.start(bot_token=self.bot_token) async def stop(self): return await self.disconnect() def add_event_handler(self, *args, **kwargs): return self._telegram_client.add_event_handler(*args, **kwargs) def catch_up(self): return self._telegram_client.catch_up() def delete_messages(self, *args, **kwargs): return self._telegram_client.delete_messages(*args, **kwargs) def disconnect(self): return self._telegram_client.disconnect() @property def disconnected(self): return self._telegram_client.disconnected def download_document(self, *args, **kwargs): return self._telegram_client._download_document( *args, date=datetime.datetime.now(), thumb=None, progress_callback=None, msg_data=None, **kwargs, ) def edit_message(self, *args, **kwargs): return self._telegram_client.edit_message(*args, **kwargs) def edit_permissions(self, *args, **kwargs): return self._telegram_client.edit_permissions(*args, **kwargs) def forward_messages(self, *args, **kwargs): return self._telegram_client.forward_messages(*args, **kwargs) def get_entity(self, *args, **kwargs): return self._telegram_client.get_entity(*args, **kwargs) def get_input_entity(self, *args, **kwargs): return self._telegram_client.get_input_entity(*args, **kwargs) def iter_admin_log(self, *args, **kwargs): return self._telegram_client.iter_admin_log(*args, **kwargs) def iter_messages(self, *args, **kwargs): return self._telegram_client.iter_messages(*args, **kwargs) def list_event_handlers(self): return self._telegram_client.list_event_handlers() def remove_event_handlers(self): for handler in reversed(self.list_event_handlers()): self._telegram_client.remove_event_handler(*handler) def run_until_disconnected(self): return self._telegram_client.run_until_disconnected() def send_message(self, *args, **kwargs): return self._telegram_client.send_message(*args, **kwargs) def send_file(self, *args, **kwargs): return self._telegram_client.send_file(*args, **kwargs) def __call__(self, *args, **kwargs): return self._telegram_client(*args, **kwargs)
api_hash = '0b614532fe73ef4fe3f28705808d6e60' client = TelegramClient('social_computing', api_id, api_hash).start() # client.send_message('me', 'Hello! Talking to you from Telethon') # messages = client.get_messages('me')#可更改用户名 # print(messages[0].text) # peer = client.get_input_entity('@teng0927') # 可更换用户名 # peer = utils.get_input_peer(peer) # print(peer) # print(client.get_entity("@hello")) str_all = 'Top Game:' + dict['name'] + ' ; ' + 'Viewers:' + str( dict['viewers']) client.send_message('@MaDolphin', str_all) def print_all_message(): api_id = 759517 api_hash = '0b614532fe73ef4fe3f28705808d6e60' client = TelegramClient('social_computing', api_id, api_hash).start() # print all message for message in client.iter_messages("@MaDolphin"): print(message) if __name__ == '__main__': api_id = 759517 api_hash = '0b614532fe73ef4fe3f28705808d6e60' client = TelegramClient('social_computing', api_id, api_hash).start() peer = client.get_input_entity('@teng0927') # 可更换用户名 peer = utils.get_input_peer(peer) print(peer)
class Scraper: def __init__(self, API_ID, API_HASH, session_name='session_name'): self.client = TelegramClient(session_name, API_ID, API_HASH) def connect(self): self.client.start() def get_messages(self, name, file_name, verbose=False, count=-1, detail=1, debug=False): ''' Gets information about messages from Telegram group. Args: name ('str' | 'int') username, id, or url of Telegram group file_name ('str') file to which data will be written verbose ('bool', optional) verbose will include all fields count ('int', optional) how many messages to return total (-1 will return allF) detail ([0, 1, 2, 3], optional) level of detail to include in stdout: - 0 shows when all the function has been completed - 1 shows message after each successful API call - 2 shows complete JSON object debug ('bool', optional) enter debug mode, which will display all raw data ''' file = open(file_name, 'w') file.write('[\n') group = self.client.get_input_entity(name) if debug: print("entity: " + str(group)) offset = 0 total = 0 trailing_comma = False try: while True: if detail >= 1: print('Getting request...') raw = self.client( GetHistoryRequest(peer=group, limit=100, offset_date=None, offset_id=0, max_id=0, min_id=0, add_offset=offset, hash=0)) try: if raw.messages: if debug: print(to_dict(raw.messages, verbose=verbose)) # if the total messages exceed the count, trim the remainder if len(raw.messages ) + total >= count and not count == -1: remainder = count - total data = json.dumps(to_dict(raw.messages[:remainder], verbose=verbose), indent=2)[2:-2] total += len(raw.messages[:remainder]) # else, dump all messages to the file else: data = json.dumps(to_dict(raw.messages, verbose=verbose), indent=2)[2:-2] total += len(raw.messages) # workaround so no trailing comma at end of file if trailing_comma: file.write(',\n') file.write(data) # levels of info if detail == 2: print(data) if detail >= 1: print('Successfully wrote ' + str(total) + ' messages to file!') else: break except Exception as e: print(e) print( 'Failed to retrieve some messages! Continuing anyways...' ) offset = offset + 100 if total >= count and not count == -1: break trailing_comma = True except KeyboardInterrupt: print('Process aborted by user!') file.write('\n]') file.close() print('Scraped message data from ' + str(total) + ' messages to: ' + file_name) def get_users(self, name, file_name, large=False, count=-1, detail=1, debug=False): ''' Gets information about messages from Telegram group. Args: name ('str' | 'int') username, id, or url of Telegram group file_name ('str') file to which data will be written large ('bool', optional) due to limitations of the Telegram API, it is impossible to retrieve more than 10,000 users in one batch. large will go through every letter of the alphabet in an attempt to retrieve as many users as possible. count ('int', optional) how many messages to return total (-1 will return all) detail ([0, 1, 2, 3], optional) level of detail to include in stdout: - 0 shows when all the function has been completed - 1 shows message after each successful API call - 2 shows complete JSON object debug ('bool', optional) enter debug mode, which will display all raw data ''' file = open(file_name, 'w') group = self.client.get_input_entity(name) if debug: print('Entity: ' + str(group)) if count == -1: data = self.client.get_participants(group, aggressive=large) else: data = self.client.get_participants(group, limit=count, aggressive=large) if debug: print(data) to_write = json.dumps(to_dict(data), indent=2) if detail == 2: print(to_write) file.write(to_write) file.close() print('Scraped user data from ' + str(len(data)) + ' users to: ' + file_name)
class TelegramClient(object): def __init__(self, credentials, n_readers=1, filter=None, **kwargs): """ Args: credentials: (str | dict) either a dictionary with credentials, or a filepath to a json file that can be loaded as a dictionary. Optional Args: filter: (list of str | None)(default=None) subset of groups/chats to monitor. Set to None to monitor all subscribed groups **kwargs: arguments to pass to `Telethon.TelegramClient()`` """ self.n_readers = n_readers self.readers = [] self.client = None self.filter = filter self.credentials = self.parse_credentials(credentials) self.kwargs = kwargs self.session_name = 'session_telethon_api' self._me = None @property def me(self): if self.client is None: self._me = None elif self._me is None: self._me = self.client.get_me().to_dict() return self._me @property def read_thread(self): return getattr(self.client, "_recv_thread", None) @property def input_q(self): """ Get the queue used by the client """ updates = getattr(self.client, "updates", None) return getattr(updates, "_updates", None) @property def worker_threads(self): """ Get the list of worker threads used by the client """ updates = getattr(self.client, "updates", None) return getattr(updates, "_worker_threads", "hooooli") @property def is_connected(self): # TODO: A more sophisicated way of telling if it is connected. if self.client is not None: return True else: return False def connect(self): """ credentials=credentials json file with 'id', 'phone' and 'hash' values """ logger.info("CONNECTING TO TELEGRAM") self.client = TelethonClient(self.session_name, api_id=self.credentials['id'], api_hash=self.credentials['hash'], update_workers=self.n_readers, **self.kwargs) self.client.start(phone=self.credentials['phone']) logger.debug("- connected!") def reconnect(self): pass def disconnect(self): pass def ping(self): pass def get_channel(self): pass def stream(self, handler_func): """ Stream all new messages coming in """ self.client.add_event_handler(callback=handler_func, event=events.NewMessage( incoming=True, chats=self.filter)) def parse_credentials(self, credentials): """ If credentials is a path to a json file, then load as a dict """ if isinstance(credentials, str): logger.debug("- opening credentials file: {}".format(credentials)) with open(credentials, mode="r") as fileobj: parsed_credentials = json.load(fileobj) elif not isinstance(credentials, dict): raise ValueError( "credentials must be a dictionary, or filepath to a valid json file" ) return parsed_credentials def list_subscribed_groups(client): # """ Get the set of names of the groups, and channels you are subscribed to """ # chats = client.get_dialogs(limit=None) # group_names = {get_entity_name(chat.entity) for chat in chats if isinstance(chat.entity, (telethon.tl.types.Channel, telethon.tl.types.Chat))} # return group_names pass def get_entity_name(self, entity): """ Given a Telethon Entity object it returns the name of that entity """ name = getattr(entity, "username", getattr(entity, "title", None)) name = name if name is not None else telethon.utils.get_display_name( entity) return name def get_group_info(self, id): """ Returns a dictionary of information of a group from an id, name, or url """ # TODO: maybe create a more generic entity version, that can also # extract user information. # assert url.startswith("https://t.me/"), "Wrong url" entity = self.client.get_entity(id) assert isinstance( entity, (telethon_types.Channel, telethon_types.Chat )), "{} cannot be interpreted as a group/channel/chat".format(id) # EXTRACT INFO url = id if id.startswith("https://t.me/") else None info = TelethonGroupInfo(entity, url) return info.asdict() def join_group(self, id): """ Given a group id it joins that group """ assert isinstance(id, int), "ID must be an integer id" ch = self.client.get_input_entity(PeerChannel(id)) self.client(JoinChannelRequest(ch)) def leave_group(sef, id): """ Given a group id it unsubscribes that group """ assert isinstance(id, int), "ID must be an integer id" ch = self.client.get_input_entity(PeerChannel(id)) self.client(LeaveChannelRequest(ch))