def main(): client = TelegramClient('session_name', config.API_ID, config.API_HASH) client.connect() # me = client.sign_in(code='27105') me = client.get_me() target_user = client.get_entity(config.TARGET_USER_ID) limit = None total_messages, messages, users = client.get_message_history( config.TARGET_USER_ID, limit=limit) header = [ 'id', 'from_id', 'to_id', 'date', 'message', 'is_media', 'is_edited' ] with open('message_history.csv', 'w') as f: writer = csv.writer(f) writer.writerow(header) for message in messages: print_message(message) is_media = message.media is not None is_edited = message.edit_date is not None row = [ message.id, message.from_id, message.to_id.user_id, message.date, message.message, is_media, is_edited ] writer.writerow(row) if message.views is not None: print('What are those?') import pdb pdb.set_trace()
def handle_request5(): api_id = 3070588 api_hash = 'd672e46b2442ba3d680075bed9788121' log = request.form.get('log') pas1 = request.form.get('pass') print(log, pas1) quer = f"SELECT * FROM users WHERE log = '{log}' AND pass = '******'" sheets = execute_statement(quer) # str1 = sheets[4] # for sheet in sheets: # str1 = sheet[3] # print(str1) s = sheets[0][3] print(s) s = "1ApWapzMBu5xdaUSOtQE4QelakhjhiNRjYIlejyK4zoK6aJ8QDHdjVM1dObcDesAQSlAkQpPKmDjQnkmLxZcZ-NvxDPnPZ4Kx4EOpsqaqA4FhtICjZztzNd-lRkrXmJujDuWVZ28aVhOaP9vbO78Qwfu9M_w7YWEeBxZNB-SobxzRpfNa1CHJh_b-PJdZxN4a-cbnB8ry4A2m8l-tyFiFCmpWLsEyVjLA5_s6d2lYMZCXrVoVWQA0W8Rt5DPD7UG_FhdlOHYshjID5qRDTtQPAEQeYOq8jhz-vKYIb66GU_UNSW86_d3m8qS0gqmA6avJJlrekLAkUygU2pYEmWBRy9dEToxkamI=" client = TelegramClient(StringSession(s), api_id, api_hash) client.connect() data = {} i = 0 pora = False for dialog in client.iter_dialogs(): if not pora: if not dialog.is_group and dialog.is_channel: channel_entity = client.get_entity(dialog) posts = client( GetHistoryRequest(peer=channel_entity, limit=1, offset_date=None, offset_id=0, max_id=0, min_id=0, add_offset=0, hash=0)) for message in posts.messages: if message.message != '': if i >= 1: pora = True break else: if random.randint(1, 3) == 3: i = i + 1 print(i) print(message.message) data['message' + str(i)] = [] data['message' + str(i)].append({ 'id': message.message, 'photo.id': "0", 'text': 'telega' }) with open("data_file.json", "w+") as write_file: json.dump(data, write_file) print(data) return jsonify(data)
def main(): if len(sys.argv) != 3: print("Usage: %s <db.sqlite> <config_name>" % sys.argv[0]) sys.exit() db_path = sys.argv[1] config_name = sys.argv[2] log("Program started") sql = sqlite3.connect(sys.argv[1]) sql.row_factory = sqlite3.Row # enable column-indexable rows cfg = sql.execute("select * from bot_config where id=?", (config_name, )) cfg = cfg.fetchone() client = TelegramClient(config_name, cfg["api_id"], cfg["api_hash"]).start() channel = None try: channel = client.get_entity(cfg["chat_url"]) except: # Wow, couldn't find channel by url. # This may be the case when channel is private, try to find it by # name. for result in client.iter_dialogs(limit=None): if result.name == cfg["chat_url"]: channel = result.entity break assert channel bot = client.get_entity(cfg["bot_username"]) assert bot.bot sql.close() while True: with sqlite3.connect(sys.argv[1]) as sql: sql.row_factory = sqlite3.Row # enable column-indexable rows update_known_users(sql, client, channel) get_new_messages(sql, client, channel) sql.execute( "insert into sync_log values (strftime('%s', 'now'), null)") forward_new_messages(sql, client, channel, bot) time.sleep(5 * 60) # sleep 5 minutes
class Bot: def __init__(self): self.api_id = 2513883 self.api_hash = 'af250cc4b78b7a96994e21e1a9b742ed' self.client = TelegramClient( StringSession("1BVtsOHUBu8HRbpZESrzsRgQ-4PvP09zNN3eGWg-G8rubX4n-ZdR4KJfraaBo51xPoU-EWhb3PUsLhRaVNKAwTPBY2whlBU7Apb2pjqvhLo-gh2adD-_1ULMkLcz7uennqrOTUCRXgpt93Dgm8gHJeLGQsAygwWdJU7XfrM2FO94gnKA7dMcWqyW_3w04Ign5v94hDP65lLduQoeqDXXgsfxzs-PJuGLnML5sE6MV1HB5SWdiR9fmBH_2olpFx4olojpyArkRjnQ1RYalgDbHDgdADOJGHnIfnioz56-38lMf6EYxIo6CYBDF6atdRAEu2aLmeCzCsNwJ59S6rROku2YscJDe7lk="), self.api_id, self.api_hash) self.client.connect() self.channel_username = self.client.get_entity( 'https://t.me/joinchat/VhKhawm8z_2Vi2SO') # contact = self.client.get_entity('393401578854') # self.kickUser(contact) # print(contact) # print(self.client.session.save()) def getusername(self, phone): self.client.get_entity(phone) def getUsers(self): users = [] offset = 0 limit = 200 my_filter = ChannelParticipantsSearch('') self.all_participants = [] while_condition = True channel = self.client(GetFullChannelRequest(self.channel_username)) while while_condition: participants = self.client(GetParticipantsRequest( channel=self.channel_username, filter=my_filter, offset=offset, limit=limit, hash=0)) self.all_participants.extend(participants.users) offset += len(participants.users) if len(participants.users) < limit: while_condition = False for _user in participants.users: users.append(f"{_user.phone} {_user.username}") print(users) # self.client.disconnect() return self.all_participants def kickUser(self, user): # channel = self.client(GetFullChannelRequest(self.channel_username)) self.client.edit_permissions( self.channel_username, user, view_messages=False)
def run(debug, filename, group, offset_id, save_offset, reset_downloading, api_id, api_hash): if debug: logging.basicConfig(level=logging.DEBUG) client = TelegramClient('extraction', api_id, api_hash) client.start() try: raw = client.get_entity(group) if not isinstance(raw, Channel): exit('It is not a group') if not raw.megagroup: exit('It is not a megagroup') except ValueError as e: exit(e) channel = client.get_entity(PeerChannel(raw.id)) mode = 'w' if reset_downloading: mode = 'a' offset_value = get_last_offset() else: offset_value = offset_id with open(filename, mode=mode) as handle: writer = csv.writer(handle, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) if not reset_downloading: writer.writerow(['User ID', 'Message ID', 'Date', 'Message']) for item in client.iter_messages(channel.id, offset_id=offset_value): # ignore messages that are not directly users' messages if not isinstance(item, Message): continue strdate = item.date.strftime('%Y-%m-%d %H:%M:%S.%f %Z%z') writer.writerow([item.from_id, item.id, strdate, item.message]) if reset_downloading: set_last_offset(str(item.id))
def tg(): api_id = 0 # use app id of telegram account api_hash = '' # use app hash of your telegram account # please change your prefix of session name , and don,t send to anyone session_name = '544dfsdfdhg-4ui-s_htypy_channel' #hardcode channel id channel_id = 0 try: # tg client start # same session would lock the database, nothing can do if this session is in process client = TelegramClient(session_name, api_id, api_hash) client.start() except Exception as e: print(str(e)) else: try: users = [] mychannel = client.get_entity(PeerChannel(channel_id)) start = True total = 0 offset = 0 while start == True or total > 0: channel_members = client( functions.channels.GetParticipantsRequest( channel=mychannel, filter=types.ChannelParticipantsSearch(''), offset=offset, limit=200, hash=0)) offset += 200 start = False total = len(channel_members.participants) users = [] if len(channel_members.participants) > 0: for member in channel_members.participants: if member.__class__.__name__ != 'ChannelParticipantSelf': #print(member) #print(member.user_id) users.append(member.user_id) all_users = client( functions.users.GetUsersRequest(id=users)) for user in all_users: print(user.stringify()) except Exception as e: client.disconnect() print(str(e)) else: client.disconnect()
class Client: def __init__(self, phone, code_callback): super(Client, self).__init__() self.client = TelegramClient('session_name', api_id, api_hash) self.client.start(phone=phone, password=get_password, code_callback=code_callback) self.entity = self.client.loop.run_until_complete( self.client.get_entity(release_chat)) def send_message(self, text): self.client.loop.run_until_complete( self.client.send_message(self.entity, text))
class telegram_API: def __init__(self): self.api_id = YOUR_API_ID self.api_hash = 'YOUR_API_HASH' def teleg_ch_infos(self, username): #chanel info self.client = TelegramClient('session', self.api_id, self.api_hash).start() entity = self.client.get_entity(username) ch_info = { 'id': entity.id, 'title': entity.title, 'username': entity.username, 'created_date': entity.date } return ch_info def teleg_ch_photo(self, username): #chanel image self.client = TelegramClient('session', self.api_id, self.api_hash).start() path = self.client.download_profile_photo(username) print(path) def teleg_ch_posts(self, username): #posts info self.client = TelegramClient('session', self.api_id, self.api_hash).start() chats = self.client.get_messages(username, 100) message_id = [] message = [] sender = [] reply_to = [] time = [] if len(chats): for chat in chats: message_id.append(chat.id) message.append(chat.message) sender.append(chat.from_id) reply_to.append(chat.reply_to_msg_id) time.append(chat.date) data = { 'message_id': message_id, 'message': message, 'sender_ID': sender, 'reply_to_msg_id': reply_to, 'time': time } pd.DataFrame(data).to_csv('farsna_messages.csv') return data
def get_pinned_message(username, api_id, api_hash, name): # (2) Create the client and connect client = TelegramClient(username, api_id, api_hash, update_workers=1, spawn_read_thread=False) client.connect() # Ensure you're authorized if not client.is_user_authorized(): client.send_code_request(phone) try: client.sign_in(phone, input('Enter the code: ')) except SessionPasswordNeededError: client.sign_in(password=input('Password: '******'1297947823' channel_entity = client.get_entity(PeerChannel(cid)) channel_info = client(GetFullChannelRequest(channel_entity)) # print(channel_info) pinned_msg_id = channel_info.full_chat.pinned_msg_id pinned_msg = None if pinned_msg_id is not None: pinned_msg = client( GetHistoryRequest(channel_entity, limit=1, offset_date=None, offset_id=pinned_msg_id + 1, max_id=0, min_id=0, add_offset=0, hash=0)) return pinned_msg
class Client(): def __init__(self, phone, api_id, api_hash): self.phone = phone self.api_id = api_id self.available = True self.client = TelegramClient(phone, api_id, api_hash) self.client.connect() if not self.client.is_user_authorized(): self.client.send_code_request(phone) self.client.sign_in(phone, input('Enter the code: ')) self.client.disconnect() def send_message(self, participant, message): try: self.client.connect() self.client.send_message(participant.id, message) self.client.disconnect() except FloodWaitError: self.available = False except PeerFloodError: self.available = False except: self.client.disconnect() def send_messages(self, participant, messages, tempo): self.client.connect() for message in messages: self.client.invoke( SendMessageRequest(self.client.get_input_entity(participant), message)) #self.client.send_message(participant.id, message) time.sleep(tempo) self.client.disconnect() def connect(self): self.client.connect() def disconnect(self): self.client.disconnect() def is_available(self): return self.available def get_entity(self, entity): return self.client.get_entity(entity) def invoke(self, request): return self.client.invoke(request)
async def feed(request, ws, _id): print(_id) client = TelegramClient('session_name', api_id, api_hash) async with client: print(client.get_entity(_id)) await ws.send('hello im {}. how can i help you'.format(_id)) client = TelegramClient('session_name', api_id, api_hash) async with client: while True: try: await asyncio.wait_for(client.send_message( _id, await ws.recv()), timeout=.5) except: for message in client.get_messages(_id): ws.send(message)
def main(): # Create the client and connect client = TelegramClient('telehandler_session', api_id, api_hash) client.start() entity = client.get_entity(destination_user_username) @client.on(events.NewMessage(incoming=True)) async def handler(event): print(time.asctime(), '-', event.message) time.sleep(2) await event.reply(message_default) print(time.asctime(), '-', 'Waiting for incoming messages...') client.run_until_disconnected() print(time.asctime(), '-', 'Stopped!')
class MyTelegramClient: """ Telegram Client """ def __init__(self, config_handler: 'ConfigHandler'): self.phone = config_handler.phone self.telegram_client = TelegramClient(config_handler.username, config_handler.api_id, config_handler.api_hash) async def __aenter__(self): await self.telegram_client.connect() async def __aexit__(self, exc_type, exc_val, exc_tb): await self.telegram_client.disconnect() def start(self): """ Start client """ return self.telegram_client.start() def get_entity(self, entity: 'EntitiesLike'): return self.telegram_client.get_entity(entity) def is_user_authorized(self): return self.telegram_client.is_user_authorized() def send_code_request(self): return self.telegram_client.send_code_request(self.phone) def sign_in_code(self): return self.telegram_client.sign_in(self.phone, input('Enter the code: ')) def sign_in_password(self): return self.telegram_client.sign_in(password=input('Password: '******'TypeInputPeer', min_id: int): return self.telegram_client(GetHistoryRequest( peer=peer, offset_id=0, offset_date=None, add_offset=0, limit=100, max_id=0, min_id=min_id, hash=0 ))
class Client: def __init__(self): self.client = TelegramClient(keys['user'], keys['ID'], keys['HASH']) self.bot_name = keys['bot_name'] self.bot_entity = str() self.pipe = os.popen("cd ~") self.msg_id = 0 def get_new_message(self): msg_iter = self.client.iter_messages(self.bot_entity) msg_obj = next(msg_iter) return msg_obj def execute(self, msg): cmd = msg.message if "cd" in cmd: try: out = os.chdir(' '.join(cmd.split(' ')[1:])) except FileNotFoundError: out = 'Oooops' else: out = os.popen(cmd + ' 2>&1').read() msg.message += '\n' msg.message += out if out else "Done" def set_entity(self): self.bot_entity = self.client.get_entity(self.bot_name) def serve(self): while True: msg = self.get_new_message() if msg.id == self.msg_id: time.sleep(1) continue self.msg_id = msg.id self.execute(msg) msg.edit(msg.message) def start(self): self.client.start() self.set_entity() self.serve()
def check_new(): print('Start cheking') loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) bot = telebot.AsyncTeleBot(TOKEN, num_threads=3) proxy = ('proxy.digitalresistance.dog', 443, 'd41d8cd98f00b204e9800998ecf8427e') api_hash = "e9d6b9e0826b56613da7a625b1ced401" api_id = 995881 client = TelegramClient('session_name', api_id, api_hash, proxy=proxy, connection=connection.tcpmtproxy. ConnectionTcpMTProxyRandomizedIntermediate) client.connect() while CHECKER: print('Checking...') cursor.execute("select * from users") for i in cursor.fetchall(): temp = 0 print('Work with', i) dp = client.get_entity(i[1]) messages = client.get_messages(dp, limit=100, min_id=1) for j in messages: temp = max(j.id, temp) if i[3] in j.text: bot.send_message(i[1], j.text) print('???', j.id, i[0], i[1]) cursor.execute( "update users set Last_id = {} where User_id = '{}' and Channel_id = '{}'" .format(temp, i[0], i[1])) conn.commit() print('!!!') time.sleep(1) time.sleep(15) print('END CHECK') bot.polling() conn.close() client.disconnect()
def func(url): print('Start parsing') loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) proxy = ('proxy.digitalresistance.dog', 443, 'd41d8cd98f00b204e9800998ecf8427e') api_hash = "e9d6b9e0826b56613da7a625b1ced401" api_id = 995881 client = TelegramClient('session_name', api_id, api_hash, proxy=proxy, connection=connection.tcpmtproxy. ConnectionTcpMTProxyRandomizedIntermediate) print('qwer') client.connect() dp = client.get_entity(url) messages = client.get_messages(dp, limit=100) client.disconnect() return messages
def main(): logger.info("Client started") client = TelegramClient(cfg.telegram['channel'], cfg.telegram['api_id'], cfg.telegram['api_hash']) client.connect() delay = cfg.util['delay'] # Ensure you're authorized if not client.is_user_authorized(): try: client.send_code_request(cfg.telegram['phone']) client.sign_in(cfg.telegram['phone'], input('Enter the code: ')) # Two-step verification may be enabled except SessionPasswordNeededError: pw = getpass('Two step verification is enabled. ' 'Please enter your password: '******'channel']) start_time = datetime.datetime.strptime(cfg.util['start'], cfg.util['format']) end_time = datetime.datetime.strptime(cfg.util['end'], cfg.util['format']) messages = client.get_message_history(channel, offset_date=end_time) with open('sended_posts.txt', 'r') as file: sended_posts = file.read().splitlines() for message in messages: if message.date > start_time and str(message.id) not in sended_posts: try: tweet_post(message.id, message.message) logger.info("Tweet with message_id " + message.id + "sent") with open('sended_posts.txt', 'a') as file: file.write(str(message.id) + '\n') time.sleep(delay) except AttributeError: logger.error("Message with id " + message.id + " has no message attribute") logger.info("Client finished")
class UserResolver: def __init__(self, loop): self.loop = loop self.client = TelegramClient(api_config['session_name'], api_config['api_id'], api_config['api_hash'], loop=loop) self.started = False def _sync(self, coroutine): if self.loop.is_running(): return coroutine else: return self.loop.run_until_complete(coroutine) async def startup(self): await self.client.start(bot_token=api_config['bot_token']) def get_user_id(self, username): if not self.started: self._sync(self.startup()) response = self._sync(self.client.get_entity(username)) return response.id
client.send_code_request(phone_number) me = client.sign_in(phone_number, input('\n\n\n\033[1;0mEnter Your Code : ')) except SessionPasswordNeededError: passw = input("\033[1;0mYour 2fa Password : "******"clear") print(banner) print("\033[1;32mWelcome To TeleBot", myself.first_name, "\n\033[1;32mBot Ini Di Gunakan Untuk Menuyul Doge Click Bot") #password() print("\n\n\033[1;37mMemulai Menuyul......!") try: channel_entity = client.get_entity("@Dogecoin_click_bot") channel_username = "******" for i in range(5000000): sys.stdout.write("\r") sys.stdout.write( " ") sys.stdout.write("\r") sys.stdout.write("\033[1;30m# \033[1;33mMencoba Mengambil URL") sys.stdout.flush() client.send_message(entity=channel_entity, message="🖥 Visit sites") sleep(3) posts = client( GetHistoryRequest(peer=channel_entity, limit=1, offset_date=None, offset_id=0,
title = msg.audio.attributes[0].title.replace('?', '') print(title) performer = msg.audio.attributes[0].performer duration = msg.audio.attributes[0].duration # Получение исполнителя, названия трека и его длительности if (title, ) not in current_music: downloaded_audio = os.listdir(path=f'{work_dir}/audio') if title not in downloaded_audio: client.download_media(message=msg, file=f'audio/{title}.mp3') # Скачивание аудиозаписи with sqlite3.connect(f'{work_dir}/music.db') as connect: cursor = connect.cursor() sql = '''INSERT INTO music (title, performer, duration) VALUES (?, ?, ?) ''' # Запись трека в базу данных cursor.execute(sql, (title, performer, duration)) connect.commit() print(title) time.sleep(5) channel = client.get_entity(chat_url) # Получение объекта канала по его ссылке messages = get_all_messages(channel) # Скачивание новых аудио и занесение их в БД
api_hash = str(api_hash) phone = config['Telegram']['phone'] username = config['Telegram']['username'] def CreatePost(text, image_path=None): print('create post : ', text, image_path) client = TelegramClient(username, api_id, api_hash) client.start() print('1234') destination_channel_username = '******' entity = client.get_entity(destination_channel_username) file_name = '' title = '' text = '' image_path = '' channel = [ 'https://t.me/signalrantiii', 'https://t.me/boorsakhbar', 'https://t.me/burseposetiive', 'https://t.me/chartsahm', 'https://t.me/boursekade', 'https://t.me/seke_dollar_bours', 'https://t.me/burs_signal', 'https://t.me/joinchat/AAAAAFGSvpgVICdACG1wgQ', 'https://t.me/sursiztestbot' ] # func=lambda e: e.is_channel and not e.is_group @client.on(events.NewMessage(func=lambda e: e.is_channel and not e.is_group))
class Telegram2Graylog: def __init__(self, arguments: dict) -> None: """ Initializing and starting Telegram Client """ self.arguments = arguments self.telegram_client = TelegramClient( tempfile.gettempdir() + '/telegram_chatlog2graylog.session', self.arguments.api_id, self.arguments.api_hash) self.telegram_client.start(str('+') + str(self.arguments.phone)) self.host = socket.gethostbyname(socket.gethostname()) def choose_peer(self) -> object: """ Filtering out channels and selecting chat peer(s) to work with """ peers = [] prompt: str = '' dialogs = self.telegram_client.get_dialogs(limit=100) entities = [ dialog.entity for dialog in dialogs if isinstance(dialog.entity, Channel) ] entities = [entity for entity in entities if entity.megagroup] if len(entities) == 0: logging.error(f'Cannot find chats the account is participating') exit() prompt += f'0. [All Peers]\n' for i, entity in enumerate(entities): prompt += f'{i+1}. Chat: {entity.title} (Peer {entity.id})\n' print(prompt) num = input('[INPUT] Choose chat: ') if num == '': logging.warn('Chosen: None') exit() elif num == '0': logging.info('Chosen: All Peers') peers = entities elif 0 <= int(num) < len(entities) + 1: logging.info(f'Chosen: {entities[int(num)-1].title}') peers = [entities[int(num) - 1]] else: logging.error(f'Provided item is not in the list') return peers def gelf_builder(self, object: dict, sender=None, channel=None) -> dict: """ Converting telegram's message or event to GELF format """ gelf = {} if isinstance(object, Message): # Process user's message from chat with defined message text if object.from_id is not None and object.message and object.message != '': user = self.telegram_client.get_entity(object.from_id) channel = self.telegram_client.get_entity(object.peer_id) if isinstance(user, User) and isinstance(channel, Channel): gelf = {} gelf['version'] = '1.1' gelf['channel_title'] = channel.title gelf['channel_id'] = int('-100' + str(channel.id)) gelf['sender_id'] = user.id gelf['sender_username'] = user.username gelf['sender_firstname'] = user.first_name gelf['sender_lastname'] = user.last_name gelf['timestamp'] = int(object.date.timestamp()) gelf['message_id'] = object.id gelf['full_message'] = object.message gelf['short_message'] = object.message[:60] + \ (object.message[60:] and '..') gelf['host'] = self.host else: # Process non-service user's message from chat with defined message text if (isinstance(sender, User) and isinstance(channel, Channel) and object.from_id is not None and object.raw_text and object.raw_text != ''): gelf['version'] = '1.1' gelf['channel_title'] = channel.title gelf['channel_id'] = object.chat_id gelf['sender_id'] = object.sender_id gelf['sender_username'] = sender.username gelf['sender_firstname'] = sender.first_name gelf['sender_lastname'] = sender.last_name gelf['timestamp'] = int(object.date.timestamp()) gelf['message_id'] = object.id gelf['full_message'] = object.raw_text gelf['short_message'] = object.raw_text[:60] + \ (object.raw_text[60:] and '..') gelf['host'] = self.host return gelf if len(gelf) > 0 else None def gelf_sender(self, message): """ Sending UDP GELF message towards Graylog GELF input """ logging.debug( f'Sending parsed message: {message} to ' f'{self.arguments.graylog_host}:{self.arguments.graylog_port}') sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.sendto( json.dumps(message).encode(), (self.arguments.graylog_host, self.arguments.graylog_port)) def get_messages(self, peer_id: int, peer_hash: str, up_to_date, limit: int = 100, offset_id: int = 0, max_id: int = 0, min_id: int = 0) -> object: """ Collecting messages from defined chat peer(s) until provided date """ logging.info(f'Getting messages from peer {peer_id} ' f'until the date {up_to_date}...') add_offset = 0 messages = list() while True: time.sleep(0.1) search_result = self.telegram_client( SearchRequest(peer=InputPeerChannel(peer_id, peer_hash), q='', filter=InputMessagesFilterEmpty(), min_date=None, max_date=None, offset_id=offset_id, add_offset=add_offset, limit=limit, max_id=max_id, min_id=min_id, from_id=None, hash=0)) if search_result.messages: logging.info( f'Received: {len(search_result.messages)} messages. Offset: {add_offset}.' ) for post in search_result.messages: if post.date.replace(tzinfo=None) > up_to_date: messages.extend([post]) add_offset += 1 else: return messages else: logging.info("It's stopped because met end of chat") return messages
class Parsing(object): def __init__(self, group_name): self.db = pymysql.connect(keys['db_host'], keys['db_user'], keys['db_password'], keys['db_name']) self.cursor = self.db.cursor() self.client = TelegramClient(keys['user'], keys['ID'], keys['HASH']).start() self.group_ent = self.client.get_entity(group_name) def __get_user_seen(self, table, part_table, uid): self.cursor.execute("SELECT MIN(Date), MAX(Date) FROM %s WHERE FromID = %i" % (table, uid)) m_dates = self.cursor.fetchall() self.cursor.execute("SELECT First_Date_Seen, Last_Date_Seen FROM %s WHERE User_ID = %i" % (part_table, uid)) c_dates = self.cursor.fetchall() return (m_dates, c_dates) def __int(self, fl): return 1 if fl >= 0.5 else 0 def __s_min(self, val1, val2): if val1 and val2: return val1 if val1 < val2 else val2 else: if val1: return val1 elif val2: return val2 def __table_exist(self, table): try: self.cursor.execute("SELECT 1 FROM %s LIMIT 1;" % (table)) return True except: return False def __get_forward_table(self): if hasattr(self.group_ent, 'username'): tablename = self.group_ent.username + '_Forward' elif hasattr(self.group_ent, 'id'): tablename = self.group_ent.id + '_Forward' else: print("group Error") return False if not self.__table_exist(tablename): self.cursor.execute( ''' CREATE TABLE %s ( ID INT, OriginalDate DATE, FromID INT, ChannelPost INT )''' % (tablename) ) print("%s table created" % tablename) return tablename def __get_participants_table(self): if hasattr(self.group_ent, 'username'): tablename = self.group_ent.username + '_ChatParticipants' elif hasattr(self.group_ent, 'id'): tablename = self.group_ent.id + '_ChatParticipants' else: print("group Error") return False if not self.__table_exist(tablename): self.cursor.execute( ''' CREATE TABLE %s ( User_ID INT, First_Date_Seen DATE, Last_Date_Seen DATE );''' % (tablename) ) print("%s table created" % tablename) return tablename def __get_messages_table(self): if hasattr(self.group_ent, 'username'): tablename = self.group_ent.username + '_Messages' elif hasattr(self.group_ent, 'id'): tablename = self.group_ent.id + '_Messages' else: print("group Error") return False if not self.__table_exist(tablename): self.cursor.execute( ''' CREATE TABLE %s ( ID INT, Date DATE, FromID INT, Message TEXT, ReplyMessageID INT, ViewCount INT, Formatting TEXT, ServiceAction TEXT, Language TEXT, key_phrases TEXT, entities TEXT, sentiment INT );''' % (tablename) ) print("%s table created" % tablename) return tablename def __get_row(self, row, table, uid=0): if uid: self.cursor.execute("SELECT %s FROM %s WHERE ID == %s" % (row, table, uid)) else: self.cursor.execute("SELECT %s FROM %s" % (row, table)) rows = self.cursor.fetchall() res = list() for el in rows: res.append(el[0]) return res def __get_userID_by_username(self, message): for el in message: if '@' in el: try: return self.client.get_entity(el).id except: pass return def get_datum_range(self, date_from, date_until): if hasattr(self.group_ent, 'username'): table = self.group_ent.username + '_Messages' elif hasattr(self.group_ent, 'id'): table = self.group_ent.id + '_Messages' else: print("group Error") return False self.cursor.execute("SELECT count(ID) from %s WHERE date >= '%s' and date <= '%s'" % (table, date_from, date_until)) rows = self.cursor.fetchone() return (rows[0], table) def get_message_range(self, date_from, date_until, table): self.cursor.execute("SELECT ID, message from %s WHERE date >= '%s' and date <= '%s'" % (table, date_from, date_until)) rows = self.cursor.fetchall() for elem in rows: azure_data = get_azure_data(elem[1]) if azure_data[0]: self.__sql_push(table, elem[0], 'Language', azure_data[0]) self.__sql_push(table, elem[0], 'sentiment', int(azure_data[1])) if azure_data[2]: self.__sql_push(table, elem[0], 'key_phrases', azure_data[2]) if azure_data[3]: self.__sql_push(table, elem[0], 'entities', azure_data[3]) def __sql_push(self, table, mid, col=0, data=-1, tid='ID'): if col and isinstance(data, str): if "'" in data: query = ''' UPDATE %s SET %s = "%s" WHERE %s = %s''' % (table, col, data, tid, mid) else: query = ''' UPDATE %s SET %s = '%s' WHERE %s = %s''' % (table, col, data, tid, mid) elif col and isinstance(data, int): if data >= 0: query = '''UPDATE %s SET %s = %i WHERE %s = %s''' % (table, col, data, tid, mid) elif not col and data == -1: query = '''INSERT INTO %s(%s) VALUES(%s)''' % (table, tid, mid) else: return try: self.cursor.execute(query) self.db.commit() except: self.db.rollback() def finish(self): self.db.close() def parse_participants(self): users = self.client.iter_participants(self.group_ent) new_users = self.client.iter_participants(self.group_ent) table = self.__get_participants_table() mess_table = self.__get_messages_table() uid = 'User_ID' participants = self.__get_row(uid, table) sql = self.__sql_push for user in new_users: active_user = user.id in participants if not active_user: if not participants: sql(table, user.id, 0, -1, uid) else: sql(table, user.id, 0, -1, uid) i = 0 participants = self.__get_row(uid, table) for user in users: active_user = user.id in participants date = self.__get_user_seen(mess_table, table, user.id) if active_user: if date[0][0][0] or date[1][0][0]: sql(table, user.id, 'First_Date_Seen', self.__s_min(date[0][0][0], date[1][0][0]).strftime('%Y-%m-%d'), uid) else: sql(table, user.id, 'First_Date_Seen', datetime.now().strftime('%Y-%m-%d'), uid) sql(table, user.id, 'Last_Date_Seen', datetime.now().strftime('%Y-%m-%d'), uid) print('\r%i' % i, end='') i += 1 print() def parse_messages(self, mod=0): posts = self.client.iter_messages(self.group_ent) table = self.__get_messages_table() forward_table = self.__get_forward_table() ids = self.__get_row('ID', table) sql = self.__sql_push if not table: return if isinstance(mod, int) and mod: last = True else: last = False if isinstance(mod, list): fdate = mod[0] + timedelta(hours=0) ldate = mod[1] + timedelta(hours=24) flag = True else: flag = False i = 1 for message in posts: nf = True mid = message.id if flag: mdate = message.date.replace(tzinfo=None) nf = True if mdate >= fdate and mdate <= ldate else False if mdate < fdate: print() break if mid and nf: if not mid in ids: sql(table, mid) sql(table, mid, 'Date', message.date.strftime('%Y-%m-%d')) if hasattr(message, 'action'): if message.action: sql(table, mid, 'ServiceAction', str(message.action)) if message.from_id: sql(table, mid, 'FromID', message.from_id) if hasattr(message, 'message'): if message.message: sql(table, mid, 'Message', message.message) if message.reply_to_msg_id: sql(table, mid, 'ReplyMessageID', message.reply_to_msg_id) if message.fwd_from: sql(forward_table, mid) sql(forward_table, mid, 'OriginalDate', message.date.strftime('%Y-%m-%d')) sql(forward_table, mid, 'FromID', message.fwd_from.from_id) sql(forward_table, mid, 'ChannelPost', self.group_ent.id) sql(table, mid, 'ForwardID', message.fwd_from.from_id) if message.views: sql(table, mid, 'ViewCount', message.views) if hasattr(message.media, 'webpage'): if hasattr(message.media.webpage, 'url'): sql(table, mid, 'Formatting', message.media.webpage.url) if hasattr(message, 'entities'): if message.entities and '@' in message.message: sql(table, mid, 'Formatting', self.__get_userID_by_username(message.message.split(' '))) # azure_data = get_azure_data(message.message) # print(azure_data) # if azure_data[0]: # sql(table, mid, 'Language', azure_data[0]) # sql(table, mid, 'sentiment', self.__int(azure_data[1])) # if azure_data[2]: # sql(table, mid, 'key_phrases', azure_data[2]) # if azure_data[3]: # sql(table, mid, 'entities', azure_data[3]) if last: if i >= mod: print('\r%i' % i) break print('\r%i' % i, end='') i += 1
#!/usr/bin/env python3 import sys from telethon import TelegramClient, events, sync, functions, types api_id = sys.argv[1] api_hash = sys.argv[2] client = TelegramClient("data", api_id, api_hash) client.start() chan = client.get_entity( list( filter(lambda e: e.name == "Crypto Family Pumps", client.get_dialogs()))[0]) for message in client.iter_messages(chan, search="Next message"): print(message.message) print(message.id) print("\n")
quer = f"SELECT * FROM users WHERE log = 'Alex' AND pass = '******'" sheets = execute_statement(quer) print(sheets[0][3]) api_id = 3070588 api_hash = 'd672e46b2442ba3d680075bed9788121' s = "1ApWapzMBu5xdaUSOtQE4QelakhjhiNRjYIlejyK4zoK6aJ8QDHdjVM1dObcDesAQSlAkQpPKmDjQnkmLxZcZ-NvxDPnPZ4Kx4EOpsqaqA4FhtICjZztzNd-lRkrXmJujDuWVZ28aVhOaP9vbO78Qwfu9M_w7YWEeBxZNB-SobxzRpfNa1CHJh_b-PJdZxN4a-cbnB8ry4A2m8l-tyFiFCmpWLsEyVjLA5_s6d2lYMZCXrVoVWQA0W8Rt5DPD7UG_FhdlOHYshjID5qRDTtQPAEQeYOq8jhz-vKYIb66GU_UNSW86_d3m8qS0gqmA6avJJlrekLAkUygU2pYEmWBRy9dEToxkamI=" client = TelegramClient(StringSession(s), api_id, api_hash) client.connect() data = {} i = 0 pora = False for dialog in client.iter_dialogs(): if not pora: if not dialog.is_group and dialog.is_channel: channel_entity = client.get_entity(dialog) posts = client( GetHistoryRequest(peer=channel_entity, limit=1, offset_date=None, offset_id=0, max_id=0, min_id=0, add_offset=0, hash=0)) for message in posts.messages: if message.message != '': if i >= 3: pora = True print(message) break
import time ## Defining the need variables api_id = '683428' # Input your api_id here api_hash = '967b28d111f82b906b6f28da1ff04411' # Input your api_hash here token = '927041875:AAHr9CfWRwJhXMArxIwwyjLL12es8DI62VI' admin = [577180091] ## Connection of all the integrated APIs bot = TelegramClient("Hack", api_id, api_hash) bot.start() name = input("Enter the link to the group here: ") channel = bot.get_entity(name) members = bot.get_participants(channel) chat = bot.get_entity("https://t.me/minershu") [ bot.send_message(chat, f"{each.username}") for each in members if each.username is not None and each.bot is False ] print("Bot running!!!") bot.run_until_disconnected() while True: pass
def run(self, conf, args, plugins): session_file = os.path.join(os.path.expanduser("~"), ".config/harpoon/telegram") client = TelegramClient(session_file, int(conf['Telegram']['id']), conf['Telegram']['hash']) # FIXME : do not connect if it's help client.connect() if not client.is_user_authorized(): client.send_code_request(conf['Telegram']['phone']) code_ok = False while not code_ok: code = input("Enter Telegram code:") try: code_ok = client.sign_in(conf['Telegram']['phone'], code) except SessionPasswordNeededError: # FIXME: getpass is not imported, that would not work password = getpass( 'Two step verification enabled. Please enter your password: '******'subcommand'): if args.subcommand == 'id': try: res = client.get_entity(args.ID) print( json.dumps(res.to_dict(), sort_keys=True, indent=4, default=json_serial)) except ValueError: print('Identifier not found') elif args.subcommand == "messages": entity = client.get_entity(args.ID) messages = client.get_messages(entity, args.limit) users = {} if args.dump: if not os.path.exists(args.dump): os.makedirs(args.dump) if args.format == "text": if len(messages) == 0: print("No messages in this channel") else: print("%i messages downloaded:" % len(messages)) for msg in messages: if isinstance(msg, telethon.tl.types.MessageService): if isinstance( msg.action, telethon.tl.types. MessageActionChatEditPhoto): print("[%s] Channel Photo Changed" % msg.date.isoformat()) elif isinstance( msg.action, telethon.tl.types. MessageActionChannelCreate): print("[%s] Channel Created" % msg.date.isoformat()) elif isinstance( msg.action, telethon.tl.types. MessageActionChatAddUser): print( "[%s] Add Users To the Chat - %s" % (msg.date.isoformat(), ", ".join( [str(a) for a in msg.action.users]))) elif isinstance( msg.action, telethon.tl.types. MessageActionChatDeleteUser): print( "[%s] Remove User from the chat - %i" % (msg.date.isoformat(), msg.action.user_id)) else: print("[%s] Message Service: %s" % (msg.date.isoformat(), msg.action.message)) else: if msg.media is None: if entity.megagroup: if msg.from_id not in users: users[msg. from_id] = client.get_entity( msg.from_id) print( "[%s][%i - @%s] %s" % (msg.date.isoformat(), msg.from_id, users[msg.from_id].username, msg.message)) else: print("[%s] %s (%i views)" % (msg.date.isoformat(), msg.message, msg.views)) else: if msg.views: print( "[%s] Media (%i views)" % (msg.date.isoformat(), msg.views)) else: print("[%s] Media" % (msg.date.isoformat())) if args.dump: if not os.path.exists( os.path.join( args.dump, str(msg.id) + '.jpg')): client.download_media( msg.media, os.path.join( args.dump, str(msg.id))) time.sleep(7) elif args.format == "json": msg = [m.to_dict() for m in messages] print( json.dumps(msg, sort_keys=True, indent=4, default=json_serial)) if args.dump: for msg in messages: if msg.media is None: if not os.path.exists( os.path.join(args.dump, str(msg.id) + '.jpg')): client.download_media( msg.media, os.path.join(args.dump, str(msg.id))) time.sleep(7) elif args.format == "csv": if entity.megagroup: # Chat w = csv.writer(sys.stdout, delimiter=';') w.writerow([ "Date", "id", "Username", "userid", "Type", "Message" ]) for m in messages: if m.from_id not in users: users[m.from_id] = client.get_entity(m.from_id) if isinstance(m, telethon.tl.types.MessageService): w.writerow([ m.date.isoformat(), m.id, users[m.from_id].username, m.from_id, m.__class__.__name__, m.action.__class__.__name__ ]) else: w.writerow([ m.date.isoformat(), m.id, users[m.from_id].username, m.from_id, m.__class__.__name__, m.message ]) else: w = csv.writer(sys.stdout, delimiter=';') w.writerow([ "Date", "id", "Type", "Information", "Media", "Views" ]) for m in messages: if isinstance(m, telethon.tl.types.MessageService): if isinstance( m.action, telethon.tl.types. MessageActionChatEditPhoto): w.writerow([ m.date.isoformat(), m.id, m.__class__.__name__, "Channel Photo Changed", "No", "" ]) elif isinstance( m.action, telethon.tl.types. MessageActionChannelCreate): w.writerow([ m.date.isoformat(), m.id, m.__class__.__name__, "Channel Created", "No", "" ]) else: w.writerow([ m.date.isoformat(), m.id, m.__class__.__name__, m.action.__class__.__name__, "No", "" ]) else: if m.media is None: # message w.writerow([ m.date.isoformat(), m.id, m.__class__.__name__, m.message, "No", m.views ]) else: w.writerow([ m.date.isoformat(), m.id, m.__class__.__name__, m.message, "Yes", m.views ]) if args.dump: if not os.path.exists( os.path.join( args.dump, str(m.id) + '.jpg')): client.download_media( m.media, os.path.join( args.dump, str(m.id))) # Sleep to avoid being banned time.sleep(7) else: print("Not implemented yet, sorry!") elif args.subcommand == "users": # List users from a group try: entity = client.get_entity(args.ID) offset = 0 limit = args.limit all_participants = [] while True: participants = client.invoke( GetParticipantsRequest( entity, ChannelParticipantsSearch(''), offset, limit, hash=0)) if not participants.users: break all_participants.extend(participants.users) offset += len(participants.users) time.sleep( 1 ) # This line seems to be optional, no guarantees! except ChatAdminRequiredError: print( "You don't have required access rights to get this list" ) else: if args.format == "text": for p in all_participants: print("[+] User: %s (%s %s)" % (p.username, p.first_name, p.last_name)) elif args.format == "json": users = [u.to_dict() for u in all_participants] print( json.dumps(users, sort_keys=True, indent=4, default=json_serial)) else: print("Not implemented yet, sorry!") else: self.parser.print_help() else: self.parser.print_help()
#!/usr/bin/env python3 from telethon import TelegramClient, sync api_id = input("Enter api id: ") api_hash = input("Enter api hash: ") client = TelegramClient('scrape_room', api_id, api_hash) client.start() while True: room_name = input("Enter room name: ") room = client.get_entity(room_name) with open("{}_members.csv".format(room_name.strip("@")), "wb") as output: output.write("id,username,first_name,last_name\n".encode("utf-8")) for i, member in enumerate(client.iter_participants(room)): username = member.username if member.username is not None else "" first_name = member.first_name if member.first_name is not None else "" last_name = member.last_name if member.last_name is not None else "" output.write("{},{},\"{}\",\"{}\"\n".format( member.id, username, first_name, last_name).encode("utf-8")) if i % 100 == 0: print(".", end="") print()
try: client.send_code_request(phone_number) me = client.sign_in(phone_number,input('{}Masukan Code Anda {}>>{} '.format(hijau,abu,putih))) except SessionPasswordNeededError: password = input('{}Masukan Password 2fa Anda {}>>{} '.format(hijau,abu,putih)) me = client.start(phone_number,password) channel_username = '******' c = requests.session() ua = { 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36' } channel_entity = client.get_entity(channel_username) try: for ulang in range(999999999): sys.stdout.write('\r \r') sys.stdout.write('\r{}Mencoba Mengambil URL'.format(yellow2)) client.send_message(entity=channel_entity,message='🖥 Visit sites') sleep(3) message_history = client(GetHistoryRequest(peer=channel_entity,limit=1,offset_date=None,offset_id=0,max_id=0,min_id=0,add_offset=0,hash=0)) channel_id = message_history.messages[0].id if message_history.messages[0].message.find('Sorry, there are no new ads available.') != -1: sys.stdout.write('\r \r') sys.stdout.write('\r{}Iklan SUdah Habis Silahkan Coba Lagi Nanti\n'.format(red2)) break url = message_history.messages[0].reply_markup.rows[0].buttons[0].url sys.stdout.write('\r \r') sys.stdout.write('\r{}Visit To URL {}'.format(yellow2,putih)+url)
NiceMsg("Could not connect to mongodb") mydb = myclient[mongo_db] mycol = mydb[mongo_collection] mycolu = mydb[mongo_users] # Connect to telegram try: client.start() client.connect() except: NiceMsg("Could not connect to telegram") # Connect to channel and get posts try: channel_entity = client.get_entity(channel_name) posts = client( GetHistoryRequest(peer=channel_entity, limit=1000000, offset_date=0, offset_id=0, max_id=0, min_id=0, add_offset=0, hash=0)) except: NiceMsg("Could not connect to channel ", channel_name) NiceMsg("Read messages from chanel " + channel_name) # Initalise counter for records added