def get_cached_client(): """Gets an authorized TelegramClient, performing the authorization process if it's the first time""" global cached_client if not cached_client: print('Loading client...') settings = load_settings() cached_client = TelegramClient(session_user_id=settings.get('session_name', 'anonymous'), api_id=settings['api_id'], api_hash=settings['api_hash']) cached_client.connect() # Then, ensure we're authorized and have access if not cached_client.is_user_authorized(): # Import the login window locally to avoid cyclic dependencies from gui.windows import LoginWindow print('First run, client not authorized. Sending code request.') cached_client.send_code_request(str(settings['user_phone'])) start_app(LoginWindow, client=cached_client, phone=settings['user_phone']) del LoginWindow print('Client loaded and authorized.') return cached_client
class PushTelegram(Pusher): def __init__(self): config = configparser.ConfigParser() config.read('../conf/config.ini') api_id = config['TELEGRAM']['api_id'] api_hash = config['TELEGRAM']['api_hash'] print(api_id,' ',api_hash) self.telegram = TelegramClient("BitCoinDev", api_id, api_hash) self.telegram.connect() if not self.telegram.is_user_authorized(): self.telegram.send_code_request('+821097950344') self.telegram.sign_in('+821097950344', input('Enter the code: ')) def send_message(self, username = None, message = None): self.telegram.send_message(username, message)
print('CTRL-C To exit') print('CTRL-C To exit') print('CTRL-C To exit') print('To test me, type a coin into the cryptoping telegram bot window on telegram such as #LTC and #DASH') print('The Telegram updates in a while loop, and creates a pid equialent... delete coin.run if exiting in the middle of a sell signal') threads = [] flag = "test" variable = "test" api_id = 189914 api_hash = '75b1fbdede4c49f7b7ca4a8681d5dfdf' # 'session_id' can be 'your_name'. It'll be saved as your_name.session client = TelegramClient('session_id', api_id, api_hash) client.connect() # PUT YOUR PHONE NUMBER ASSICOATED WITH TELEGRAM BELOW google voice works... if not client.is_user_authorized(): client.send_code_request('+14698447320') client.sign_in('+14698447320', input('Enter code: ')) # Now you can use the connected client as you wish def generate_random_long(): import random return random.choice(range(0,10000000)) def update_handler(d): global flag global variable # On this example, we just show the update object itself
import logging import getpass logging.basicConfig(level=logging.INFO) if api_id == '' or api_hash == '': logging.fatal( "You must assign a API before using this script! 在登录前你必须给定ID和HASH @ data.py" ) logging.info("Trying to Login to Telegram... 正在尝试登录...") client = TelegramClient('session_file', api_id, api_hash, update_workers=1, spawn_read_thread=False) client.connect() if client.is_user_authorized() is not True: logging.info( 'You have not login yet, Trying to log you in... 没有活跃的登录Session,尝试登录...' ) logging.info( 'if you have 2FA password, please enter right now. This Password will not be stored | 如果你有两步认证密码,请现在输入。这个密码不会被保存' ) password = getpass.getpass() if password != '': client.start(password=password) else: client.start()
from telethon import TelegramClient from telethon.tl.types import InputPeerChat from telethon.tl.functions.messages import GetHistoryRequest import csv api_id = 92095 api_hash = 'e33fd27a8b4fd13829cd5e9e6444d562' phone = '+4746397700' client = TelegramClient('session_name', api_id, api_hash) client.connect() if not client.is_user_authorized(): client.sign_in(phone=phone) client.sign_in(phone, input('Enter the code: ')) channel = client.get_entity('t.me/joinchat/CWuF8EA8ZNIn60hzbU4low') zh_full = client( GetHistoryRequest(peer=channel, offset_id=0, offset_date=None, add_offset=0, limit=20000, max_id=0, min_id=0)) output = [] for m in zh_full.messages: if hasattr(m, 'message'): row = (m.from_id, client.get_entity(m.from_id).username,
# 2) The session file exists and the session is logged out # 3) The session file doesn't exist # # The script handles these cases in the following way: # 1) Session is logged in: print "true" # 2) Session is logged out: print "false" # 3) Session is logged out: print "false" # # Output: the script prints to stdout "true" if the session is logged in, and # "false" otherwise. #------------------------------------------------------------------------------# import telethon.sync from telethon import TelegramClient import sys import os.path api_id = sys.argv[1] api_hash = sys.argv[2] session_name = sys.argv[3] if not os.path.exists(session_name + ".session"): print("false") else: client = TelegramClient(session_name, api_id, api_hash) client.connect() if client.is_user_authorized(): print("true") else: print("false")
def main(): if not sys.argv[1] or not sys.argv[2] or not sys.argv[3]: return enable_win_unicode_console() config = configparser.RawConfigParser(allow_no_value = True) config.read('signals_listener.ini') session_name = config['main']['session_fname'] api_id = sys.argv[1] api_hash = sys.argv[2] phone = sys.argv[3] try: signals_preload = sys.argv[4] if signals_preload is not None and signals_preload != '': signals_preload = int(signals_preload) else: signals_preload = -1 except: signals_preload = -1 global signal_expr global signal_separator global signal_coin1_variants global signal_coin2_variants global log if signals_preload < 0: signals_preload = int(config['channels']['signals_preload_default']) signal_separator = str(config['channels']['signal_separator']) signal_coin1_variants = str(config['channels']['signal_coin1_variants']) signal_coin2_variants = str(config['channels']['signal_coin2_variants']) debug_mode = int(config['main']['debug_mode']) > 0 log_file_name = str(config['main']['log_file']) log_run_file_name = str(config['main']['log_run_file']) proxy_use = int(config['main']['use_proxy']) proxy_type = str(config['main']['proxy_type']) proxy_host = str(config['main']['proxy_host']) proxy_port = str(config['main']['proxy_port']) proxy_login = str(config['main']['proxy_login']) proxy_password = str(config['main']['proxy_password']) if proxy_port: proxy_port = int(proxy_port) if debug_mode: log = io.open('./' + log_file_name,'w+',encoding='utf8') log.write("Starting log:\n") else: log = None channels, signal_expr = loadChanDataFromConfig(config) if proxy_use > 0 and proxy_host and proxy_port > 0: if not proxy_type: proxy_type = 'SOCKS5' print('Using '+proxy_type+' proxy: ' + proxy_host + ':' + str(proxy_port)) if proxy_type == 'SOCKS4': proxy_type = socks.SOCKS4 elif proxy_type == 'HTTP': proxy_type = socks.HTTP else: proxy_type = socks.SOCKS5 if proxy_login or proxy_password: proxy = (proxy_type, proxy_host, proxy_port, True, proxy_login, proxy_password) else: proxy = (proxy_type, proxy_host, proxy_port) else: proxy = None client = TelegramClient( session_name, api_id=api_id, api_hash=api_hash, proxy=proxy, update_workers=1, spawn_read_thread=True ) print('Connecting to Telegram servers...') try: if not client.connect(): print('Initial connection failed. Retrying...') if not client.connect(): print('Could not connect to Telegram servers.') return except: print('Could not connect to Telegram servers.') return if not client.is_user_authorized(): client.send_code_request(phone) print('Enter the code ('+phone+'): ') code = input() client.sign_in(phone, code) print(client.session.server_address) # Successfull chan_index = 0 while chan_index < len(channels): print(channels[chan_index].title) channels[chan_index].entity = checkCurchan(channels[chan_index], client, signals_preload) if channels[chan_index].entity: @client.on(events.NewMessage(chats=[channels[chan_index].entity], incoming=True)) def normal_handler(event): if log: log.write(">>>\n") log.write(str(event)) log.write("<<<\n") separateCheck(event.text, getChannelTitleForEvent(channels, event), getChannelRatingForEvent(channels, event), dateFix(event.message.date), client) time.sleep(1) chan_index = chan_index + 1 if log: chan_index = 0 while chan_index < len(channels): log.write("\n") log.write(str(channels[chan_index].entity)) chan_index = chan_index + 1 log.close() log = None log = io.open('./' + log_run_file_name,'w+',encoding='utf8') log.write("Runtime log:\n") print('------------------') while True: time.sleep(0.1)
def download_media(pSection_config): if not 'name' in pSection_config: logging.error('The Section Name not especified! Aborting section') return ## Geting download path if not 'download_path' in pSection_config: lDownload_path = gDownload_path + '/' + pSection_config['name'] else: lDownload_path = pSection_config['download_path'] if lDownload_path[1] != '/': lDownload_path = gRoot_path + lDownload_path if not os.path.isdir(lDownload_path): os.mkdir(lDownload_path) logging.info('Creating Download Dir: ' + lDownload_path) else: logging.info('Using Download Dir: ' + lDownload_path) lDownload_path = lDownload_path + '/' if lDownload_path[-1] != '/' else '' lApi_id = pSection_config[ 'api_id'] if 'api_id' in pSection_config else gApi_id lApi_hash = pSection_config[ 'api_hash'] if 'api_hash' in pSection_config else gApi_hash lPhone_number = pSection_config[ 'phone_number'] if 'phone_number' in pSection_config else gPhone_number if not (lApi_hash and lApi_id and lPhone_number): logging.error('Authentication data not Set!') logging.error('Stopping import for' + pSection_config['name']) return if not 'channel_username' in pSection_config or not pSection_config[ 'channel_username']: logging.warning('Channel User Name not valid for ' + pSection_config['name']) return lSession_name = lPhone_number[1:] lLimit = int(pSection_config['messages_limit'] ) if 'messages_limit' in pSection_config else 10 lExtensions = pSection_config[ 'filter'] if 'filter' in pSection_config else None lTimestamp_name = pSection_config[ 'timestamp_name'] if 'timestamp_name' in pSection_config else gTimestamp_name # Log in to Telegram and create a client object to use for getting data # Create the client and connect client = TelegramClient(lSession_name, lApi_id, lApi_hash) client.start() logging.info("Client Created") # Ensure you're authorized if not client.is_user_authorized(): logging.info('Requesting new Code!') client.send_code_request(lPhone_number) try: logging.info('Gettign from user new telegram code') client.sign_in(lPhone_number, input('Enter the code: ')) except SessionPasswordNeededError: logging.info('Getting MFA Password') client.sign_in(password=input('Password: '******'Starting get Messages one by one') #Get last "messages_limit" messages from channel/group lItemsCount = 0 for msg in client.get_messages(pSection_config['channel_username'], limit=lLimit): if msg.media is not None: if lExtensions: if msg.file.ext in lExtensions: logging.info(msg.sender.title, msg.text) lMediaFile = msg.file.name if lMediaFile == None: lMediaFile = lDownload_path + msg.file.media.date.strftime( '%Y-%m-%d_%I-%M-%S') + msg.file.ext else: if lTimestamp_name: lMediaFile = lDownload_path + msg.file.media.date.strftime( '%Y-%m-%d_%I-%M-%S-') + lMediaFile else: lMediaFile = lDownload_path + lMediaFile logging.info('Download File: ' + lMediaFile) if os.path.isfile(lMediaFile): localSize = os.path.getsize(lMediaFile) remoteSize = msg.file.size if localSize < remoteSize: logging.info('Deleting incompleted Download!') os.remove(lMediaFile) else: logging.info( 'Skiping Download: File already exists!') continue client.download_media(message=msg, file=lMediaFile) lItemsCount += 1 else: logging.info('Ignoring Media "' + msg.text + '" due Filter Config') logging.info('Finish process') logging.info('Items Downloaded: ' + str(lItemsCount))
class TGInformer: def __init__( self, account_id=None, db_prod_ip=None, db_prod_port=None, db_prod_name=None, db_prod_user=None, db_prod_password=None, db_local_ip=None, db_local_port=None, db_local_name=None, db_local_user=None, db_local_password=None, tg_notifications_channel_id=None, google_credentials_path=None, google_sheet_name=None, ): # ------------------ # Instance variables # ------------------ self.keyword_list = [] self.channel_list = [] self.channel_meta = {} self.bot_task = None self.KEYWORD_REFRESH_WAIT = 15 * 60 self.MIN_CHANNEL_JOIN_WAIT = 30 self.MAX_CHANNEL_JOIN_WAIT = 120 self.bot_uptime = 0 # -------------- # Display banner # -------------- print(""" ____ ____ / _/___ / __/___ _________ ___ ___ _____ / // __ \/ /_/ __ \/ ___/ __ `__ \/ _ \/ ___/ _/ // / / / __/ /_/ / / / / / / / / __/ / /___/_/ /_/_/ \____/_/ /_/ /_/ /_/\___/_/ by @paulpierre 11-26-2019 """) # ------------------------------------------------ # Check if we're in app engine and set environment # ------------------------------------------------ if os.getenv('GAE_INSTANCE'): self.SERVER_MODE = 'prod' # prod vs local self.MYSQL_CONNECTOR_STRING = 'mysql+mysqlconnector://{}:{}@{}:{}/{}'.format( db_prod_user, db_prod_password, db_prod_ip, db_prod_port, db_prod_name) else: self.SERVER_MODE = 'local' self.MYSQL_CONNECTOR_STRING = 'mysql+mysqlconnector://{}:{}@{}:{}/{}'.format( db_local_user, db_local_password, db_local_ip, db_local_port, db_local_name) logging.info('SERVER_MODE: {} GAE_ENV: {}'.format( self.SERVER_MODE, str(os.getenv('GAE_INSTANCE')))) # ----------------------------------------- # Set the channel we want to send alerts to # ----------------------------------------- self.monitor_channel = tg_notifications_channel_id if not account_id: logging.error('Must specify account_id for bot instance') return # ----------------------- # Initialize Google Sheet # ----------------------- scope = [ 'https://www.googleapis.com/auth/spreadsheets', 'https://www.googleapis.com/auth/drive' ] creds = ServiceAccountCredentials.from_json_keyfile_name( google_credentials_path, scope) self.gsheet = gspread.authorize(creds) self.sheet = self.gsheet.open(google_sheet_name).sheet1 # ------------------- # Initialize database # ------------------- self.engine = db.create_engine( self.MYSQL_CONNECTOR_STRING) # , echo=True self.Session = sessionmaker(bind=self.engine) self.session = self.Session() # -------------------- # Load account from DB # -------------------- self.tg_user = None try: self.account = self.session.query(Account).filter_by( account_id=account_id).first() except ProgrammingError as e: logging.error('Database is not set up, setting it up') build_database.initialize_db() self.account = self.session.query(Account).filter_by( account_id=account_id).first() if not self.account: logging.error( 'Invalid account_id {} for bot instance'.format(account_id)) sys.exit(0) # ---------------------- # Telegram service login # ---------------------- logging.info('Logging in with account # {}'.format( self.account.account_phone)) session_file = 'session/' + self.account.account_phone.replace('+', '') self.client = TelegramClient(session_file, self.account.account_api_id, self.account.account_api_hash) # ----------------------- # Authorize from terminal # ----------------------- # TODO: automate authcode with the Burner API self.client.connect() if not self.client.is_user_authorized(): logging.info('Client is currently not logged in, please sign in!') self.client.send_code_request(self.account.account_phone) self.tg_user = self.client.sign_in(self.account.account_phone, input('Enter code: ')) # ============= # Get all users # ============= def get_channel_all_users(self, channel_id): # TODO: this function is not complete channel = self.client.get_entity(PeerChat(channel_id)) users = self.client.get_participants(channel) print('total users: {}'.format(users.total)) for user in users: if user.username is not None and not user.is_self: print(utils.get_display_name(user), user.username, user.id, user.bot, user.verified, user.restricted, user.first_name, user.last_name, user.phone, user.is_self) # ===================== # Get # of participants # ===================== async def get_channel_user_count(self, channel): data = await self.client.get_entity(PeerChannel(-channel)) users = await self.client.get_participants(data) return users.total # ======================= # Get channel by group ID # ======================= def get_channel_info_by_group_id(self, id): channel = self.client.get_entity(PeerChat(id)) return { 'channel_id': channel.id, 'channel_title': channel.title, 'is_broadcast': False, 'is_mega_group': False, 'channel_access_hash': None, } # ========================== # Get channel by channel URL # ========================== async def get_channel_info_by_url(self, url): logging.info('{}: Getting channel info with url: {}'.format( sys._getframe().f_code.co_name, url)) channel_hash = utils.parse_username(url)[0] # ----------------------------------------- # Test if we can get entity by channel hash # ----------------------------------------- try: channel = await self.client.get_entity(channel_hash) except ValueError: logging.info('{}: Not a valid telegram URL: {}'.format( sys._getframe().f_code.co_name, url)) return False except FloodWaitError as e: logging.info('{}: Got a flood wait error for: {}'.format( sys._getframe().f_code.co_name, url)) await asyncio.sleep(e.seconds * 2) return { 'channel_id': channel.id, 'channel_title': channel.title, 'is_broadcast': channel.broadcast, 'is_mega_group': channel.megagroup, 'channel_access_hash': channel.access_hash, } # =================== # Get user info by ID # =================== async def get_user_by_id(self, user_id=None): u = await self.client.get_input_entity(PeerUser(user_id=user_id)) user = await self.client(GetFullUserRequest(u)) logging.info('{}: User ID {} has data:\n {}\n\n'.format( sys._getframe().f_code.co_name, user_id, user)) return { 'username': user.user.username, 'first_name': user.user.first_name, 'last_name': user.user.last_name, 'is_verified': user.user.verified, 'is_bot': user.user.bot, 'is_restricted': user.user.restricted, 'phone': user.user.phone, } # ============================== # Initialize keywords to monitor # ============================== def init_keywords(self): keywords = self.session.query(Keyword).filter_by( keyword_is_enabled=True).all() for keyword in keywords: self.keyword_list.append({ 'id': keyword.keyword_id, 'name': keyword.keyword_description, 'regex': keyword.keyword_regex }) logging.info('{}: Monitoring keywords: {}'.format( sys._getframe().f_code.co_name, json.dumps(self.keyword_list, indent=4))) # =========================== # Initialize channels to join # =========================== async def init_monitor_channels(self): # --------------------- # Let's start listening # --------------------- @self.client.on(events.NewMessage) async def message_event_handler(event): await self.filter_message(event) # ----------------------------- # Update the channel data in DB # ----------------------------- current_channels = [] # Lets iterate through all the open chat channels we have async for dialog in self.client.iter_dialogs(): channel_id = dialog.id # As long as it is not a chat with ourselves if not dialog.is_user: # Certain channels have a prefix of 100, lets remove that if str(abs(channel_id))[:3] == '100': channel_id = int(str(abs(channel_id))[3:]) # Lets add it to the current list of channels we're in current_channels.append(channel_id) logging.info('id: {} name: {}'.format(dialog.id, dialog.name)) logging.info('{}: ### Current channels {}'.format( sys._getframe().f_code.co_name, json.dumps(current_channels))) # ----------------------------------- # Get the list of channels to monitor # ----------------------------------- self.session = self.Session() account = self.session.query(Account).first() monitors = self.session.query(Monitor).filter_by( account_id=account.account_id).all() channels_to_monitor = [] for monitor in monitors: channel_data = { 'channel_id': monitor.channel.channel_id, 'channel_name': monitor.channel.channel_name, 'channel_title': monitor.channel.channel_title, 'channel_url': monitor.channel.channel_url, 'account_id': monitor.channel.account_id, 'channel_is_megagroup': monitor.channel.channel_is_mega_group, 'channel_is_group': monitor.channel.channel_is_group, 'channel_is_private': monitor.channel.channel_is_private, 'channel_is_broadcast': monitor.channel.channel_is_broadcast, 'channel_access_hash': monitor.channel.channel_access_hash, 'channel_size': monitor.channel.channel_size, 'channel_is_enabled': monitor.channel.channel_is_enabled, 'channel_tcreate': monitor.channel.channel_tcreate } if monitor.channel.channel_is_enabled is True: channels_to_monitor.append(channel_data) self.session.close() # ------------------------------- # Iterate through channel objects # ------------------------------- for channel in channels_to_monitor: self.session = self.Session() channel_obj = self.session.query(Channel).filter_by( channel_id=channel['channel_id']).first() # ------------------------------- # We have sufficient channel data # ------------------------------- if channel['channel_id']: self.channel_list.append(channel['channel_id']) logging.info( 'Adding channel {} to monitoring w/ ID: {} hash: {}'. format(channel['channel_name'], channel['channel_id'], channel['channel_access_hash'])) self.channel_meta[channel['channel_id']] = { 'channel_id': channel['channel_id'], 'channel_title': channel['channel_title'], 'channel_url': channel['channel_url'], 'channel_size': 0, 'channel_texpire': datetime.now() + timedelta(hours=3) } else: # ------------------------ # If not grab channel data # ------------------------ if channel['channel_url'] and '/joinchat/' not in channel[ 'channel_url']: o = await self.get_channel_info_by_url( channel['channel_url']) # ----------------------------- # If channel is invalid, ignore # ----------------------------- if o is False: logging.error('Invalid channel URL: {}'.format( channel['channel_url'])) continue logging.info('{}: ### Successfully identified {}'.format( sys._getframe().f_code.co_name, channel['channel_name'])) # ------------------------- # If the channel is a group # ------------------------- elif channel['channel_is_group']: o = await self.get_channel_info_by_group_id( channel['channel_id']) logging.info('{}: ### Successfully identified {}'.format( sys._getframe().f_code.co_name, channel['channel_name'])) else: logging.info('{}: Unable to indentify channel {}'.format( sys._getframe().f_code.co_name, channel['channel_name'])) continue channel_obj.channel_id = o['channel_id'] channel_obj.channel_title = o['channel_title'] channel_obj.channel_is_broadcast = o['is_broadcast'] channel_obj.channel_is_mega_group = o['is_mega_group'] channel_obj.channel_access_hash = o['channel_access_hash'] self.channel_meta[o['channel_id']] = { 'channel_id': o['channel_id'], 'channel_title': o['channel_title'], 'channel_url': channel['channel_url'], 'channel_size': 0, 'channel_texpire': datetime.now() + timedelta(hours=3) } # ------------------------------- # Determine is channel is private # ------------------------------- channel_is_private = True if ( channel['channel_is_private'] or '/joinchat/' in channel['channel_url']) else False if channel_is_private: logging.info( 'channel_is_private: {}'.format(channel_is_private)) # ------------------------------------------ # Join if public channel and we're not in it # ------------------------------------------ if channel[ 'channel_is_group'] is False and channel_is_private is False and channel[ 'channel_id'] not in current_channels: logging.info('{}: Joining channel: {} => {}'.format( sys._getframe().f_code.co_name, channel['channel_id'], channel['channel_name'])) try: await self.client( JoinChannelRequest(channel=await self.client. get_entity(channel['channel_url']))) sec = randrange(self.MIN_CHANNEL_JOIN_WAIT, self.MAX_CHANNEL_JOIN_WAIT) logging.info('sleeping for {} seconds'.format(sec)) await asyncio.sleep(sec) except FloodWaitError as e: logging.info( 'Received FloodWaitError, waiting for {} seconds..'. format(e.seconds)) # Lets wait twice as long as the API tells us for posterity await asyncio.sleep(e.seconds * 2) except ChannelPrivateError as e: logging.info( 'Channel is private or we were banned bc we didnt respond to bot' ) channel['channel_is_enabled'] = False # ------------------------------------------ # Join if private channel and we're not in it # ------------------------------------------ elif channel_is_private and channel[ 'channel_id'] not in current_channels: channel_obj.channel_is_private = True logging.info('{}: Joining private channel: {} => {}'.format( sys._getframe().f_code.co_name, channel['channel_id'], channel['channel_name'])) # ------------------------------------- # Join private channel with secret hash # ------------------------------------- channel_hash = channel['channel_url'].replace( 'https://t.me/joinchat/', '') try: await self.client( ImportChatInviteRequest(hash=channel_hash)) # ---------------------- # Counter FloodWaitError # ---------------------- sec = randrange(self.MIN_CHANNEL_JOIN_WAIT, self.MAX_CHANNEL_JOIN_WAIT) logging.info('sleeping for {} seconds'.format(sec)) await asyncio.sleep(sec) except FloodWaitError as e: logging.info( 'Received FloodWaitError, waiting for {} seconds..'. format(e.seconds)) await asyncio.sleep(e.seconds * 2) except ChannelPrivateError as e: logging.info( 'Channel is private or we were banned bc we didnt respond to bot' ) channel['channel_is_enabled'] = False except UserAlreadyParticipantError as e: logging.info('Already in channel, skipping') self.session.close() continue # --------------------------------- # Rollback session if we get a dupe # --------------------------------- try: self.session.commit() except IntegrityError: self.session.rollback() except InterfaceError: pass self.session.close() logging.info('{}: Monitoring channels: {}'.format( sys._getframe().f_code.co_name, json.dumps(self.channel_list, indent=4))) logging.info('Channel METADATA: {}'.format(self.channel_meta)) # =========================== # Filter the incoming message # =========================== async def filter_message(self, event): # If this is a channel, grab the channel ID if isinstance(event.message.to_id, PeerChannel): channel_id = event.message.to_id.channel_id # If this is a group chat, grab the chat ID elif isinstance(event.message.to_id, PeerChat): channel_id = event.message.chat_id else: # Message comes neither from a channel or chat, lets skip return # Channel values from the API are signed ints, lets get ABS for consistency channel_id = abs(channel_id) message = event.raw_text # Lets check to see if the message comes from our channel list if channel_id in self.channel_list: # Lets iterate through our keywords to monitor list for keyword in self.keyword_list: # If it matches the regex then voila! if re.search(keyword['regex'], message, re.IGNORECASE): logging.info( 'Filtering: {}\n\nEvent raw text: {} \n\n Data: {}'. format(channel_id, event.raw_text, event)) # Lets send the notification with all the pertinent information in the params await self.send_notification(message_obj=event.message, event=event, sender_id=event.sender_id, channel_id=channel_id, keyword=keyword['name'], keyword_id=keyword['id']) # ==================== # Handle notifications # ==================== async def send_notification(self, sender_id=None, event=None, channel_id=None, keyword=None, keyword_id=None, message_obj=None): message_text = message_obj.message # Lets set the meta data is_mention = message_obj.mentioned is_scheduled = message_obj.from_scheduled is_fwd = False if message_obj.fwd_from is None else True is_reply = False if message_obj.reply_to_msg_id is None else True is_bot = False if message_obj.via_bot_id is None else True if isinstance(message_obj.to_id, PeerChannel): is_channel = True is_group = False is_private = False elif isinstance(message_obj.to_id, PeerChat): is_channel = False is_group = True is_private = False else: is_channel = False is_group = False is_private = False # We track the channel size and set it to expire after sometime, if it does we update the participant size if channel_id in self.channel_meta and self.channel_meta[channel_id][ 'channel_size'] == 0 or datetime.now( ) > self.channel_meta[channel_id]['channel_texpire']: logging.info('refreshing the channel information') channel_size = await self.get_channel_user_count(channel_id) else: channel_size = self.channel_meta[channel_id]['channel_size'] # Lets get who sent the message sender = await event.get_sender() sender_username = sender.username channel_id = abs(channel_id) timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S") # Set the message for the notification we're about to send in our monitor channel message = '⚠️ "{}" mentioned by {} in => "{}" url: {}\n\n Message:\n"{}\ntimestamp: {}'.format( keyword, sender_username, self.channel_meta[channel_id]['channel_title'], self.channel_meta[channel_id]['channel_url'], message_text, timestamp) logging.info('{} Sending notification {}'.format( sys._getframe().f_code.co_name, message)) # ---------------- # Send the message # ---------------- await self.client.send_message(self.monitor_channel, message) # ------------------------- # Write to the Google Sheet # ------------------------- self.sheet.append_row([ sender_id, sender_username, channel_id, self.channel_meta[channel_id]['channel_title'], self.channel_meta[channel_id]['channel_url'], keyword, message_text, is_mention, is_scheduled, is_fwd, is_reply, is_bot, is_channel, is_group, is_private, channel_size, timestamp ]) # -------------- # Add user to DB # -------------- o = await self.get_user_by_id(sender_id) self.session = self.Session() if not bool( self.session.query(ChatUser).filter_by( chat_user_id=sender_id).all()): self.session.add( ChatUser(chat_user_id=sender_id, chat_user_is_bot=o['is_bot'], chat_user_is_verified=o['is_verified'], chat_user_is_restricted=o['is_restricted'], chat_user_first_name=o['first_name'], chat_user_last_name=o['last_name'], chat_user_name=o['username'], chat_user_phone=o['phone'], chat_user_tlogin=datetime.now(), chat_user_tmodified=datetime.now())) # ----------- # Add message # ----------- msg = Message(chat_user_id=sender_id, account_id=self.account.account_id, channel_id=channel_id, keyword_id=keyword_id, message_text=message_text, message_is_mention=is_mention, message_is_scheduled=is_scheduled, message_is_fwd=is_fwd, message_is_reply=is_reply, message_is_bot=is_bot, message_is_group=is_group, message_is_private=is_private, message_is_channel=is_channel, message_channel_size=channel_size, message_tcreate=datetime.now()) self.session.add(msg) self.session.flush() message_id = msg.message_id self.session.add( Notification(keyword_id=keyword_id, message_id=message_id, channel_id=channel_id, account_id=self.account.account_id, chat_user_id=sender_id)) # ----------- # Write to DB # ----------- try: self.session.commit() except IntegrityError: pass self.session.close() async def update_keyword_list(self): # ------------------------------ # Lets update keywords in memory # ------------------------------ # TODO: functionality to poll the DB for new keywords and refresh in memory logging.info('### updating keyword_list') pass # =========================== # Loop we run while we listen # =========================== async def bot_interval(self): self.init_keywords() await self.init_monitor_channels() while True: logging.info('### Running bot interval') await self.update_keyword_list() await asyncio.sleep(self.KEYWORD_REFRESH_WAIT) def stop_bot_interval(self): self.bot_task.cancel() # =========================== # Initialize connection to TG # =========================== def init(self): loop = asyncio.get_event_loop() self.bot_task = loop.create_task(self.bot_interval()) with self.client: self.client.run_until_disconnected() try: loop.run_until_complete(self.bot_task) except asyncio.CancelledError: logging.info('### Async cancelled') pass
def account(): reg_form = forms.RegistrationForm() new_acc_form = forms.newAccountForm() #check if registration form was submitted if reg_form.submit_reg.data and reg_form.validate_on_submit(): current_app.database.registration(reg_form.username.data, reg_form.password.data) return redirect(url_for('account')) #check if new telegram acc form was submitted if new_acc_form.submit_acc.data and new_acc_form.validate_on_submit(): api_keys = current_app.database.get_api_keys() api_id, api_hash = api_keys['api_id'], api_keys['api_hash'] #create new TelegramClient for this number and request activation try: data = new_acc_form.data unique_key = str(uuid4()) client = TelegramClient(unique_key, api_id, api_hash) clients_list[data['phone']] = client #creating another process in case of laggs request_sign_in(data['phone']) current_app.database.add_account(new_acc_form.data, unique_key) except: clients_list.pop(data['phone'], None) flash('Some error occured, try again.', 'registration error') pass return redirect(url_for('account')) #activating or removing account if request.form: if request.form.get('action', None) == 'Activate' and request.form['code'] != '': #activating account through TelegramClient that we created earlier for this number client = clients_list.get(request.form['phone'], None) if client == None: flash('Some error with activation.', 'activating error') client.disconnect() else: try: # connect and use given code client.connect() client.sign_in(code=request.form['code']) time.sleep(0.5) if not client.is_user_authorized(): # authorization failed client.disconnect() raise Exception( "Looks like there was a wrong code? user not authorized." ) client.disconnect() # if it is ok, add account to db current_app.database.activate_account( request.form['phone']) clients_list.pop(request.form['phone'], None) except Exception as e: print(e) client.disconnect() flash('Wrong code or some error occured.', 'activating error') # user requested deleting of acc elif request.form.get('action', None) == 'Remove': current_app.database.del_account(request.form['phone']) all_accounts = [ account for account in current_app.database.get_accounts_list() ] return render_template('account.html', reg_form=reg_form, new_acc_form=new_acc_form, all_accounts=all_accounts)
if BlueLoad("Telegram", "DATA/DATA") == "1": Telegram = True try: from telethon import TelegramClient, utils except: import os print("Module Telethon, not installed, starting Installation...") os.system("pip3 install --user telethon") print("Module Telethon Installed, please restart APP...") api_id = 291651 api_hash = '0f734eda64f8fa7dea8ed9558fd447e9' client = TelegramClient('telepygram', api_id, api_hash) isConnected = client.connect() # return True print("Connection: " + str(isConnected)) isAuthorized = client.is_user_authorized() print("Authorized: " + str(isAuthorized)) if not isAuthorized: phone_number = input( "Enter your phone number\nIn international format please\n") print("Phone is " + str(phone_number)) client.send_code_request(phone_number) authorized_code = input("Please enter code:\n") me = client.sign_in(phone_number, authorized_code) TelegramContact = BlueLoad("TelegramContact", "DATA/DATA") client.send_message(TelegramContact, "Server gestarted") Telegram = True
def send_sms(): try: api = open("API.txt","r") api_id = api.read() api.close() hash = open("hash.txt","r") api_hash = hash.read() hash.close() tel = open("tel.txt","r") phone = tel.read() tel.close() client = TelegramClient(phone, api_id, api_hash) except KeyError: os.system('clear') main.banner() sys.exit(1) client = TelegramClient(phone, api_id, api_hash) client.connect() if not client.is_user_authorized(): client.send_code_request(phone) os.system('clear') main.banner() client.sign_in(phone, input('[+] введите код: ')) os.system('clear') main.banner() input_file = "members.csv" users = [] with open(input_file, encoding='UTF-8') as f: rows = csv.reader(f,delimiter=",",lineterminator="\n") next(rows, None) for row in rows: user = {} user['username'] = row[0] user['id'] = int(row[1]) user['access_hash'] = int(row[2]) user['name'] = row[3] users.append(user) print("[1] отправить смс по идентификатору ID\n[2] отправить смс username ") mode = int(input("Выбор : ")) reklama = open("reklama.txt", "r") message = reklama.read() reklama.close() for user in users: if mode == 2: if user['username'] == "": continue receiver = client.get_input_entity(user['username']) elif mode == 1: receiver = InputPeerUser(user['id'],user['access_hash']) else: print("[!] Неверный режим. Выход.") client.disconnect() sys.exit() try: print("[+] Отправка сообщения на:", user['name']) client.send_message(receiver, message.format(user['name'])) print("[+] Ожидание {} секунд".format(SLEEP_TIME)) time.sleep(SLEEP_TIME) except PeerFloodError: print("[!] Получение сообщения об ошибке из телеграммы. \n[!] Скрипт останавливается сейчас. \n[!] Пожалуйста, попробуйте еще раз через некоторое время.") client.disconnect() sys.exit() except Exception as e: print("[!] ошибка:", e) print("[!] Пытаясь продолжить...") continue client.disconnect() print("Выполнено. Сообщение отправлено всем пользователям.")
def upload(paths, s): """Upload sticker sets to Telegram. \b Paths can be: 1. directories with a .ssd (sticker set definitions) file, or 2. .ssd files themselves """ import logging from telethon import TelegramClient from telethon.errors import RPCError from pytgasu.upload import CustomisedSession, SetDefParse, SetUploader # region Telegram init # TODO: strip Telethon to avoid too much implicit import # Probably have to let the 'update' thread stay even we don't need it # as ping-pongs prevent server from disconnecting us, # but what's the point as we are constantly talking while running this function? tc = TelegramClient(session=CustomisedSession.try_load_or_create_new(), api_id=TG_API_ID, api_hash=TG_API_HASH) logging.getLogger('TelethonLogger').setLevel( logging.ERROR) # suppress logging from telethon # Stolen from telethon.InteractiveTelegramClient :P tc.connect() if not tc.is_user_authorized(): print(PROMPT_ON_FIRST_LAUNCH) user_phone = input(PROMPT_PHONE_NUMBER) tc.send_code_request(user_phone) code_ok = False while not code_ok: code = input(PROMPT_LOGIN_CODE) try: code_ok = tc.sign_in(user_phone, code) # Two-step verification may be enabled except RPCError as e: from getpass import getpass if e.password_required: pw = getpass(PROMPT_2FA_PASSWORD) code_ok = tc.sign_in(password=pw) else: raise e # endregion # region Set list init sticker_sets = list() for setpath in paths: print(NOTICE_PREPARING % setpath) path = Path(setpath).resolve() set_def_tuple = () if path.is_dir(): for d in path.glob('*.ssd'): set_def_tuple = SetDefParse(d) # only process one break elif path.suffix == '.ssd': set_def_tuple = SetDefParse(path) if set_def_tuple: sticker_sets.append(set_def_tuple) # endregion SetUploader(tc=tc, sets=sticker_sets, subscribe=s) tc.disconnect()
def main(): # Get ENV variables from the '.env' file load_dotenv() api_id = os.getenv('API_ID') api_hash = os.getenv('API_HASH') phone = os.getenv('PHONE') fileName = input("Enter the File Name: ") fileName = fileName + '.csv' client = TelegramClient(phone, api_id, api_hash) client.connect() if not client.is_user_authorized(): client.send_code_request(phone) client.sign_in(phone, input('Enter the OTP: ')) groups_list = [] group = {} # Get's a List of Dictionaries with Group name with Group ID for d in client.get_dialogs(): try: if d.is_group and not d.is_channel and d.name != '': group = {"id": d.entity.id, "title": d.entity.title} groups_list.append(group) except: continue print('Choose a group to scrape members from:') i = 0 for g in groups_list: print(str(i) + '- ' + g['title']) i += 1 g_index = input("Enter a Number: ") target_group = groups_list[int(g_index)] print('Fetching Members...') all_participants = [] all_participants = client.get_participants(target_group["title"]) print('Saving In file...') with open(fileName, mode="w", encoding='UTF-8') as f: writer = csv.writer(f, delimiter=",", lineterminator="\n") writer.writerow(['username', 'phone', 'group', 'user_id', 'group_id']) for user in all_participants: if user.username: username = user.username else: username = "" if user.phone: phone = user.phone else: phone = "" if user.id: user_id = user.id else: user_id = "" if target_group["title"]: group = target_group["title"] else: group = "" if target_group["id"]: group_id = target_group["id"] else: group_id = "" writer.writerow([username, phone, group, user_id, group_id]) print('Members scraped successfully.')