def main(): session_name = environ.get('TG_SESSION', 'session') user_phone = environ['TG_PHONE'] client = TelegramClient(session_name, int(environ['TG_API_ID']), environ['TG_API_HASH'], proxy=None, update_workers=4) print('INFO: Connecting to Telegram Servers...', end='', flush=True) client.connect() print('Done!') if not client.is_user_authorized(): print('INFO: Unauthorized user') client.send_code_request(user_phone) code_ok = False while not code_ok: code = input('Enter the auth code: ') try: code_ok = client.sign_in(user_phone, code) except SessionPasswordNeededError: password = getpass( 'Two step verification enabled. Please enter your password: '******'INFO: Client initialized succesfully!') client.add_update_handler(update_handler) input('Press Enter to stop this!\n')
class TelegramDriver: def __init__(self, config, bot_dialog_config): self.config = config self.bot_dialog_config = bot_dialog_config self.client = None self.logger = logging.getLogger() self.updater_telegram_channel = Updater( self.config["crypto-bot"]["token"]) def log_started(self): self.send_to_channel(self.config["crypto-bot"]["channel_id"], self.bot_dialog_config["Start"]) self.send_to_channel(self.config["crypto-bot"]["channel_id"], self.bot_dialog_config["Ready"]) def first_connection(self): self.client.send_code_request( self.config["telegram-api"]["phone_number"]) myself = self.client.sign_in( self.config["telegram-api"]["phone_number"], input('Enter code: ')) self.logger.info(myself.stringify()) def connect(self): self.client = TelegramClient("User", self.config["telegram-api"]["api_id"], self.config["telegram-api"]["api_hash"], update_workers=1, spawn_read_thread=False) self.client.connect() if self.client.is_connected(): if not self.client.is_user_authorized(): self.first_connection() self.logger.info("Client connected to Telegram.") else: self.logger.error("Client not connected") def send_to_channel(self, channel_id, msg): self.updater_telegram_channel.bot.send_message(chat_id=channel_id, text=msg) def add_handler_update(self, callback): self.client.add_update_handler(callback) def call_idle(self): self.client.idle() self.send_to_channel(self.config["crypto-bot"]["channel_id"], self.bot_dialog_config["Stop"]) def disconnect(self): self.client.disconnect()
def main(): session_name = environ.get('TG_SESSION', 'session') client = TelegramClient(session_name, int(environ['TG_API_ID']), environ['TG_API_HASH'], proxy=None, update_workers=4, spawn_read_thread=False) if 'TG_PHONE' in environ: client.start(phone=environ['TG_PHONE']) else: client.start() client.add_update_handler(update_handler) print('(Press Ctrl+C to stop this)') client.idle()
def main(): client = TelegramClient(config.session_name, config.api_id, config.api_hash, update_workers=1) client.connect() if not client.is_user_authorized(): client.send_code_request(config.phone) client.sign_in(phone=config.phone, code=input("Enter code: ")) client.add_update_handler(handle_update) while True: command = input(">> ") if command == "exit": break else: result = re.match(r"^join\s+@?(\w+)", command) if result: username = result.group(1) add_channel(client, username) client.disconnect()
global variable variable=str(variable) variablestr=str(variable) print('Starting Trade of: ' + variablestr) process0='./zenbot.sh trade poloniex.' + variablestr subprocess.Popen(process0,shell=True) time.sleep(3600) print('Starting node kill process) process1='sudo killall node' subprocess.Popen(process1,shell=True) print('Starting final sell Of:' + variablestr + ' In Case of Error') process2='./zenbot.sh sell --order_adjust_time=1000000000 --sell_pct=100 --markup_pct=0 poloniex.' + variablestr proc2 = subprocess.Popen(process2,shell=True) proc2.communicate() print('Starting final sell Of:' + variablestr + ' In Case of Error') process3='./zenbot.sh sell --order_adjust_time=1000000000 --sell_pct=100 --markup_pct=0 poloniex.' + variablestr proc3 = subprocess.Popen(process3,shell=True) proc3.communicate() os.remove(pid) print('Done running loop, process file deleted. Waiting for another coin...') # From now on, any update received will be passed to 'update_handler' NOTE... Later, Zenbot will be modified to cancel on order adjust. while True: client.add_update_handler(update_handler) input('Press <ENTER> to exit...') client.disconnect()
with open(path, 'r', encoding='utf-8') as file: for line in file: value_pair = line.split('=') left = value_pair[0].strip() right = value_pair[1].strip() if right.isnumeric(): result[left] = int(right) else: result[left] = right return result settings = load_settings() session_name = "botbotbot" client = TelegramClient(session_name, int(settings['api_id']), settings['api_hash'], proxy=None, update_workers=4, spawn_read_thread=False) if True: client.start(phone='+ENTERYOURPHONENUMBERFORTELEGRAMHERE') else: client.start() client.add_update_handler(dat) print('(Press Ctrl+C to stop this)') client.idle()
class TelethonChecker(object): """ Use Telethon to check all the messages in the account and pick the correct message """ def __init__(self,config): """ Init the telethon client. """ self.client = TelegramClient("session_name", int(config["api_id"]), config["api_hash"], proxy=None, update_workers=config["worker"]) print('INFO: Connecting to Telegram Servers...', end='', flush=True) self.client.connect() print('Done!') self.read_userlist() if not self.client.is_user_authorized(): print('INFO: Unauthorized user') self.client.send_code_request(config["phone"]) code_ok = False while not code_ok: code = input('Enter the auth code: ') try: code_ok = self.client.sign_in(config["phone"], code) except SessionPasswordNeededError: return print('INFO: Client initialized succesfully!') @classmethod def get_instance(cls): """ Class Object generator, used to make sure only one Telegram helper object is generated :param bot_token: The token of the bot :param offset: The offset of the update :return: The TelegramHelper object """ try: if cls.instance: return cls.instance else: raise Exception("No instance") except Exception as e: def yaml_reader(config): with open(config) as f: return yaml.load(f) config = yaml_reader("config.yaml") cls.instance=cls(config=config) return cls.instance def set_update_handler(self,func): self.client.add_update_handler(func) def read_userlist(self): try: with open("users.txt",'r+') as file: try: self.user_list=json.loads(file.read()) print(self.user_list) except: file.write(json.dumps([])) except: with open("users.txt", "w+") as file: file.write(json.dumps([])) def update_userlist(self): with open("users.txt","w+") as file: file.write(json.dumps(self.user_list)) def add_userlist(self,user_id): self.user_list.append(user_id) self.update_userlist()
entity, tty.ChannelParticipantsAdmins(), 0, 1)) assert(admins.users[0].is_self) entity_creator = client.get_input_entity(admins.users[1]) except: return else: channel.add(entity.channel_id, entity_creator.user_id) client.send_message(entity_creator, '绑定成功!你可以将机器人从管理员中移除了') with open('config.json', 'r', encoding='UTF-8') as f: configs = json.load(f) client = TelegramClient(configs['telegram']['some_name'], configs['telegram']['api_id'], configs['telegram']['api_hash'], update_workers=10) if not client.connect(): print('连接服务器失败') exit() if not client.is_user_authorized(): client.send_code_request(configs['telegram']['phone_number']) code = input('输入 code: ') client.sign_in(configs['telegram']['phone_number'], code) client.add_update_handler(callback) command = '' while command != '/stop': command = input('command: ')
def main(): api_id = 105158 api_hash = '9eeea2ab5df259875d174dbddce9223d' phone = '+541150184194' client = TelegramClient('session_name', api_id, api_hash, proxy=None, update_workers=4) print('INFO: Connecting to Telegram Servers...', end='', flush=True) client.connect() print('Done!') if not client.is_user_authorized(): print('INFO: Unauthorized user') client.send_code_request(phone) code_ok = False while not code_ok: code = input('Enter the auth code: ') try: code_ok = client.sign_in(phone, code) except SessionPasswordNeededError: password = getpass( 'Two step verification enabled. Please enter your password: '******'INFO: Client initialized succesfully!') CHANNEL_FROM = client.get_entity("https://t.me/TrdAR") # CHANNEL_FROM = client.get_entity("https://t.me/Cryptotguide") CHANNEL_TO = client.get_entity( "telegram.me/joinchat/AAAAAEGV4HnGlRNMhIBnBw") peers_from = [ client.get_input_entity( "https://t.me/joinchat/AAAAAEqa813uKBVUOvVMhw"), client.get_input_entity( "https://t.me/joinchat/AAAAAEGV4HnGlRNMhIBnBw"), client.get_input_entity("https://t.me/edwardmorra_btc"), client.get_input_entity("https://t.me/Cryptotguide"), client.get_input_entity("https://t.me/Mrcryptoindia"), client.get_input_entity("https://t.me/coindetector"), # client.get_input_entity("https://t.me/cryptobullet"), client.get_input_entity("https://t.me/Securetradingsignals") ] print(str(peers_from)) def update_handler(update): print(type(update)) print(update) print("------------------") if isinstance(update, UpdateNewChannelMessage): # message_from = client.get_entity(PeerChannel(update.message.to_id)) # print("From: "+str(update.message.to_id)) try: for peer_from in peers_from: if update.message.to_id.channel_id != peer_from.channel_id: continue if "http" in str(update.message.message) or "https" in str( update.message.message): continue peer_to = client.get_input_entity( PeerChannel(CHANNEL_TO.id)) print("Message comming from channel id: " + str(update.message.to_id.channel_id)) print("To: " + str(peer_from.channel_id)) print("From: " + str(peer_to.channel_id)) print("########\nMessage:") print(str(update.message.message)) print("########\nMessage id:") print(str(update.message.id)) print("########:") client( ForwardMessagesRequest( from_peer= peer_from, # who sent these messages or what channel sent in? id=[update.message.id], # which are the messages? to_peer= peer_to # who or what channel are we forwarding them to? )) except Exception as ex: print("Error: " + str(ex)) # client(ForwardMessagesRequest( # from_peer=CHANNEL_FROM, # who sent these messages or what channel sent in? # id=[msg.id for msg in update.messages], # which are the messages? # to_peer=CHANNEL_TO # who or what channel are we forwarding them to? # )) # print('Press Enter to stop this!') client.add_update_handler(update_handler) input('Press Enter to stop this!\n')
class TelegramWorker(QtCore.QObject): # SIGNALS (cannot be in constructor https://stackoverflow.com/questions/2970312/pyqt4-qtcore-pyqtsignal-object-has-no-attribute-connect) # sent when new message is available NEED mag self. voor deze dingen? newMessage = QtCore.pyqtSignal(str) # sent when telegram setup is complete (verified and partner set) setReady = QtCore.pyqtSignal() # sent when partner username is needed reqPartner = QtCore.pyqtSignal() # sent when verification is needed reqVerify = QtCore.pyqtSignal() # sent when initialisation is done loadingFinished = QtCore.pyqtSignal() # SETUP @QtCore.pyqtSlot(str) def setPhone(self,phone): self.phone = phone self.client.send_code_request(self.phone) @QtCore.pyqtSlot(str) def verify(self,code):# TODO check of code wel ok was, geeft deze functie feedback? self.client.sign_in(self.phone, code) # NEED check of code klopt self.client.add_update_handler(self.newMessageHandler) self.loadPartner() @QtCore.pyqtSlot(str) def setPartner(self,username): with open('partner','w') as f: f.write(username) self.partner = username self.setReady.emit() # NORMAL OPERATION def __init__(self): super(self.__class__, self).__init__() # is not part of constructor because in KatApp constructor it is necessary to first connect the signals after calling this constructor @QtCore.pyqtSlot() def initialise(self): # api credentials apiId = 134734 apiHash = '88e71c3b86c4958290a5609f73054236' self.client = TelegramClient('session', apiId, apiHash) # TODO aanpassen naar iets netjes, readen van file self.client.connect() # check if session file is valid if self.client.is_user_authorized(): self.client.add_update_handler(self.newMessageHandler) self.loadPartner() else: self.reqVerify.emit() self.loadingFinished.emit() def newMessageHandler(self,update): if isinstance(update, UpdateShortMessage): if not update.out: # TODO check update.user_id of dat het wel Baert is self.newMessage.emit(update.message) def loadPartner(self): # check if text file exists if os.path.isfile('partner'): with open('partner', 'r') as f: self.partner = f.read().rstrip() self.setReady.emit() else: self.reqPartner.emit() @QtCore.pyqtSlot(str) def sendMessage(self,message): self.client.send_message(self.partner, message)
class BotChecker(object): def __init__(self, session_name, api_id, api_hash, phone_number, updater=None): self.phone_number = phone_number self.client = TelegramClient(session_name, api_id, api_hash, update_workers=4, spawn_read_thread=True, timeout=datetime.timedelta(seconds=15)) self.client.connect() self._pinged_bots = [] self._responses = {} self.botbuilders = [] if not self.client.is_user_authorized(): log.info("Sending code request...") self.client.send_code_request(phone_number) if updater: updater.bot.send_message(settings.ADMINS[0], CONFIRM_PHONE_CODE, reply_markup=ForceReply()) updater.dispatcher.add_handler(MessageHandler( Filters.reply & Filters.user(settings.ADMINS[0]), lambda bot, update: authorization_handler( bot, update, self)), group=3) self.pending_authorization = True else: self.client.send_code_request(phone_number) self.client.sign_in(phone_number, input('Enter code: ')) else: self._initialize() def reset(self): self._pinged_bots = [] self._responses = {} def authorize(self, code): self.client.sign_in(self.phone_number, code) self._initialize() def _initialize(self): self.pending_authorization = False self.client.add_update_handler(self._update_handler) def _update_handler(self, update): if update is None: log.error("Received `None` update.") return try: uid = update.message.from_id except AttributeError: try: uid = update.user_id except AttributeError: return # try: # entity = self.client.get_entity(uid) # log.debug("Received response from @{}".format(entity.username)) # except: if uid in self._pinged_bots: log.debug("Received update from pinged bot {}: {}".format( uid, type(update))) message_text = None try: message_text = update.message.message except AttributeError: try: message_text = update.message except AttributeError: pass self._responses[uid] = message_text def _init_thread(self, target, *args, **kwargs): thr = Thread(target=target, args=args, kwargs=kwargs) thr.start() def schedule_conversation_deletion(self, peer, delay=5): def inner(): time.sleep(delay) entity = self.client.get_input_entity(peer) self.client(DeleteHistoryRequest(entity, max_id=999999999)) log.debug("Deleted conversation with {}".format(entity)) thr = threading.Thread(target=inner, args=()) thr.start() def delete_all_conversations(self): all_peers = [ utils.resolve_id(x[0]) for x in self.client.session.entities.get_input_list() ] for peer in all_peers: log.debug("Deleting conversation with {}...".format(peer)) try: input_entity = self.client.session.entities.get_input_entity( peer[0]) self.client( DeleteHistoryRequest(input_entity, max_id=9999999999999999)) except: log.error("Couldn't find {}".format(peer[0])) def get_bot_entity(self, username) -> User: entity = self.client.get_entity(username) if not hasattr(entity, 'bot'): raise NotABotError("This user is not a bot.") time.sleep(45) # ResolveUsernameRequests are expensive return entity def get_bot_entity_by_id(self, chat_id) -> User: entity = self.client.get_entity(chat_id) if not hasattr(entity, 'bot'): raise NotABotError("This user is not a bot.") return entity def _response_received(self, bot_user_id): return bot_user_id in [k for k in self._responses.keys()] def _delete_response(self, bot_user_id): del self._responses[bot_user_id] def ping_bot(self, entity, timeout=30): input_entity = utils.get_input_peer(entity) time.sleep(1) bot_user_id = input_entity.user_id self._pinged_bots.append(bot_user_id) log.debug('Pinging @{username}...'.format(username=entity.username)) self.client.send_message(input_entity, '/start') start = datetime.datetime.now() help_attempted = False while not self._response_received(bot_user_id): if datetime.datetime.now() - start > datetime.timedelta(seconds=5) and \ not help_attempted: # Try sending /help if /start didn't work self.client.send_message(input_entity, '/help') help_attempted = True if datetime.datetime.now() - start > datetime.timedelta( seconds=timeout): # No response self._pinged_bots.remove(bot_user_id) log.debug('@{} did not respond after {} seconds.'.format( entity.username, timeout)) return False time.sleep(0.3) response_text = self._responses[bot_user_id] self._delete_response(bot_user_id) self._pinged_bots.remove(bot_user_id) if isinstance(response_text, str): if 'Use /off to pause your subscription.' in response_text \ or 'Use /stop to unsubscribe.' in response_text: self.botbuilders.append(entity) # Evaluate WJClub's ParkMeBot flags reserved_username = ZERO_CHAR1 + ZERO_CHAR1 + ZERO_CHAR1 + ZERO_CHAR1 parked = ZERO_CHAR1 + ZERO_CHAR1 + ZERO_CHAR1 + ZERO_CHAR2 maintenance = ZERO_CHAR1 + ZERO_CHAR1 + ZERO_CHAR2 + ZERO_CHAR1 if zero_width_encoding(response_text) in (reserved_username, parked, maintenance): return False return True def get_bot_last_activity(self, entity): entity = self.get_bot_entity(entity) _, messages, _ = self.client.get_message_history(entity, limit=5) peer_messages = [m for m in messages if m.from_id == entity.id] if len(peer_messages) == 0: return None last_peer_message = peer_messages[-1] return last_peer_message.date def disconnect(self): self.client.disconnect()
client = TelegramClient(config.session_id, config.api_id, config.api_hash, update_workers=4) client.connect() if not client.is_user_authorized(): client.sign_in(config.phone) client.sign_in(code=input('Code:')) print len(client.get_dialogs()) def printupdate(update): print update if messagefilters.Filters.command(update) and isinstance( update, UpdateShortMessage): text = update.effective_message.message if text == '/start': print '/start command used' try: print functions.effective_chat_id(update) client.send_message( functions.effective_chat_id(update)[1], 'Hello, World! :)') except Exception, e: print e client.add_update_handler(printupdate) time.sleep(1000000)
# # Connect to Telegram # client = TelegramClient('session_name', configuration['api_id'], configuration['api_hash'], update_workers=2) if client.connect() != True: print( "Can't connect to Telegram. Maybe you abused API limit retries? Also check your connection!" ) exit(1) client.add_update_handler(receiveUpdate) # # Ensure you're authorized # if not client.is_user_authorized(): client.send_code_request(configuration['phone']) client.sign_in( configuration['phone'], input('Authorization required. Check Telegram and enter the code: ')) # # Search chat #
update ) == UpdateNewChannelMessage and update.message.to_id.channel_id == channel_manual.id: print('message id ' + str(update.message.id)) print('channel id ' + str(update.message.to_id.channel_id)) #print(update) #print(dir(update)) client.invoke( ForwardMessagesRequest(from_peer=channel_from_input_peer, id=[update.message.id], to_peer=channel_to_input_peer)) # print('UPDATE_MESSAGE') #print(client.invoke(GetMessagesRequest(channel=my_channel_to, id=[update.message.id]))) #client.invoke(ForwardMessagesRequest(from_peer=my_channel_from, id=[update.message.id], to_peer=my_channel_to)) else: continue #def forward(update): #if isinstance(update, UpdateShortMessage) and not update.out: #total_count, messages, senders = client.get_message_history(channel_from_input_peer.chats[0], limit=1) # print('UPDATE_MESSAGE') # print(update.message) # print('FULL_MESSAGE') # print(update) #client.invoke(ForwardMessagesRequest(from_peer=my_channel_from, id=[msg.id], to_peer=my_channel_to)) client.add_update_handler(forward) #input('Press enter to stop this!') #client.disconnect()