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()) 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 decorator(func): tbot.add_event_handler(func, events.UserUpdate(**args)) return func
def main(): logging.basicConfig(level=logging.ERROR) extract_configs() setup_telegram_connection() setup_sqlite_connection('logs.sqlite') @CLIENT.on(events.NewMessage()) async def handlerNewMessage(event): try: await record_message(event.message, CLIENT) except KeyboardInterrupt: raise except Exception as e: print(e) @CLIENT.on(events.ChatAction()) async def handlerChatAction(event): event_name = type(event.original_update.message.action).__name__ date = event.original_update.message.date date = date.strftime('%Y.%d.%m %H:%M:%S %a') attributes = event.original_update.message.action.__dict__ attributes['id'] = event.original_update.message.id attributes['to_id'] = list( event.original_update.message.to_id.__dict__.values())[ 0] ########### attributes['event_name'] = event_name attributes['date'] = date for k, v in attributes.items(): if type(v) == list: attributes[k] = str(v) columns = ','.join(str(e) for e in list(attributes.keys())) placeholders = ':' + ', :'.join( str(e) for e in list(attributes.keys())) CURSOR.execute( "INSERT INTO ChatActions (%s) VALUES (%s)" % (columns, placeholders), attributes) CONN.commit() @CLIENT.on(events.MessageEdited()) async def handlerMessageEdited(event): _id = event.message.id _to_id = list(event.message.to_id.__dict__.values())[0] _from_id = event.message.from_id _message = event.message.message _date = event.message.date.strftime('%Y.%d.%m %H:%M:%S %a') CURSOR.execute( "UPDATE Messages SET edited=1 WHERE to_id=:to_id AND id=:id", { 'id': _id, 'to_id': _to_id }) CURSOR.execute( "INSERT INTO Edited VALUES (:id, :to_id, :from_id, :message, :date)", { 'id': _id, 'to_id': _to_id, 'from_id': _from_id, 'message': _message, 'date': _date }) CONN.commit() @CLIENT.on(events.MessageDeleted()) async def handlerMessageDeleted(event): print(event) for i in range(len(event.deleted_ids)): attributes = [] values = [] attributes.append("id=" + str(event.deleted_ids[i])) values.append(str(event.deleted_ids[i])) if isinstance(event.original_update, UpdateDeleteChannelMessages): attributes.append("to_id=" + str(event.original_update.channel_id)) values.append(str(event.original_update.channel_id)) CURSOR.execute("UPDATE Messages SET deleted=1 WHERE %s" % ' AND '.join(attributes)) #for i in range(len(event.deleted_ids)): current_time = datetime.datetime.now() values.append(current_time.strftime('"%Y.%d.%m %H:%M:%S %a"')) CURSOR.execute("INSERT INTO Deleted VALUES (%s)" % ', '.join(values)) CONN.commit() @CLIENT.on(events.UserUpdate()) async def handlerUserUpdate(event): id = event.original_update.user_id try: user = (await CLIENT( GetFullUserRequest(await CLIENT.get_input_entity(id)))).user username = user.username first_name = user.first_name last_name = user.last_name except Exception as e: print(e) username = "" first_name = "" last_name = "" event_name = type(event.original_update).__name__ attributes = event.original_update.status.__dict__ if len(list(attributes.values())) > 0: date = list(attributes.values())[0] else: date = [0, 0, 0, 0, 0, 0] date = date.strftime('%Y.%d.%m %H:%M:%S %a') CURSOR.execute( "INSERT INTO UserUpdates VALUES(:id, :username, :firstName, :lastName, :update, :date)", { 'id': id, 'username': username, 'firstName': first_name, 'lastName': last_name, 'update': event_name, 'date': date }) CONN.commit() CLIENT.start() CLIENT.run_until_disconnected() CONN.close()