def __init__(self): super(EchoLayer, self).__init__() YowInterfaceLayer.__init__(self) self.connected = False self.serve = Serve() self.bus_service = ServiceBusService( service_namespace='msgtestsb', shared_access_key_name='RootManageSharedAccessKey', shared_access_key_value= 'Ar9fUCZQdTL7cVWgerdNOB7sbQp0cWEeQyTRYUjKwpk=')
def __init__(self): super(EchoLayer, self).__init__() YowInterfaceLayer.__init__(self) self.connected = False self.serve = Serve() self.bus_service = ServiceBusService( service_namespace='msgtestsb', shared_access_key_name='RootManageSharedAccessKey', shared_access_key_value='Ar9fUCZQdTL7cVWgerdNOB7sbQp0cWEeQyTRYUjKwpk=')
def main(mode: str, log_level: str, log_dir: str): log_dir = log_dir or os.getcwd() if mode is None: log_name = f"Debugger_Main({os.getpid()})" log_name = f"{log_dir}\\{log_name}" if platform.system( ) == "Windows" else f"{log_dir}/{log_name}" loggers.set_filename(log_name) if log_level == "info": loggers.set_use_console(False) loggers.set_use_file(True) loggers.set_level(loggers.INFO) elif log_level == "debug": loggers.set_use_console(True) loggers.set_use_file(True) loggers.set_level(loggers.DEBUG) else: loggers.set_use_console(False) loggers.set_use_file(True) loggers.set_level(loggers.ERROR) Serve(IP, PORT, log_name, log_level, log_dir).start() elif mode == "debug": loggers.set_use_console(False) loggers.set_use_file(True) log_name = f"Debugger_Sub({os.getpid()})" log_name = f"{log_dir}\\{log_name}" if platform.system( ) == "Windows" else f"{log_dir}/{log_name}" loggers.set_filename(log_name) if log_level == "info": loggers.set_level(loggers.INFO) elif log_level == "debug": loggers.set_level(loggers.DEBUG) else: loggers.set_level(loggers.ERROR) print(f"pid {os.getpid()}") debug(log_level, log_dir) else: raise Exception("Invaild params.")
First, a few handler functions are defined. Then, those functions are passed to the Dispatcher and registered at their respective places. Then, the bot is started and runs until we press Ctrl-C on the command line. Usage: Basic Echobot example, repeats messages. Press Ctrl-C on the command line or send a signal to the process to stop the bot. """ from telegram import Updater import logging import json, sys from serve import Serve, TESTSCRIPT serve = Serve() BOTKEY = "" if not BOTKEY: try: BOTKEY = sys.argv[1] except: print "BOTKEY not provided" sys.exit() # Enable logging logging.basicConfig(filename="/tmp/" + TESTSCRIPT + "telegram.log", format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) logger = logging.getLogger(__name__)
class EchoLayer(YowInterfaceLayer): def __init__(self): super(EchoLayer, self).__init__() YowInterfaceLayer.__init__(self) self.connected = False self.serve = Serve() self.bus_service = ServiceBusService( service_namespace='msgtestsb', shared_access_key_name='RootManageSharedAccessKey', shared_access_key_value='Ar9fUCZQdTL7cVWgerdNOB7sbQp0cWEeQyTRYUjKwpk=') @ProtocolEntityCallback("message") def onMessage(self, recdMsg): jsondict = {'medium': 'whatsapp'} jsondict['phonenum'] = recdMsg.getFrom(False) jsondict['msgtype'] = recdMsg.getType() if jsondict['msgtype'] == 'text': jsondict['msgbody'] = recdMsg.getBody() if jsondict['msgtype'] == 'media': jsondict['mediatype'] = recdMsg.getMediaType() if jsondict['mediatype'] in ["image", "audio", "video"]: jsondict['mediaurl'] = recdMsg.getMediaUrl() if jsondict['mediatype'] in ["image", "video"]: jsondict['caption'] = recdMsg.getCaption() else: jsondict['caption'] = None elif jsondict['mediatype'] == 'vcard': jsondict['name'] = recdMsg.getName() jsondict['carddata'] = recdMsg.getCardData() elif jsondict['mediatype'] == "location": jsondict['lat'] = recdMsg.getLatitude() jsondict['long'] = recdMsg.getLongitude() jsondict['name'] = recdMsg.getLocationName() jsondict['url'] = recdMsg.getLocationURL() jsondict['encoding'] = "raw" if jsondict['msgtype'] == 'text': logging.info( recdMsg.getBody()) pushjson = json.dumps(jsondict) if AZURE_SERVICING: msg = Message(pushjson) self.bus_service.send_queue_message('process_incoming', msg) else: retjson = self.serve.getResponseWrapper(pushjson, recdMsg) if retjson: SendQueue.put(retjson) self.toLower(recdMsg.ack()) self.toLower(recdMsg.ack(True)) self.sendMessages() def sendMessages(self): try: sendmsg = SendQueue.get_nowait() except: return jsondict = json.loads(sendmsg) phonenum = jsondict['phonenum'] if jsondict['restype'] == 'list': ret = jsondict['response'] else: ret = [(jsondict['restype'], jsondict['response'])] for (restype,response) in ret: logging.info( '%s: Send to %s %s ' % (datetime.now(), phonenum, restype)) if restype in [ 'image' , 'audio', 'video' ]: if 'localfile' in response.keys(): path = response['localfile'] else: mediaurl = response['mediaurl'] path = '/tmp/' + basename(mediaurl) if isfile(path): unlink(path) urlretrieve(mediaurl, path) if isfile(path): if restype == 'image': self.image_send(phonenum, path, response['caption']) if restype == 'video': # self.video_send(phonenum, path, response['caption']) # video not supported yet self.message_send(phonenum, "Video Message not supported yet") if restype == 'audio': # self.audio_send(phonenum, path) # video not supported yet self.message_send(phonenum, "Audio Message not supported yet") elif restype == 'text': self.message_send(phonenum, response) elif restype == 'vcard': self.vcard_send(phonenum, response['name'],response['carddata']) elif restype == 'location': self.location_send(phonenum, response['lat'],response['long'], response['name'], response['url'], response['encoding']) # handling completed queue in azure service not yet implemented #CompletedSendQueue.append(key[1]) @ProtocolEntityCallback("receipt") def onReceipt(self, entity): self.toLower(entity.ack()) self.sendMessages() def logResponse(self, msg): if msg.getType() == 'text': logging.info(("Echoing %s to %s" % (msg.getBody(), msg.getFrom(False)))) elif msg.getType() == 'media': if msg.getMediaType() in [ "image", "audio", "video"]: logging.info(("Echoing %s %s to %s" % (msg.getMediaType(), msg.url, msg.getFrom(False)))) elif msg.getMediaType() == "location": logging.info(("Echoing location (%s, %s) to %s" % (msg.getLatitude(), msg.getLongitude(), msg.getFrom(False)))) elif msg.getMediaType() == "vcard": logging.info(("Echoing vcard (%s, %s) to %s" % (msg.getName(), msg.getCardData(), msg.getFrom(False)))) @ProtocolEntityCallback("success") def onSuccess(self, entity): self.connected = True logger.info("Logged in! Auth") self.sendMessages() @ProtocolEntityCallback("failure") def onFailure(self, entity): self.connected = False logger.info("Login Failed, reason: %s" % entity.getReason()) def message_send(self, number, content): outgoingMessage = TextMessageProtocolEntity(content.encode("utf-8") if version_info >= (3,0) else content, to = self.normalizeJid(number)) self.toLower(outgoingMessage) def vcard_send(self, number, name, carddata): outgoingMessage = VCardMediaMessageProtocolEntity( name, carddata, to = self.normalizeJid(number)) self.toLower(outgoingMessage) def location_send(self, number, lat, lon, name, url, encoding): outgoingMessage = LocationMediaMessageProtocolEntity( lat, lon, name, url, encoding, to = self.normalizeJid(number)) self.toLower(outgoingMessage) def image_send(self, number, path, caption = None): jid = self.normalizeJid(number) entity = RequestUploadIqProtocolEntity(RequestUploadIqProtocolEntity.MEDIA_TYPE_IMAGE, filePath=path) successFn = lambda successEntity, originalEntity: self.onRequestUploadResult(jid, path, successEntity, originalEntity, caption) errorFn = lambda errorEntity, originalEntity: self.onRequestUploadError(jid, path, errorEntity, originalEntity) self._sendIq(entity, successFn, errorFn) def video_send(self, number, path, caption = None): jid = self.normalizeJid(number) entity = RequestUploadIqProtocolEntity(RequestUploadIqProtocolEntity.MEDIA_TYPE_VIDEO, filePath=path) successFn = lambda successEntity, originalEntity: self.onRequestUploadResult(jid, path, successEntity, originalEntity, caption) errorFn = lambda errorEntity, originalEntity: self.onRequestUploadError(jid, path, errorEntity, originalEntity) self._sendIq(entity, successFn, errorFn) def audio_send(self, number, path): jid = self.normalizeJid(number) entity = RequestUploadIqProtocolEntity(RequestUploadIqProtocolEntity.MEDIA_TYPE_AUDIO, filePath=path) successFn = lambda successEntity, originalEntity: self.onRequestUploadResult(jid, path, successEntity, originalEntity) errorFn = lambda errorEntity, originalEntity: self.onRequestUploadError(jid, path, errorEntity, originalEntity) self._sendIq(entity, successFn, errorFn) def normalizeJid(self, number): if '@' in number: return number elif "-" in number: return "*****@*****.**" % number return "*****@*****.**" % number ########### callbacks ############ def onRequestUploadResult(self, jid, filePath, resultRequestUploadIqProtocolEntity, requestUploadIqProtocolEntity, caption = None): if requestUploadIqProtocolEntity.mediaType == RequestUploadIqProtocolEntity.MEDIA_TYPE_AUDIO: doSendFn = self.doSendAudio elif requestUploadIqProtocolEntity.mediaType == RequestUploadIqProtocolEntity.MEDIA_TYPE_IMAGE: doSendFn = self.doSendImage else: doSendFn = self.doSendVideo if resultRequestUploadIqProtocolEntity.isDuplicate(): doSendFn(filePath, resultRequestUploadIqProtocolEntity.getUrl(), jid, resultRequestUploadIqProtocolEntity.getIp(), caption) else: successFn = lambda filePath, jid, url: doSendFn(filePath, url, jid, resultRequestUploadIqProtocolEntity.getIp(), caption) mediaUploader = MediaUploader(jid, self.getOwnJid(), filePath, resultRequestUploadIqProtocolEntity.getUrl(), resultRequestUploadIqProtocolEntity.getResumeOffset(), successFn, self.onUploadError, self.onUploadProgress, async=False) mediaUploader.start() def onRequestUploadError(self, jid, path, errorRequestUploadIqProtocolEntity, requestUploadIqProtocolEntity): logger.error("Request upload for file %s for %s failed" % (path, jid)) def onUploadError(self, filePath, jid, url): logger.error("Upload file %s to %s for %s failed!" % (filePath, url, jid)) def onUploadProgress(self, filePath, jid, url, progress): return #sys.stdout.write("%s => %s, %d%% \r" % (os.path.basename(filePath), jid, progress)) #sys.stdout.flush() def doSendVideo(self, filePath, url, to, ip = None, caption = None): entity = VideoDownloadableMediaMessageProtocolEntity.fromFilePath(filePath, url, ip, to, caption = caption) self.toLower(entity) def doSendImage(self, filePath, url, to, ip = "127.0.0.1", caption = None): logger.info('filepath:%s url:%s to:%s ip:%s caption:%s ' % (filePath, url, to, ip, caption)) entity = ImageDownloadableMediaMessageProtocolEntity.fromFilePath(filePath, url, ip, to, caption = caption) self.toLower(entity) def doSendAudio(self, filePath, url, to, ip = None, caption = None): entity = AudioDownloadableMediaMessageProtocolEntity.fromFilePath(filePath, url, ip, to) self.toLower(entity) def getMediaMessageBody(self, message): if message.getMediaType() in ("image", "audio", "video"): return self.getDownloadableMediaMessageBody(message) else: return "[Media Type: %s]" % message.getMediaType() def getDownloadableMediaMessageBody(self, message): return "[Media Type:{media_type}, Size:{media_size}, URL:{media_url}]".format( media_type = message.getMediaType(), media_size = message.getMediaSize(), media_url = message.getMediaUrl() )
class EchoLayer(YowInterfaceLayer): def __init__(self): super(EchoLayer, self).__init__() YowInterfaceLayer.__init__(self) self.connected = False self.serve = Serve() self.bus_service = ServiceBusService( service_namespace='msgtestsb', shared_access_key_name='RootManageSharedAccessKey', shared_access_key_value= 'Ar9fUCZQdTL7cVWgerdNOB7sbQp0cWEeQyTRYUjKwpk=') @ProtocolEntityCallback("message") def onMessage(self, recdMsg): jsondict = {'medium': 'whatsapp'} jsondict['phonenum'] = recdMsg.getFrom(False) jsondict['msgtype'] = recdMsg.getType() if jsondict['msgtype'] == 'text': jsondict['msgbody'] = recdMsg.getBody() if jsondict['msgtype'] == 'media': jsondict['mediatype'] = recdMsg.getMediaType() if jsondict['mediatype'] in ["image", "audio", "video"]: jsondict['mediaurl'] = recdMsg.getMediaUrl() if jsondict['mediatype'] in ["image", "video"]: jsondict['caption'] = recdMsg.getCaption() else: jsondict['caption'] = None elif jsondict['mediatype'] == 'vcard': jsondict['name'] = recdMsg.getName() jsondict['carddata'] = recdMsg.getCardData() elif jsondict['mediatype'] == "location": jsondict['lat'] = recdMsg.getLatitude() jsondict['long'] = recdMsg.getLongitude() jsondict['name'] = recdMsg.getLocationName() jsondict['url'] = recdMsg.getLocationURL() jsondict['encoding'] = "raw" if jsondict['msgtype'] == 'text': logging.info(recdMsg.getBody()) pushjson = json.dumps(jsondict) if AZURE_SERVICING: msg = Message(pushjson) self.bus_service.send_queue_message('process_incoming', msg) else: retjson = self.serve.getResponseWrapper(pushjson, recdMsg) if retjson: SendQueue.put(retjson) self.toLower(recdMsg.ack()) self.toLower(recdMsg.ack(True)) self.sendMessages() def sendMessages(self): try: sendmsg = SendQueue.get_nowait() except: return jsondict = json.loads(sendmsg) phonenum = jsondict['phonenum'] if jsondict['restype'] == 'list': ret = jsondict['response'] else: ret = [(jsondict['restype'], jsondict['response'])] for (restype, response) in ret: logging.info('%s: Send to %s %s ' % (datetime.now(), phonenum, restype)) if restype in ['image', 'audio', 'video']: if 'localfile' in response.keys(): path = response['localfile'] else: mediaurl = response['mediaurl'] path = '/tmp/' + basename(mediaurl) if isfile(path): unlink(path) urlretrieve(mediaurl, path) if isfile(path): if restype == 'image': self.image_send(phonenum, path, response['caption']) if restype == 'video': # self.video_send(phonenum, path, response['caption']) # video not supported yet self.message_send(phonenum, "Video Message not supported yet") if restype == 'audio': # self.audio_send(phonenum, path) # video not supported yet self.message_send(phonenum, "Audio Message not supported yet") elif restype == 'text': self.message_send(phonenum, response) elif restype == 'vcard': self.vcard_send(phonenum, response['name'], response['carddata']) elif restype == 'location': self.location_send(phonenum, response['lat'], response['long'], response['name'], response['url'], response['encoding']) # handling completed queue in azure service not yet implemented #CompletedSendQueue.append(key[1]) @ProtocolEntityCallback("receipt") def onReceipt(self, entity): self.toLower(entity.ack()) self.sendMessages() def logResponse(self, msg): if msg.getType() == 'text': logging.info( ("Echoing %s to %s" % (msg.getBody(), msg.getFrom(False)))) elif msg.getType() == 'media': if msg.getMediaType() in ["image", "audio", "video"]: logging.info( ("Echoing %s %s to %s" % (msg.getMediaType(), msg.url, msg.getFrom(False)))) elif msg.getMediaType() == "location": logging.info(("Echoing location (%s, %s) to %s" % (msg.getLatitude(), msg.getLongitude(), msg.getFrom(False)))) elif msg.getMediaType() == "vcard": logging.info( ("Echoing vcard (%s, %s) to %s" % (msg.getName(), msg.getCardData(), msg.getFrom(False)))) @ProtocolEntityCallback("success") def onSuccess(self, entity): self.connected = True logger.info("Logged in! Auth") self.sendMessages() @ProtocolEntityCallback("failure") def onFailure(self, entity): self.connected = False logger.info("Login Failed, reason: %s" % entity.getReason()) def message_send(self, number, content): outgoingMessage = TextMessageProtocolEntity( content.encode("utf-8") if version_info >= (3, 0) else content, to=self.normalizeJid(number)) self.toLower(outgoingMessage) def vcard_send(self, number, name, carddata): outgoingMessage = VCardMediaMessageProtocolEntity( name, carddata, to=self.normalizeJid(number)) self.toLower(outgoingMessage) def location_send(self, number, lat, lon, name, url, encoding): outgoingMessage = LocationMediaMessageProtocolEntity( lat, lon, name, url, encoding, to=self.normalizeJid(number)) self.toLower(outgoingMessage) def image_send(self, number, path, caption=None): jid = self.normalizeJid(number) entity = RequestUploadIqProtocolEntity( RequestUploadIqProtocolEntity.MEDIA_TYPE_IMAGE, filePath=path) successFn = lambda successEntity, originalEntity: self.onRequestUploadResult( jid, path, successEntity, originalEntity, caption) errorFn = lambda errorEntity, originalEntity: self.onRequestUploadError( jid, path, errorEntity, originalEntity) self._sendIq(entity, successFn, errorFn) def video_send(self, number, path, caption=None): jid = self.normalizeJid(number) entity = RequestUploadIqProtocolEntity( RequestUploadIqProtocolEntity.MEDIA_TYPE_VIDEO, filePath=path) successFn = lambda successEntity, originalEntity: self.onRequestUploadResult( jid, path, successEntity, originalEntity, caption) errorFn = lambda errorEntity, originalEntity: self.onRequestUploadError( jid, path, errorEntity, originalEntity) self._sendIq(entity, successFn, errorFn) def audio_send(self, number, path): jid = self.normalizeJid(number) entity = RequestUploadIqProtocolEntity( RequestUploadIqProtocolEntity.MEDIA_TYPE_AUDIO, filePath=path) successFn = lambda successEntity, originalEntity: self.onRequestUploadResult( jid, path, successEntity, originalEntity) errorFn = lambda errorEntity, originalEntity: self.onRequestUploadError( jid, path, errorEntity, originalEntity) self._sendIq(entity, successFn, errorFn) def normalizeJid(self, number): if '@' in number: return number elif "-" in number: return "*****@*****.**" % number return "*****@*****.**" % number ########### callbacks ############ def onRequestUploadResult(self, jid, filePath, resultRequestUploadIqProtocolEntity, requestUploadIqProtocolEntity, caption=None): if requestUploadIqProtocolEntity.mediaType == RequestUploadIqProtocolEntity.MEDIA_TYPE_AUDIO: doSendFn = self.doSendAudio elif requestUploadIqProtocolEntity.mediaType == RequestUploadIqProtocolEntity.MEDIA_TYPE_IMAGE: doSendFn = self.doSendImage else: doSendFn = self.doSendVideo if resultRequestUploadIqProtocolEntity.isDuplicate(): doSendFn(filePath, resultRequestUploadIqProtocolEntity.getUrl(), jid, resultRequestUploadIqProtocolEntity.getIp(), caption) else: successFn = lambda filePath, jid, url: doSendFn( filePath, url, jid, resultRequestUploadIqProtocolEntity.getIp( ), caption) mediaUploader = MediaUploader( jid, self.getOwnJid(), filePath, resultRequestUploadIqProtocolEntity.getUrl(), resultRequestUploadIqProtocolEntity.getResumeOffset(), successFn, self.onUploadError, self.onUploadProgress, async=False) mediaUploader.start() def onRequestUploadError(self, jid, path, errorRequestUploadIqProtocolEntity, requestUploadIqProtocolEntity): logger.error("Request upload for file %s for %s failed" % (path, jid)) def onUploadError(self, filePath, jid, url): logger.error("Upload file %s to %s for %s failed!" % (filePath, url, jid)) def onUploadProgress(self, filePath, jid, url, progress): return #sys.stdout.write("%s => %s, %d%% \r" % (os.path.basename(filePath), jid, progress)) #sys.stdout.flush() def doSendVideo(self, filePath, url, to, ip=None, caption=None): entity = VideoDownloadableMediaMessageProtocolEntity.fromFilePath( filePath, url, ip, to, caption=caption) self.toLower(entity) def doSendImage(self, filePath, url, to, ip="127.0.0.1", caption=None): logger.info('filepath:%s url:%s to:%s ip:%s caption:%s ' % (filePath, url, to, ip, caption)) entity = ImageDownloadableMediaMessageProtocolEntity.fromFilePath( filePath, url, ip, to, caption=caption) self.toLower(entity) def doSendAudio(self, filePath, url, to, ip=None, caption=None): entity = AudioDownloadableMediaMessageProtocolEntity.fromFilePath( filePath, url, ip, to) self.toLower(entity) def getMediaMessageBody(self, message): if message.getMediaType() in ("image", "audio", "video"): return self.getDownloadableMediaMessageBody(message) else: return "[Media Type: %s]" % message.getMediaType() def getDownloadableMediaMessageBody(self, message): return "[Media Type:{media_type}, Size:{media_size}, URL:{media_url}]".format( media_type=message.getMediaType(), media_size=message.getMediaSize(), media_url=message.getMediaUrl())