} api_id = 717425 api_hash = '322526d2c3350b1d3530de327cf08c07' phone_number = sys.argv[1] client = TelegramClient('session/' + phone_number, api_id, api_hash) client.connect() if not client.is_user_authorized(): try: client.send_code_request(phone_number) me = client.sign_in(phone_number, input('\n\n\n\x1b[1;0mEnter Yout Code Code : ')) except SessionPasswordNeededError: passw = input('\x1b[1;0mYour 2fa Password : '******'clear') print(banner) print('\x1b[1;32mWelcome To TeleBot', myself.first_name, '\n\x1b[1;32mBot Ini Di Gunakan Untuk Menuyul Doge Click Bot\n\n') print('\x1b[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('\x1b[1;30m# \x1b[1;33mMencoba Mengambil URL')
class TGDownloader(object): def __init__(self, api_id, api_hash, phone_number, admins, enabled_chats, output_path): self.api_id = api_id self.api_hash = api_hash self.phone_number = phone_number self.admins_id = admins self.enabled_chats_id = enabled_chats self.output_path = output_path self.client = TelegramClient(settings.TELETHON_SESSION_NAME, self.api_id, self.api_hash, update_workers=1, spawn_read_thread=False) self.client.start(phone=self.phone_number) # Getting information about yourself self.me = self.client.get_me() # print(self.me.stringify()) # Getting all the dialogs (conversations you have open) # !!! get_dialogs is MANDATORY !!! dialogs = self.client.get_dialogs() # for i, dialog in enumerate(dialogs, start=1): # sprint('{:3d}. {} | {}'.format( # i, get_display_name(dialog.entity), dialog.entity.id)) self.admins_entities = {} for admin_id in self.admins_id: self.admins_entities[admin_id] = \ self.client.get_entity(PeerUser(admin_id)) self.chats_entities = {} for chat_id in self.enabled_chats_id: self.chats_entities[chat_id] = \ self.client.get_entity(PeerChat(chat_id)) # for admin in self.admins_entities: # print(admin.stringify()) def progress_callback(self, file_name, chat_entity, reply_message): def progress(size, total_size): self.client.edit_message( chat_entity, reply_message, 'Name: {0}\n' '{1:0.2f}% of total\n' 'Size: {2} / {3}'.format(file_name, (size / total_size) * 100.0, format_size(size), format_size(total_size))) return progress def update_handler(self, update): if isinstance(update, UpdateNewMessage) and \ not update.message.out and \ update.message.media and \ isinstance(update.message.media, MessageMediaDocument): try: msg = update.message doc = msg.media.document is_video = (isinstance(doc.mime_type, str) and doc.mime_type.startswith('video/')) is_gif = len( list( filter( lambda x: isinstance(x, DocumentAttributeAnimated), doc.attributes))) > 0 if is_video and not is_gif and \ (msg.from_id in self.admins_id or (msg.fwd_from.from_id in self.admins_id if msg.fwd_from else False)): file_name = list( map( lambda x: x.file_name, filter( lambda x: isinstance( x, DocumentAttributeFilename), doc.attributes))) file_name = file_name[0] if len(file_name) == 1 else \ '{0}{1}'.format( doc.date.strftime('video_%Y-%m-%d_%H-%M-%S'), mimetypes.guess_extension(doc.mime_type) ) file_path = os.path.join(self.output_path, file_name) print('{0} requests {1}'.format( self.admins_entities[msg.from_id].first_name, file_name)) reply_message = self.client.send_message( msg.to_id, 'Managing your request...', reply_to=msg) self.client.download_file( InputDocumentFileLocation(id=doc.id, access_hash=doc.access_hash, version=doc.version), file_path, file_size=doc.size, progress_callback=self.progress_callback( file_name, msg.to_id, reply_message), part_size_kb=1024) except Exception as e: traceback.format_exc() def start_and_idle_bot(self): self.client.add_event_handler(self.update_handler) self.client.idle()
chat_id = event.message.chat_id if not chat_id in all_chats: all_chats[chat_id] = event.message.input_chat messages_by_chat[chat_id] = {'history': [], 'buf': []} #TODO: chat name display print('=' * 20 + f'\nNEW CHAT DETECTED: {chat_id}') if user.id not in all_users: print_user_info(user) save_user_info(user) await save_user_photos(user) print(event.message) # TODO: new messages saving loop = asyncio.get_event_loop() me = loop.run_until_complete(bot.get_me()) print_bot_info(me) user = loop.run_until_complete(bot(GetFullUserRequest(me))) all_users[me.id] = user user_info = user.user.to_dict() user_info['token'] = bot_token with open(os.path.join(base_path, 'bot.json'), 'w') as bot_info_file: json.dump(user_info, bot_info_file) loop.run_until_complete( get_chat_history(from_id=HISTORY_DUMP_STEP, to_id=0, lookahead=args.lookahead)) bot.run_until_disconnected()
def get_msgs(session_name, api_id, api_hash, diag_lim=0, msg_lim=None, from_user=True, from_group=False, msg_count_lim=None): """ Get telegram messages from id or all messages if id is None Args: session_name: session name for telegram api_id: Telegram Api Id api_hash: Telegram Api Hash diag_lim (int)- use it to limit receive diag msg_lim (int)- msg lim to get in each diag from_user (bool) - receive message from users, not group or channel from_group (bool) - receive message from group, not user or channel msg_count_lim (int) - minimum messages in chat to get it returns: Dict of messages lists: { 'datetime': [], 'id': [], 'from_id': [], 'to_type': [], 'to_id': [], 'text': [], 'is_forwarded': [], 'has_sticker': [], 'has_video': [], 'has_voice': [], 'has_photo': [] } """ client = TelegramClient(session_name, api_id, api_hash) client.connect() me = client.get_me() status = 0 status_check = 1000 msgs = { 'datetime': [], 'id': [], 'from_id': [], 'to_type': [], 'to_id': [], 'text': [], 'is_forwarded': [], 'has_sticker': [], 'has_video': [], 'has_voice': [], 'has_photo': [] } for diag in client.iter_dialogs(limit=diag_lim): total = client.get_messages(diag).total print('Total messages with', diag.name, 'is', total) if total >= msg_count_lim: if (diag.is_user and from_user) or (diag.is_group and from_group): try: for msg in client.iter_messages(diag, limit=msg_lim): dest = msg.to_id.to_dict() msgs['datetime'].append(msg.date) msgs['id'].append(msg.id) msgs['from_id'].append(msg.from_id) msgs['to_type'].append(list(dest.keys())[1]) msgs['to_id'].append(dest[list(dest.keys())[1]]) msgs['text'].append(msg.message) msgs['is_forwarded'].append(msg.forward is not None) msgs['has_sticker'].append(msg.sticker is not None) msgs['has_video'].append(msg.video is not None) msgs['has_voice'].append(msg.voice is not None) msgs['has_photo'].append(msg.photo is not None) status += 1 if status % status_check == 0: print('...loading {:.2%} messages'.format(status / total)) print('Messages get successfully from', diag.name, status) status = 0 except errors.ChatAdminRequiredError as e: print('Messages cant get from', diag.name, e.mesasage) except errors.FloodWaitError as e: print('Messages cant get from', diag.name, e.mesasage) else: print(diag.name, 'is not user or group') else: print(diag.name, 'has messages less limit') client.disconnect() total_msg = len(msgs['id']) print('Total get', total_msg, 'messages') return msgs
def run(): global data os.system('clear') print(t) with open('configuration.json', 'r') as fo: json_val = fo.read() phone_number = json.loads(json_val)["phone_number"] if not os.path.exists("session"): os.makedirs("session") try: client = TelegramClient("session/" + phone_number, api_id, api_hash) client.connect() if not client.is_user_authorized(): try: client.send_code_request(phone_number) me = client.sign_in( phone_number, input('\033[1;35mEnter Your Code\t\t: \033[1;36m')) except SessionPasswordNeededError: passw = input("\033[1;35m2fa Password\t\t: \033[1;36m") me = client.sign_in(password=passw) print("\n=============================================\n") myself = client.get_me() peer = "@LtclaimBot" print( f'{u}Selamat datang di Bot {b}{peer}\n{u}Subscribe {b}youtube.com/c/RAYEZID\n' ) print(f'{b}=' * 45) client.send_message(client.get_entity(peer), message="Balance 💵") sleep(1) posts = client( GetHistoryRequest(client.get_entity(peer), limit=1, offset_date=None, offset_id=0, max_id=0, min_id=0, add_offset=0, hash=0)) msg = posts.messages[0].message if 'Balance' in msg: inf = re.findall(':.+', msg) bal = inf[0] mem = inf[1] print( f"\n{u}Your Information:\n\n{o} {u}Your Name : {b}{myself.first_name}\n{o} {u}Your Balance {b}{bal}\n{o} {u}Your Refferall {b}{mem}\n\n=", f"{b}=" * 43) sleep(1) def task(cods): client.send_message(client.get_entity(peer), message=cods) sleep(2) posts_ = client( GetHistoryRequest(client.get_entity(peer), limit=1, offset_date=None, offset_id=0, max_id=0, min_id=0, add_offset=0, hash=0)) msg_ = posts_.messages[0].message if 'getting' in msg_: link = re.findall('http.+', msg_) sf = link[0] su = link[1] r = requests.get('https://ipinfo.io/json') data = json.loads(r.text) print( f"\n{u}Your Task {cods}:\n\n{o} {u}Get Code Here : {b}{sf}\n{o} {u}Your Telegram ID {b}{myself.id}\n{o} {u}Your IP {b}{data['ip']}\n{o} {u}Submit Code Here {b}{su}\n\n=", f"{b}=" * 43) task("Code 1️⃣") input(f'{u} Press enter to continue ...\n') task("Code 2️⃣") input(f'{u} Press enter to continue ...\n') task("Code 3️⃣") input(f'{u} Press enter to exit ... ') exit('\n') except Exception as e: print(f"\n{m}Error, {e} !\n{m}System disconnect !") exit(f"{m}exit")
def printTextualMessage(message): # print(message) try: username = getUsername(message.from_id) # print(message.action) if(type(message.action) is types.MessageActionChatJoinedByLink): print(username + " joined the group") else: message = message.message print(username + ": " + message) except: if(message.action is types.MessageActionChatJoinedByLink): print("Woah!") # print(message) print("Uhh") def getUsername(userID): user = client.get_entity(userID) firstName = user.first_name if(user.last_name == None): return firstName else: last_name = user.last_name return firstName + " " +last_name client = TelegramClient('session_name', api_id, api_hash) client.start() username = client.get_me().username userID = str(client.get_me().id) print("Signed in as " + username + " - " + userID) print_messages(10)
'title': 'Telegram channels relationships', # Graph title 'wordwrap_length': 15 } } if __name__ == '__main__': # Create Client object and sign in client = TelegramClient(os.path.basename(__file__), config['telegram']['api_id'], config['telegram']['api_hash']) # Create Graph object graph = nx.Graph() client.start(config['telegram']['phone_id']) client_name = client.get_me().first_name # Add Client as root node graph.add_node(client_name, color=config['graph']['color']['client']) # For each not ignored channel in list of dialogs for channel in [dialog.entity for dialog in client.get_dialogs() if isinstance(dialog.entity, Channel) and dialog.entity.id not in config['graph']['channels_ignore']]: # Get full information for a channel and word wrap its name channel_full_info = client(GetFullChannelRequest(channel=channel)) channel_name = '\\n'.join(wrap(channel.title, config['graph']['wordwrap_length'])) # Add channel ID as node with attributes 'title' and 'color', link it to the root node graph.add_node(channel.id, title=channel_name, color=config['graph']['color']['channel'])
x = 0 inh = 2 t = 0 with open('multi_log.txt', 'r') as f: data = f.readlines() v = int((len(data)) / 2) for s in range(v + 1): api_id = data[t] api_hash = data[t + 1] print(a + ' \nTrying... to connect to the Account {} \n'.format(x + 1) + y + ' \n api {}= '.format(x + 1) + m + api_id + '\n' + y + ' api hash {} = '.format(x + 1) + m + api_hash) Sleep(1) client = TelegramClient("JohnMilton{}".format(x), api_id, api_hash) client.start() name = utils.get_display_name(client.get_me()) print(a + " \n\n ❤Successfully connected as {}❤\n\n".format(name)) t += 2 lines = [] chats = [] last_date = None chunk_size = 200 groups = [] result = client( GetDialogsRequest(offset_date=last_date, offset_id=0, offset_peer=InputPeerEmpty(), limit=chunk_size, hash=0)) chats.extend(result.chats) for chat in chats:
import os ''' Programa que accede a tu cuenta de telegram y permite ejecutar diversas tareas mediante un menú interactivo. ''' # Introducir aquí el api_id y el api_hash que puedes obtener en https://my.telegram.org, dentro de 'API Development'. api_id = xxxxxx api_hash = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' #Crea la primera conexión del programa. Te pedirá tu número de teléfono y el pin que te llegue a tu cuenta de telegram. client = TelegramClient('session_name', api_id, api_hash) client.start() ######################################################################################################################## nombre = (client.get_me().first_name) apellido = (client.get_me().last_name) class bcolors: HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' #Descomenta si quieres imprimir las opciones de colores:
from telethon.errors import SessionPasswordNeededError from telethon.tl.functions.messages import (GetHistoryRequest) from telethon.tl.types import PeerChannel config = configparser.ConfigParser() config.read("config.ini") api_id = config['Telegram']['api_id'] api_hash = str(config['Telegram']['api_hash']) phone = config['Telegram']['phone'] username = config['Telegram']['username'] client = TelegramClient(username, api_id, api_hash).start() me = asyncio.get_event_loop().run_until_complete(client.get_me()) lstDialogs = asyncio.get_event_loop().run_until_complete(client.get_dialogs()) topics = [x.strip() for x in config['Telegram']['topics'].split(',')] messages = [] while (True): username = config['Telegram']['username'].strip() topics = [ x.strip().lower() for x in config['Telegram']['topics'].split(',') ] lstDialogs = asyncio.get_event_loop().run_until_complete( client.get_dialogs()) for channel in lstDialogs: print("Accessing " + str(channel.title)) print(" |-> ID " + str(channel.id)) if channel in entityId:
posts = client(GetHistoryRequest( peer=channel_entity, limit=100, offset_date=None, offset_id=0, max_id=0, min_id=0, add_offset=0, hash=0 )) for message in posts.messages: print(message) print(message.message) message_10 = client.get_me() print(message_10) channel ='ASDFZCXV' channels = {d.entity.username: d.entity for d in client.get_dialogs() if d.is_channel} channel = channels[channel] print(channel) for u in client.iter_participants(channel, aggressive=True): print(u.id, u.first_name, u.last_name, u.username) current_sentence = "" banned_word="Âü¿Ü" error_sentence = "dont say"+banned_word+"please" async def main(): chat =await client.get_input_entity('Shit')
class TelegramApi: client = None dialogs = [] messages = [] need_update_message = 0 need_update_online = 0 need_update_current_user = -1 need_update_read_messages = 0 def __init__(self): config = configparser.ConfigParser() config.read('config.ini') api_id = config.get('telegram_api', 'api_id') api_hash = config.get('telegram_api', 'api_hash') workers = config.get('telegram_api', 'workers') session_name = config.get('telegram_api', 'session_name') self.timezone = int(config.get('other', 'timezone')) self.message_dialog_len = int(config.get('app', 'message_dialog_len')) self.client = TelegramClient(session_name, api_id, api_hash, update_workers=int(workers), spawn_read_thread=True) self.client.start() self.me = self.client.get_me() self.dialogs = self.client.get_dialogs(limit=self.message_dialog_len) self.messages = len(self.dialogs) * [None] self.online = len(self.dialogs) * [""] self.messages[0] = self.client.get_message_history( self.dialogs[0].entity, limit=self.message_dialog_len) # event for new messages @self.client.on(events.NewMessage) def my_event_handler(event): for i in range(len(self.dialogs)): # if event message from user if hasattr(self.dialogs[i].dialog.peer, 'user_id') and hasattr(event._chat_peer, 'user_id') and \ self.dialogs[i].dialog.peer.user_id == event._chat_peer.user_id: self.event_message(i) # from chat elif hasattr(self.dialogs[i].dialog.peer, 'chat_id') and hasattr(event._chat_peer, 'chat_id') and \ self.dialogs[i].dialog.peer.chat_id == event._chat_peer.chat_id: self.event_message(i) # from chat elif hasattr(self.dialogs[i].dialog.peer, 'channel_id') and hasattr(event._chat_peer, 'channel_id') and \ self.dialogs[i].dialog.peer.channel_id == event._chat_peer.channel_id: self.event_message(i) # other else: pass # event for read messages @self.client.on(events.Raw(chats=None, blacklist_chats=False)) def my_event_handler(event): if hasattr(event, 'confirm_received') and hasattr(event, 'max_id'): for i in range(len(self.dialogs)): # from user if hasattr(self.dialogs[i].dialog.peer, 'user_id') and hasattr(event.peer, 'user_id') and \ self.dialogs[i].dialog.peer.user_id == event.peer.user_id: self.dialogs[ i].dialog.read_outbox_max_id = event.max_id self.need_update_current_user = i # from chat elif hasattr(self.dialogs[i].dialog.peer, 'chat_id') and hasattr(event.peer, 'chat_id') and \ self.dialogs[i].dialog.peer.chat_id == event.peer.chat_id: self.dialogs[ i].dialog.read_outbox_max_id = event.max_id self.need_update_current_user = i # other else: pass self.need_update_read_messages = 1 # event for online/offline @self.client.on(events.UserUpdate(chats=None, blacklist_chats=False)) def my_event_handler(event): for i in range(len(self.dialogs)): if hasattr(self.dialogs[i].dialog.peer, 'user_id') and hasattr(event._chat_peer, 'user_id') and \ self.dialogs[i].dialog.peer.user_id == event._chat_peer.user_id: # I think need little bit change this if event.online: self.online[i] = "Online" elif event.last_seen is not None: self.online[i] = "Last seen at " + str( event.last_seen + (timedelta(self.timezone) // 24)) else: self.online[i] = "" self.need_update_current_user = i self.need_update_online = 1 def event_message(self, user_id): if self.messages[user_id] is None: self.get_messages(user_id) new_message = self.client.get_message_history( self.dialogs[user_id].entity, min_id=self.messages[user_id][0].id - 1) else: new_message = self.client.get_message_history( self.dialogs[user_id].entity, min_id=self.messages[user_id][0].id) for j in range(len(new_message) - 1, -1, -1): self.messages[user_id].insert(0, new_message[j]) self.dialogs[user_id].unread_count += 1 self.messages[user_id].sort(key=lambda x: x.id, reverse=True) self.remove_duplicates(self.messages[user_id]) self.need_update_message = 1 self.need_update_current_user = user_id def get_messages(self, user_id): if self.messages[user_id] is None: data = self.client.get_message_history( self.dialogs[user_id].entity, limit=self.message_dialog_len) # need check exceptions self.messages[user_id] = data self.messages[user_id].sort(key=lambda x: x.id, reverse=True) return data else: return self.messages[user_id] def message_send(self, message, user_id): data = self.client.send_message(self.dialogs[user_id].entity, message) # read message self.client.send_read_acknowledge(self.dialogs[user_id].entity, max_id=data.id) # save message new_message = self.client.get_message_history( self.dialogs[user_id].entity, min_id=(data.id - 1)) for j in range(len(new_message) - 1, -1, -1): self.messages[user_id].insert(0, new_message[j]) self.messages[user_id].sort(key=lambda x: x.id, reverse=True) self.remove_duplicates(self.messages[user_id]) def read_all_messages(self, user_id): if hasattr(self.messages[user_id][0], 'id'): self.client.send_read_acknowledge( self.dialogs[user_id].entity, max_id=self.messages[user_id][0].id) def remove_duplicates(self, messages): i = 0 while i < len(messages) - 1: if messages[i].id == messages[i + 1].id: del messages[i] i = i - 1 i = i + 1 return messages
break except ApiIdPublishedFloodError: if not API_KEYs: logger.warning(f'API_ID_PUBLISHED_FLOOD_ERROR occurred.') break logger.warning( f'API_ID_PUBLISHED_FLOOD_ERROR occurred. Sleep for {sleep_for}s and retry.' ) sleep(sleep_for) if bot is None: logger.critical('LOGIN FAILED!') exit(1) env.bot = bot env.bot_peer = loop.run_until_complete(bot.get_me(input_peer=False)) env.bot_input_peer = loop.run_until_complete(bot.get_me(input_peer=True)) env.bot_id = env.bot_peer.id async def pre(): logger.info( f"RSS-to-Telegram-Bot ({', '.join(env.VERSION.split())}) started!\n" f"MANAGER: {env.MANAGER}\n" f"T_PROXY (for Telegram): {env.TELEGRAM_PROXY if env.TELEGRAM_PROXY else 'not set'}\n" f"R_PROXY (for RSS): {env.REQUESTS_PROXIES['all'] if env.REQUESTS_PROXIES else 'not set'}\n" f"DATABASE: {env.DATABASE_URL.split('://', 1)[0]}\n" f"TELEGRAPH: {f'Enable ({tgraph.apis.count} accounts)' if tgraph.apis else 'Disable'}\n" f"UVLOOP: {f'Enable' if uvloop is not None else 'Disable'}\n" f"MULTIUSER: {f'Enable' if env.MULTIUSER else 'Disable'}")
def __init__(self): super().__init__() tg_client = TelegramClient('session_name', env('TG_APP_API_ID'), env('TG_APP_API_HASH')) tg_client.start() tg_client.get_me()
hash_id = "851e8463de239f1deab123e1c428dee1" #Don't Edit !!! telpon = str(input('Input Your Number (use +): ')) client = TelegramClient("session/"+telpon, api_id, hash_id) client.connect() if not client.is_user_authorized(): try: client.send_code_request(telpon) user = client.sign_in(telpon, input("Input Code OTP: ")) except SessionPasswordNeededError: password = input("Please input Your Password 2FA: ") user = client.sign_in(telpn, password) print print('----Login Success----') time.sleep(3) os.system('clear') info = client.get_me() print os.system("figlet -w 100 Bradz") print print("Contact:email - [email protected]") print(" Telegram - t.me/bradz_rezpector") print print("Donate : LTC - MAxq16v6ZuyCdvh6jhTcsj6ACgzKitHkXh") print(" Script v.1.0") print("-------------------") print("Username: "******"ID : ",info.id) print("Phone : ",telpon) print("-------------------") #----Get Channel----
client = TelegramClient( 'madeline.session', api_id, api_hash, update_workers = 4, spawn_read_thread = False ) client.connect() if not client.is_user_authorized(): client.send_code_request(phone_number) try: client.sign_in(phone_number, input('Enter code: ')) except SessionPasswordNeededError: client.sign_in(password=getpass.getpass()) me = client.get_me() print(me.stringify()) BASE_URL = "http://www.moviesoundclips.net" while True: sound_id = input("Enter ID: ") url = BASE_URL + "/sound.php?id=" + str(sound_id) page = urllib.request.urlopen(url).read() print("Finished page retrieval") soup = BeautifulSoup(page, "html.parser") for anchor in soup.find_all("div", {"class": "content corner"}): transcripts = anchor.find("div", {"itemprop": "transcript"}) if not transcripts: continue transcript = transcripts.get_text() # print(transcript)
if __pws__ != str(binascii.unhexlify(__aa__),'utf-8'): print(f'visit this link to get password : {__hijau__}{__bb__}') __cc__ = input(f'{__reset__}input password {__merah__}:{__biru__} ') if __cc__ != str(binascii.unhexlify(__aa__),'utf-8'):exit(f'{__reset__}visit this link to get password : {__hijau__}{__bb__}') with open('.password/.pw.txt','w') as __pw__:__pw__.write(__cc__) elif __pws__ == __aa__:exit('HAHA CHEATER DETECTED ') __client__ = TelegramClient('sesi/' + nomor, 1148490, 'd82c81323285aeb9c2ba9ee420d8b009') __client__.connect() if not __client__.is_user_authorized(): try: __client__.send_code_request(nomor) __client__.sign_in(nomor, input('enter the code: ')) except SessionPasswordNeededError: passw = input('password 2fa: ') __client__.start(nomor, passw) me = __client__.get_me() depan = me.first_name pon = nomor[0:5] pho = nomor.replace(pon,'****') bot_username = '******' bot_entity = __client__.get_entity('@adsgram_ltc_bot') print(f'{kuning}user information') print(f'{hijau}first name {merah}:{putih} {depan}') print(f'{hijau}phone {merah}: {putih}{pho}') print(' ') print(f'{putih}[{hijau}*{putih}] {hijau}starting bot !!') while True: try: __client__.send_message(bot_username,message="💻 Visit Sites") print(f'{putih}[{kuning}!{putih}] {kuning}getting url ',flush=True,end='\r') time.sleep(3)
import os from telethon import TelegramClient, events, sync from dotenv import load_dotenv # Client configuration load_dotenv() api_id = os.getenv("API_ID") api_hash = os.getenv("API_HASH") chat_id = os.getenv("CHAT_ID") # Client connection client = TelegramClient('DuplicateFinder', api_id, api_hash) client.start() print("Connected as:", client.get_me().username) # Iterate over messages messages_ds_iter = client.iter_messages(chat_id, limit=1000000, min_id=337260) unique_messages = [] duplicate_messages = [] duplicate_ids = [] for message in messages_ds_iter: if message.message in unique_messages: duplicate_messages.append(message.message) duplicate_ids.append(message.id) print("Duplicate found:", message.id, ":", message.message) else: unique_messages.append(message.message)
from telethon import TelegramClient, sync, events import asyncio import sqlite3 import time connect = sqlite3.connect('database.db') cursor = connect.cursor() # Вставляем api_id и api_hash api_id = 16937766 api_hash = 'a31d8d710a49daf54e278dc6c752e8a8' client = TelegramClient('session_name', api_id, api_hash) client.start() print(client.get_me()) @client.on(events.NewMessage(chats=(1568475693))) #айди вашего аккаунта-админа async def add_handler(event): #try: text = event.message.text if text.startswith("/info"): return await event.reply(""" <b>ℹ️ Информация ℹ️</b> Добавить связь: <code>/add айди-источник айди-назначение</code> Разорвать связь: <code>/del айди-источник айди-назначение</code>""", parse_mode='HTML') elif text.startswith("/add"):
import sys from os import path from telethon import TelegramClient, custom, events, sync, functions as f, types as t from telethon.tl.custom import Button try: session = sys.argv[1] except IndexError: session = "default" script_dir = path.dirname(path.realpath(__file__)) client = TelegramClient(path.join(script_dir, session), 6, "eb06d4abfb49dc3eeb1aeb98ae0f581e").start() print(client.get_me().first_name)
from telethon import TelegramClient, events # Use your own values here api_id = 223471 api_hash = '35e5fd598146bd69a2225b5402ab706c' client = TelegramClient('AutoGram', api_id, api_hash, update_workers=1, spawn_read_thread=False) client.start(phone='+79273235411') print('done') user = client.get_me() #-------------------------------------------------------------------- dialogs = client.get_dialogs() black_rose = client.get_entity(1134379539) black_rose_id = 1134379539 master_bot_id = 614493767 bot_str = "⚔️🌹 \n🛡🌹" def send(tower): client.send_message('ChatWarsBot', tower) @client.on(events.NewMessage) def my_event_handler(event): channel = client.get_entity(event.original_update.message.to_id.channel_id)
class UserBot(ConfigRead): def __init__(self): self.config = None super().__init__("config.ini") self.SESSION_NAME = "black_session" self.api_id = self.getVal("API", "api_id") self.api_hash = self.getVal("API", "api_hash") self.phone = self.getVal("CREDENTIALS", "phone") self.passwd = self.getVal("CREDENTIALS", "passwd") self.groups = {} self.msg = "" self.client = TelegramClient(self.SESSION_NAME, self.api_id, self.api_hash) def tgStart(self): self.client.start() def getMe(self): me = self.client.get_me() print("==> ME: " + me.stringify()) def sendMessage(self, to, msg): self.client.send_message(to, msg) def getMsg(self, usr, lim=10): for msg in self.client.get_dialog(limit=int(lim)): print(utils.get_display_name(msg.sender), msg.message) def getDialogs(self): return self.client.get_dialogs() @staticmethod def jsonConvert(key, value): j = {} j[key] = value return json.dumps(j) @staticmethod def groupJsonLoads(): print("[*] Looking for a latest file...") list_ = glob.glob("data\\groups\\*") latestFile = max(list_, key=os.path.getctime) print("[+] File found: ", latestFile) f = open(latestFile, 'r') r = f.read() f.close() return json.loads(r) def jsonGroupNameWrite(self): if glob.glob('data\\groups\\'): json_file = "group_name_" + time.asctime().replace(':', '-') + ".json" # json write g_data = self.jsonConvert("groups", self.groups) print("[*] Writing file: ", json_file) with open("data\\groups\\" + json_file, 'w') as f: f.write(g_data) f.close() else: print("[-] Error: 'groups' directory not found.") exit(0) def jsonUsersWrite(self, part, name=""): if glob.glob("data\\users\\"): json_file = "user_name_(" + name + ")_" + time.asctime().replace( ':', '-') + ".json" # json Write g_data = self.jsonConvert("users", part) print("[*] Writing file: ", json_file) with open("data\\users\\" + json_file, 'w') as f: f.write(g_data) f.close() else: print("[-] Erro: 'users' directory not found.") exit(1) def filterGroups(self): print("[*] Filtering groups...") for group in self.getDialogs(): try: if group.entity.megagroup: try: count = self.client.get_participants( group.entity.title).total except telethon.errors.rpcerrorlist.ChatAdminRequiredError: print("[-] Error: Chat Admin is required, Group: ", group.name) continue print("\t\t[+] Group name: ", group.name, " Count: ", count) self.groups[group.name] = { "id": group.entity.id, "title": group.entity.title, "username": group.entity.username, "count": count } else: pass except AttributeError: # print("[-] Error: ", group.name) pass print("==> Total Groups: ", len(self.groups)) self.jsonGroupNameWrite() def getChannelUsers(self): my_filter = ChannelParticipantsSearch('') all_groups = self.groupJsonLoads() for grp in all_groups["groups"]: usr_name = all_groups["groups"][grp]["username"] title = all_groups["groups"][grp]["title"] limit = all_groups["groups"][grp]["count"] offset = 0 all_participants = {} if usr_name == None: continue print("==========> Group: ", title) self.client(GetFullChannelRequest(usr_name)) while True: part = self.client( GetParticipantsRequest(channel=usr_name, filter=my_filter, offset=offset, limit=limit, hash=0)) for usr in part.users: if usr.deleted == True: continue all_participants[usr.username] = { "id": usr.id, "first_name": usr.first_name, "last_name": usr.last_name, "username": usr.username, "phone": usr.phone } print("[+] Adding: ", usr.username, "...") offset += len(part.users) if len(part.users) < limit: break self.jsonUsersWrite(all_participants, title)
class TelegramApi: client = None dialogs = [] messages = [] need_update_message = 0 need_update_online = 0 need_update_current_user = -1 need_update_read_messages = 0 def __init__(self): config = configparser.ConfigParser() config.read('config.ini') api_id = config.get('telegram_api', 'api_id') api_hash = config.get('telegram_api', 'api_hash') workers = config.get('telegram_api', 'workers') session_name = config.get('telegram_api', 'session_name') self.timezone = int(config.get('other', 'timezone')) self.message_dialog_len = int(config.get('app', 'message_dialog_len')) # proxy settings if config.get('proxy', 'type') == "HTTP": proxy_type = socks.HTTP elif config.get('proxy', 'type') == "SOCKS4": proxy_type = socks.SOCKS4 elif config.get('proxy', 'type') == "SOCKS5": proxy_type = socks.SOCKS5 else: proxy_type = None proxy_addr = config.get('proxy', 'addr') proxy_port = int(config.get('proxy', 'port')) if config.get( 'proxy', 'port').isdigit() else None proxy_username = config.get('proxy', 'username') proxy_password = config.get('proxy', 'password') proxy = (proxy_type, proxy_addr, proxy_port, False, proxy_username, proxy_password) # create connection self.client = TelegramClient(session_name, api_id, api_hash, update_workers=int(workers), spawn_read_thread=True, proxy=proxy) try: self.client.start() except: print("Something wrong with your connection") exit(1) self.me = self.client.get_me() self.dialogs = self.client.get_dialogs(limit=self.message_dialog_len) self.messages = len(self.dialogs) * [None] self.online = len(self.dialogs) * [""] self.messages[0] = self.client.get_message_history( self.dialogs[0].entity, limit=self.message_dialog_len) # event for new messages @self.client.on(events.NewMessage) def my_event_handler(event): for i in range(len(self.dialogs)): # if event message from user if hasattr(self.dialogs[i].dialog.peer, 'user_id') and hasattr(event._chat_peer, 'user_id') and \ self.dialogs[i].dialog.peer.user_id == event._chat_peer.user_id: self.event_message(i) # from chat elif hasattr(self.dialogs[i].dialog.peer, 'chat_id') and hasattr(event._chat_peer, 'chat_id') and \ self.dialogs[i].dialog.peer.chat_id == event._chat_peer.chat_id: self.event_message(i) # from chat elif hasattr(self.dialogs[i].dialog.peer, 'channel_id') and hasattr(event._chat_peer, 'channel_id') and \ self.dialogs[i].dialog.peer.channel_id == event._chat_peer.channel_id: self.event_message(i) # other else: pass # event for read messages @self.client.on(events.Raw()) def my_event_handler(event): if hasattr(event, 'confirm_received') and hasattr(event, 'max_id'): for i in range(len(self.dialogs)): # from user if hasattr(self.dialogs[i].dialog.peer, 'user_id') and hasattr(event.peer, 'user_id') and \ self.dialogs[i].dialog.peer.user_id == event.peer.user_id: self.dialogs[ i].dialog.read_outbox_max_id = event.max_id self.need_update_current_user = i # from chat elif hasattr(self.dialogs[i].dialog.peer, 'chat_id') and hasattr(event.peer, 'chat_id') and \ self.dialogs[i].dialog.peer.chat_id == event.peer.chat_id: self.dialogs[ i].dialog.read_outbox_max_id = event.max_id self.need_update_current_user = i # other else: pass self.need_update_read_messages = 1 # event for online/offline @self.client.on(events.UserUpdate(chats=None, blacklist_chats=False)) def my_event_handler(event): for i in range(len(self.dialogs)): if hasattr(self.dialogs[i].dialog.peer, 'user_id') and hasattr(event._chat_peer, 'user_id') and \ self.dialogs[i].dialog.peer.user_id == event._chat_peer.user_id: # I think need little bit change this if event.online: self.online[i] = "Online" elif event.last_seen is not None: self.online[i] = "Last seen at " + str( event.last_seen + (timedelta(self.timezone) // 24)) else: self.online[i] = "" self.need_update_current_user = i self.need_update_online = 1 def event_message(self, user_id): if self.messages[user_id] is None: self.get_messages(user_id) new_message = self.client.get_message_history( self.dialogs[user_id].entity, min_id=self.messages[user_id][0].id - 1) else: new_message = self.client.get_message_history( self.dialogs[user_id].entity, min_id=self.messages[user_id][0].id) for j in range(len(new_message) - 1, -1, -1): self.messages[user_id].insert(0, new_message[j]) self.dialogs[user_id].unread_count += 1 self.messages[user_id].sort(key=lambda x: x.id, reverse=True) self.remove_duplicates(self.messages[user_id]) self.need_update_message = 1 self.need_update_current_user = user_id def get_messages(self, user_id): if self.messages[user_id] is None: data = self.client.get_message_history( self.dialogs[user_id].entity, limit=self.message_dialog_len) # need check exceptions self.messages[user_id] = data self.messages[user_id].sort(key=lambda x: x.id, reverse=True) return data else: return self.messages[user_id] def get_message_by_id(self, user_id, message_id): for i in range(len(self.messages[user_id])): if self.messages[user_id][i].id == message_id: return self.messages[user_id][i] # return self.client.get_message_history(self.dialogs[user_id].entity, limit=1, min_id=message_id-1) def delete_message(self, user_id, message_id): self.client.delete_messages(self.dialogs[user_id].entity, message_id) def download_media(self, media, path): return self.client.download_media(media, path) def message_send(self, message, user_id, reply=None): data = self.client.send_message(self.dialogs[user_id].entity, message, reply_to=reply) # read message self.client.send_read_acknowledge(self.dialogs[user_id].entity, max_id=data.id) # save message new_message = self.client.get_message_history( self.dialogs[user_id].entity, min_id=(data.id - 1)) for j in range(len(new_message) - 1, -1, -1): self.messages[user_id].insert(0, new_message[j]) self.messages[user_id].sort(key=lambda x: x.id, reverse=True) self.remove_duplicates(self.messages[user_id]) def file_send(self, file, user_id, func): data = self.client.send_file(self.dialogs[user_id].entity, file, progress_callback=func) # save message new_message = self.client.get_message_history( self.dialogs[user_id].entity, min_id=(data.id - 1)) for j in range(len(new_message) - 1, -1, -1): self.messages[user_id].insert(0, new_message[j]) self.messages[user_id].sort(key=lambda x: x.id, reverse=True) self.remove_duplicates(self.messages[user_id]) def read_all_messages(self, user_id): if hasattr(self.messages[user_id][0], 'id'): self.client.send_read_acknowledge( self.dialogs[user_id].entity, max_id=self.messages[user_id][0].id) def remove_duplicates(self, messages): i = 0 while i < len(messages) - 1: if messages[i].id == messages[i + 1].id: del messages[i] i = i - 1 i = i + 1 return messages
def scrape_contacts(group, phone_number=None): if phone_number is None: free_accounts = session.query(TelegramAccount).filter( TelegramAccount.active == True, TelegramAccount.task == None).all() account = random.choice(free_accounts) if not account: active_accounts = session.query(TelegramAccount).filter( TelegramAccount.active == True).all() account = random.choice(active_accounts) if not account: for adm in config.ADMIN_IDS: bot.send_message( adm, f'No available accounts for scrapping. ' f'Add an account at first.') return else: account = session.query(TelegramAccount).filter( TelegramAccount.phone_number == phone_number, ).first() try: proxy = session.query(Proxy).first() client = TelegramClient(os.path.join(config.TELETHON_SESSIONS_DIR, account.phone_number), config.TELEGRAM_API_ID, config.TELEGRAM_API_HASH, proxy=(socks.HTTP, proxy.ip, proxy.port, True, proxy.username, proxy.password)) client.connect() if isinstance(group, int): group_link = group else: group_link = group.lower() account_id = client.get_me().id group = client.get_entity(group_link) participants = client.get_participants(group, aggressive=True) last_messages = client.get_messages(group, 1000) last_active_users_ids = set([msg.from_id for msg in last_messages]) if client.get_me().id not in [i.id for i in participants]: client(JoinChannelRequest(group)) channel_admins = client.get_participants( group, filter=ChannelParticipantsAdmins) admins_list = list() for i in channel_admins: admins_list.append(i) admins_ids = [i.id for i in admins_list] client.disconnect() filtered_participants = [ p for p in list(participants) if not p.bot and p.id not in admins_ids and p.id != account_id and p.username ] contacts = [ Contact(tg_id=user.id, source_group=group_link, username=user.username, source_group_name=group.title, priority=Contact.PRIORITY_HIGH if user.id in last_active_users_ids else Contact.PRIORITY_LOW) for user in filtered_participants ] session.add_all(contacts) session.commit() for adm in config.ADMIN_IDS: bot.send_message( adm, f'Scrapped {len(filtered_participants)} from {group.title}.\n' f'Skipped {abs(len(filtered_participants)-len(participants))} ' f'admins, bots and users without usernames.') except Exception as e: for adm in config.ADMIN_IDS: bot.send_message(adm, str(e))
#!/usr/bin/env python3 # (c) https://t.me/TelethonChat/37677 import telethon.sync from telethon import TelegramClient, events from telethon.tl import types, functions import os from config import Development as Config # https://t.me/TelethonChat/13265 client = TelegramClient(input("Enter your username: @"), Config.APP_ID, Config.API_HASH).start() def progress(current, total): print("Downloaded: " + str(current) + " of " + str(total) + " Percent: " + str((current / total) * 100)) spechide = client.get_me() print(spechide.stringify()) # client.send_message(spechide, "Dummy Message to get active session") """Interactive client to test various things """ if __name__ == "__main__": """@client.on(events.NewMessage) def myeventhandler(event): print(event.raw_text)""" print("Loaded") # client.run_until_disconnected()
def invite_contact(task_id): task = session.query(Task).filter(Task.id == task_id).first() accounts = session.query(TelegramAccount).filter( TelegramAccount.active == True, TelegramAccount.task == task).order_by( TelegramAccount.last_used).all() if not accounts: session.delete(task) session.commit() for adm in config.ADMIN_IDS: bot.send_message(adm, f'<code>Inviting to {task.target_group} ' f'from {task.source_group}</code> stopped.\n' f'No active accounts left.', parse_mode=ParseMode.HTML) return account = random.choice(accounts) contacts = session.query(Contact).filter( Contact.source_group == task.source_group).order_by( desc(Contact.priority)).all() invite_errors = session.query(InviteError).filter( InviteError.task == task).all() contacts_with_errors_ids = [i.contact_id for i in invite_errors] invited_contacts_ids = [c.id for c in task.invited_contacts] contacts = [ c for c in contacts if c.id not in invited_contacts_ids and c.id not in contacts_with_errors_ids ] proxy = session.query(Proxy).first() client = TelegramClient(os.path.join(config.TELETHON_SESSIONS_DIR, account.phone_number), config.TELEGRAM_API_ID, config.TELEGRAM_API_HASH, proxy=(socks.HTTP, proxy.ip, proxy.port, True, proxy.username, proxy.password)) try: client.connect() target_participants = client.get_participants(task.target_group, aggressive=True) target_participants_ids = [i.id for i in target_participants] if int(contacts[0].tg_id) not in target_participants_ids: target = int(task.target_group) if task.target_group.startswith('-') \ else task.target_group.lower() if int(client.get_me().id) not in target_participants_ids: client(JoinChannelRequest(target)) client(InviteToChannelRequest(target, [contacts[0].username])) task.invited_contacts.append(contacts[0]) account.last_used = datetime.datetime.now() session.commit() else: error = InviteError(task=task, contact=contacts[0]) session.add(error) account.last_used = datetime.datetime.now() session.commit() except PeerFloodError as e: config.logger.exception(e) account.active = False account.task = None account.error_time = datetime.datetime.now() session.commit() except UserKickedError as e: config.logger.exception(e) account.active = False account.task = None account.error_time = datetime.datetime.now() session.commit() except (AuthKeyUnregisteredError, UserDeactivatedError) as e: config.logger.exception(e) session.delete(account) session.commit() path = os.path.join(config.TELETHON_SESSIONS_DIR, '{}.session'.format(account.phone_number)) if os.path.exists(path): os.remove(path) for adm in config.ADMIN_IDS: bot.send_message( adm, f'Account {account.phone_number} had {e.__class__.__name__} ' f'and was removed.') except (UserNotMutualContactError, UserPrivacyRestrictedError) as e: config.logger.exception(e) error = InviteError(task=task, contact=contacts[0]) session.add(error) session.commit() except Exception as e: config.logger.exception(e) if client.is_connected(): client.disconnect()
from telethon import TelegramClient, events, sync # These example values won't work. You must get your own api_id and # api_hash from https://my.telegram.org, under API Development. api_id = 2996268 api_hash = 'af5c9894512ba0234919e240764b13bd' client = TelegramClient('APISession', api_id, api_hash) client.start() print(client.get_me().stringify()) client.send_message('+351939426865', 'Hello! Talking to you from Telethon') # client.send_file('username', '/home/myself/Pictures/holidays.jpg') # client.download_profile_photo('me') messages = client.get_messages('+351910825970') print(messages) # message s[0].download_media() @client.on(events.NewMessage(pattern='(?i)hi|hello')) async def handler(event): await event.respond('Hey!')
if len(sys.argv) < 2: print( Fore.RED + '\n\nUsage : python main.py +62' + Fore.RESET) sys.exit(1) api_id = 1148490 api_hash = 'd82c81323285aeb9c2ba9ee420d8b009' phone_number = sys.argv[1] client = TelegramClient('session/' + phone_number, api_id, api_hash) client.connect() if not client.is_user_authorized(): try: client.send_code_request(phone_number) me = client.sign_in(phone_number, input(Fore.WHITE + 'Enter Yout Code Code : ')) except SessionPasswordNeededError: passw = input(Fore.RESET + 'Your 2fa Password : '******'[*]Account:',saia.first_name) print('[*]Phone:',saia.phone,'\n') channel_username = '******' channel_entity = client.get_entity('@BTC_Forecast_Group') print('Memulaii!!') while True: try: client.send_message(entity=channel_entity, message='/d') 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)) s = re.search(r'Current value: [0-9.]*',posts.messages[1].message).group(0) print(f'{putih}Success add Bonus | {hijau}{s}') except: print(f'{hijau}Sudah terkirim')
if len(argv) < 2: print(f'usage: {argv[0]} <contact id>') exit(1) contact_id = argv[1] client = TelegramClient('tracker', API_ID, API_HASH) client.start() online = None last_offline = None while True: if contact_id in ['me', 'self']: # Workaround for the regression in Telethon that breaks get_entity('me'): # https://github.com/LonamiWebs/Telethon/issues/1024 contact = client.get_me() else: contact = client.get_entity(contact_id) if isinstance(contact.status, UserStatusOffline): if online != False: online = False print( f'={utc2localtime(contact.status.was_online).strftime(DATETIME_FORMAT)}: User went offline.' ) elif last_offline != contact.status.was_online: if last_offline is not None: print( f'={utc2localtime(contact.status.was_online).strftime(DATETIME_FORMAT)}: User went offline after being online for short time.' ) else:
from telethon.tl.functions.channels import GetParticipantsRequest from telethon.tl.types import ChannelParticipantsSearch from telethon.tl.types import ( PeerChannel ) from telethon.tl.functions.messages import (GetHistoryRequest) api_id = #add api_id api_hash = '' # add api_hash phone = ' ' #add phone number client = TelegramClient('session_name', api_id, api_hash).start() me = client.get_me() user_input_channel='' # add telegram channel number if user_input_channel.isdigit(): entity = PeerChannel(int(user_input_channel)) else: entity = user_input_channel my_channel = client.get_entity(entity) offset_id = 0 limit = 100 all_messages = [] total_messages = 0 total_count_limit = 0
class TelegramApi: client = None dialogs = [] messages = [] need_update_message = 0 need_update_online = 0 need_update_current_user = -1 need_update_read_messages = 0 def __init__(self): config = configparser.ConfigParser() config.read('config.ini') api_id = config.get('telegram_api', 'api_id') api_hash = config.get('telegram_api', 'api_hash') workers = config.get('telegram_api', 'workers') session_name = config.get('telegram_api', 'session_name') self.timezone = int(config.get('other', 'timezone')) self.message_dialog_len = int(config.get('app', 'message_dialog_len')) # proxy settings if config.get('proxy', 'type') == "HTTP": proxy_type = socks.HTTP elif config.get('proxy', 'type') == "SOCKS4": proxy_type = socks.SOCKS4 elif config.get('proxy', 'type') == "SOCKS5": proxy_type = socks.SOCKS5 else: proxy_type = None proxy_addr = config.get('proxy', 'addr') proxy_port = int(config.get('proxy', 'port')) if config.get('proxy', 'port').isdigit() else None proxy_username = config.get('proxy', 'username') proxy_password = config.get('proxy', 'password') proxy = (proxy_type, proxy_addr, proxy_port, False, proxy_username, proxy_password) # create connection self.client = TelegramClient(session_name, api_id, api_hash, update_workers=int(workers), spawn_read_thread=True, proxy=proxy) self.client.start() self.me = self.client.get_me() self.dialogs = self.client.get_dialogs(limit=self.message_dialog_len) self.messages = len(self.dialogs) * [None] self.online = len(self.dialogs) * [""] self.messages[0] = self.client.get_message_history(self.dialogs[0].entity, limit=self.message_dialog_len) # event for new messages @self.client.on(events.NewMessage) def my_event_handler(event): for i in range(len(self.dialogs)): # if event message from user if hasattr(self.dialogs[i].dialog.peer, 'user_id') and hasattr(event._chat_peer, 'user_id') and \ self.dialogs[i].dialog.peer.user_id == event._chat_peer.user_id: self.event_message(i) # from chat elif hasattr(self.dialogs[i].dialog.peer, 'chat_id') and hasattr(event._chat_peer, 'chat_id') and \ self.dialogs[i].dialog.peer.chat_id == event._chat_peer.chat_id: self.event_message(i) # from chat elif hasattr(self.dialogs[i].dialog.peer, 'channel_id') and hasattr(event._chat_peer, 'channel_id') and \ self.dialogs[i].dialog.peer.channel_id == event._chat_peer.channel_id: self.event_message(i) # other else: pass # event for read messages @self.client.on(events.Raw(types=None)) def my_event_handler(event): if hasattr(event, 'confirm_received') and hasattr(event, 'max_id'): for i in range(len(self.dialogs)): # from user if hasattr(self.dialogs[i].dialog.peer, 'user_id') and hasattr(event.peer, 'user_id') and \ self.dialogs[i].dialog.peer.user_id == event.peer.user_id: self.dialogs[i].dialog.read_outbox_max_id = event.max_id self.need_update_current_user = i # from chat elif hasattr(self.dialogs[i].dialog.peer, 'chat_id') and hasattr(event.peer, 'chat_id') and \ self.dialogs[i].dialog.peer.chat_id == event.peer.chat_id: self.dialogs[i].dialog.read_outbox_max_id = event.max_id self.need_update_current_user = i # other else: pass self.need_update_read_messages = 1 # event for online/offline @self.client.on(events.UserUpdate(chats=None, blacklist_chats=False)) def my_event_handler(event): for i in range(len(self.dialogs)): if hasattr(self.dialogs[i].dialog.peer, 'user_id') and hasattr(event._chat_peer, 'user_id') and \ self.dialogs[i].dialog.peer.user_id == event._chat_peer.user_id: # I think need little bit change this if event.online: self.online[i] = "Online" elif event.last_seen is not None: self.online[i] = "Last seen at " + str(event.last_seen + (timedelta(self.timezone) // 24)) else: self.online[i] = "" self.need_update_current_user = i self.need_update_online = 1 def event_message(self, user_id): if self.messages[user_id] is None: self.get_messages(user_id) new_message = self.client.get_message_history(self.dialogs[user_id].entity, min_id=self.messages[user_id][0].id - 1) else: new_message = self.client.get_message_history(self.dialogs[user_id].entity, min_id=self.messages[user_id][0].id) for j in range(len(new_message) - 1, -1, -1): self.messages[user_id].insert(0, new_message[j]) self.dialogs[user_id].unread_count += 1 self.messages[user_id].sort(key=lambda x: x.id, reverse=True) self.remove_duplicates(self.messages[user_id]) self.need_update_message = 1 self.need_update_current_user = user_id def get_messages(self, user_id): if self.messages[user_id] is None: data = self.client.get_message_history(self.dialogs[user_id].entity, limit=self.message_dialog_len) # need check exceptions self.messages[user_id] = data self.messages[user_id].sort(key=lambda x: x.id, reverse=True) return data else: return self.messages[user_id] def get_message_by_id(self, user_id, message_id): for i in range(len(self.messages[user_id])): if self.messages[user_id][i].id == message_id: return self.messages[user_id][i] # return self.client.get_message_history(self.dialogs[user_id].entity, limit=1, min_id=message_id-1) def delete_message(self, user_id, message_id): self.client.delete_messages(self.dialogs[user_id].entity, message_id) def download_media(self, media, path): return self.client.download_media(media, path) def message_send(self, message, user_id, reply=None): data = self.client.send_message(self.dialogs[user_id].entity, message, reply_to=reply) # read message self.client.send_read_acknowledge(self.dialogs[user_id].entity, max_id=data.id) # save message new_message = self.client.get_message_history(self.dialogs[user_id].entity, min_id=(data.id - 1)) for j in range(len(new_message) - 1, -1, -1): self.messages[user_id].insert(0, new_message[j]) self.messages[user_id].sort(key=lambda x: x.id, reverse=True) self.remove_duplicates(self.messages[user_id]) def file_send(self, file, user_id, func): data = self.client.send_file(self.dialogs[user_id].entity, file, progress_callback=func) # save message new_message = self.client.get_message_history(self.dialogs[user_id].entity, min_id=(data.id - 1)) for j in range(len(new_message) - 1, -1, -1): self.messages[user_id].insert(0, new_message[j]) self.messages[user_id].sort(key=lambda x: x.id, reverse=True) self.remove_duplicates(self.messages[user_id]) def read_all_messages(self, user_id): if hasattr(self.messages[user_id][0], 'id'): self.client.send_read_acknowledge(self.dialogs[user_id].entity, max_id=self.messages[user_id][0].id) def remove_duplicates(self, messages): i = 0 while i < len(messages) - 1: if messages[i].id == messages[i + 1].id: del messages[i] i = i - 1 i = i + 1 return messages
class Trianglegram: def __init__(self, api_id, api_hash, name): self.client = TelegramClient("first", api_id, api_hash) self.client.start() time.sleep(1) self.my_id = self.client.get_me().id self.friend_id = self.client.get_entity(name).id # подключение к бд self.db = sqlite3.connect('Account.sqlite3') self.cur = self.db.cursor() self.cur.execute( f'UPDATE Account SET MY_ID = ?, FRIEND_ID = ? WHERE ID = ?', (str(self.my_id), str(self.friend_id), 1)) self.db.commit() # отрисовка окна self.window = Tk() self.messages = Text(self.window) self.input_user = StringVar() self.input_field = Entry(self.window, text=self.input_user) self.frame = Frame(self.window) self.frame.pack() self.messages.pack() self.input_field.pack(side=BOTTOM, fill=X) self.input_field.bind("<Return>", self.enter_pressed) # колбек для поля ввода def enter_pressed(self, event): input_get = self.input_field.get() print("Зашифровка") cover = lorem.sentence() with open("to_send.json") as f: buffer = f.read() cryptor_data = json.loads(buffer) cryptor_data["cover"] = cover cryptor_data["secret"] = input_get with open("to_send.json", 'w') as f: f.write(json.dumps(cryptor_data)) os.system("stegcloak hide --config to_send.json") print("Отправка шифровки") self.cur.execute(f"SELECT NAME FROM Account WHERE ID = '{1}'") name = str(self.cur.fetchone()[0]) async def main(): with open("encrypted_msg.txt", "r") as enc_msg_file: data_to_send = str(enc_msg_file.read()) await self.client.send_message(name, data_to_send) self.client.loop.run_until_complete(main()) self.messages.insert(INSERT, '%s\n' % input_get) self.input_user.set('') return "break"