def runforever(): path_to_images = 'casosReportados/' path_to_cut_images = 'placasAreconocer/' files_exist = check_files_existence() if files_exist: # Files has veen moved to worddir? move_files_to_work_dir(files_exist) for fname in sorted(glob.glob(path_to_images + '*.jpg')): os.remove(fname) for fname_img in sorted(glob.glob(path_to_cut_images + '*.jpg')): os.remove(fname_img) for fname_img_png in sorted(glob.glob(path_to_cut_images + '*.png')): os.remove(fname_img_png) files_exist = False print('FINISHED TIME FOR ') time.sleep(5) print('end') return runforever() else: print('waiting for files in directories...') print('Checkpoint') time.sleep(5) try: send(name_to_workdir) except: print('Already Uploaded!.') return runforever()
def setting_saver(update, context, section): if context.args: context.user_data[section] = {} for id in context.args: count = '' if ',' in id: id, count = id.split(',') if id_lookup.get(id, {}).get('name', False): # Don't save if item doesn't exist context.user_data[section][id] = count settings = sorted(context.user_data.get(section, {})) if len(settings) > 0: res = [ f'{"Saving" if section == "save" else "Ignoring"} {"these" if len(settings) > 1 else "this"}:' ] else: res = [ f'Not {"saving" if section == "save" else "ignoring"} anything!' ] cmd = [f'/{section}'] for id in settings: name = id_lookup.get(id, {}).get('name', 'unknown') count = context.user_data[section][id] id_count = f'{id}{"," if count else ""}{count}' res.append(f' <code>{id_count}</code> {name}') cmd.append(id_count) if settings: res.append(f'<code>{" ".join(cmd)}</code>') text = '\n'.join(res) send(text, update, context)
def run(self): print 'connecting...' self.connect() print 'sending messages...' send(self.socket, self.message, 'request') res = receive(self.socket, 'response') print res
def command_handler(soc: socket.socket, msg: str): print("command (" + msg + ") is handled by a thread") cmd = msg.split()[0] args = msg.split()[1:] # optlist, args = getopt.getopt(args, 'h', ['help']) # print(optlist, args) # TODO if cmd == "help" or msg == '\0' or cmd == "-h" or cmd == "--help": # commands.main_help(soc) # TODO more intelligent Help(soc) elif cmd == "stop-server": set_interaction(soc, False) os.kill(os.getpid(), signal.SIGINT) elif cmd == "ps": Ps(soc, args) elif cmd == "run": Run(soc, args) elif cmd == "rm": Rm(soc, args) elif cmd == "stop": Stop(soc, args) elif cmd == "images": Images(soc, args) else: # pass set_interaction(soc, False) send(soc, "pass", newline=True) soc.close() client_sockets.remove(soc)
def incoming(update, context): """main function that deals with incoming messages that are the meat and potatos of this bot""" if not update.effective_message.text: return responses = main(update, context) for response in responses: send(response, update, context)
def location(update, context): tf = TimezoneFinder() latitude, longitude = update.effective_message.location.latitude, update.effective_message.location.longitude context.user_data['location'] = round(latitude, 3), round(longitude, 3) context.user_data['timezone'] = tf.timezone_at(lat=latitude, lng=longitude) text = f'Saving your location as {context.user_data["location"]} making your timezone be {context.user_data["timezone"]}' send(text, update, context)
def send_offer(self, start_port, payload): options = {"ICE": "remove", "label": "caller", "generate RTCP": "on"} sdp_offer = self.commands.offer( generate_sdp('127.0.0.1', start_port, payload=payload), # generate_sdp(self.sdp_address, start_port), str(start_port) + "-" + str(start_port + 2), "from-tag" + str(start_port), **options) if not self.ws: send(self.address, self.port, sdp_offer, self.sdp_address, start_port) else: ws_send(self.address, self.port, sdp_offer, bind_address=self.sdp_address, bind_port=start_port) self.calls.append({ 'call_id': str(start_port) + "-" + str(start_port + 2), 'from-tag': "from-tag" + str(start_port) })
def choose_pack(bot, update): packs = queries.active_packs(user(update)) if not packs: send(update, say.no_packs_available) return ConversationStates.QUIT send(update, say.enumerated(packs)) return ConversationStates.CHOOSE_PACK
def on_receive_message_3(client, userdata, msg): """ Handles the message received from device to confirm the shared_key. Then, it sends a message to be confirmed by the device. """ global encriptor, shared_key global symmetricAlgorithm # Received a message with the KEY generated + 30, to ensure the # rightful of the device to connect. Send KEY Received + 20. if encriptor != None: new_key = msg.get("new_key", "") if new_key != "": # Get the new_key to encrypt next message. encriptor = utils.modify_encriptor(new_key, symmetricAlgorithm) keyPlusThirty = shared_key + "30".encode() keyReceived = msg.get("payload", "") if str(keyPlusThirty) == keyReceived: key = shared_key + "20".encode() key_confirmation = {"payload": str(key)} # Generate the new key to be used by the platform to encrypt next message. key_confirmation["new_key"] = utils.generate_new_key( symmetricAlgorithm) message = add_header_message( key_confirmation, userdata,\ REGISTRATION_TOPIC, 4 ) utils.send(client, encriptor, message) # After sending the message, modify encriptor with the new # key before generated. encriptor = utils.modify_encriptor( key_confirmation["new_key"],\ symmetricAlgorithm ) return True return False
def get_pack_id(update): try: pack_id = queries.active_packs( update.message.from_user.id)[int(update.message.text) - 1][0] except (TypeError, IndexError, ValueError): send(update, say.incorrect_input) return None return pack_id
def mlm(update, context): """get me more stamina if you want""" messages = ( "If you're going to recruit a new player and already have enough stamina yourself, why not use my /promo code instead?\nI'm a collector and can use every extra bit of stamina.", 'Join the Chat Wars! First MMORPG in Telegram. Use this invite link to receive 10💰 as a welcome gift:\nhttps://telegram.me/chtwrsbot?start=ad53406f0a3544689bed29057419ae15', ) for message in messages: send(message, update, context)
def notify_learn_handle(bot, update): res = update.message.text if res not in enums.NotificationType.values(): send(update, say.incorrect_input + say.choose_learn_notifications, markup=enums.NotificationType.values()) return NOTIFY_LEARN states[user(update)].append(res) return notify_stats(update)
def general_goal_handle(bot, update): res = update.message.text if res not in enums.GenGoalType.values(): send(update, say.incorrect_input + say.choose_general_goal, markup=enums.GenGoalType.values()) return GENERAL_GOAL states[user(update)].append(res) return weekly_goal(update)
def start_voting(self, client_socket_coordinator, file_name): print("came to start voting") self.votes[file_name] = {} print("came to start voting") for client_socket in self.connections: if client_socket != client_socket_coordinator: self.votes[file_name][client_socket] = None send(client_socket, VOTING) send(client_socket, file_name)
def giveawayCom(): global giveaway giveaway = [] utils.send( s, "A giveaway has just begun! For the next 3 minutes, do !enter to put in your ticket!" ) t = threading.Thread(target=openClose) t.start()
def help_page(self, have_set_interaction): if not have_set_interaction: set_interaction(self.soc, False) path = os.path.join(".", "docs", self.cmd + ".txt") if os.path.exists(path): with open(path) as f: send(self.soc, f.read(), newline=True) else: send(self.soc, "Docs to be implemented", newline=True)
def settings(update, context): """direct users to the settings""" text = 'Use /save and/or /ignore to customize your experience.\n'\ '\n'\ 'Add a space-separated list of IDs after the command to save or ignore. You can limit how many of an item are affected by attaching an amount to the ID with a comma. Using the command with nothing else will show you what you have stored.\n'\ '\n'\ 'Example:\n'\ '<code>/save 01 02,150 03</code> 👈 Save all thread, all pelt and 150 sticks. Rest of the sticks get deposited.' send(text, update, context)
def weekly_goal_handle(bot, update): try: res = int(update.message.text) if not 1000 > res > 0: raise ValueError except (TypeError, ValueError): send(update, say.incorrect_weekly_goal) return WEEKLY_GOAL states[user(update)].append(res) return notify_learn(update)
def handle(self): optlist, args = getopt.getopt(self.args, 'h', ['help']) print("DEBUG/optlist:", optlist) print("DEBUG/args:", args) set_interaction(self.soc, False) if len(args) == 0 or ('--help', '') in optlist or ('-h', '') in optlist: self.help_page(True) else: send(self.soc, run.terminate(args[0]), newline=True)
def pack_chosen(bot, update): pack_id = get_pack_id(update) if not pack_id: return choose_pack(bot, update) cards = queries.select_cards(user(update), pack_id) if not cards: send(update, say.pack_is_empty) return choose_pack(bot, update) states[user(update)] = cards return choose_mode(bot, update)
def language_chosen(bot, update): if update.message.text not in languages: send(update, say.incorrect_input) return choose_language(bot, update) states[user(update)].language = (0 if update.message.text == languages[0] else 1) states[user(update)].shuffle() return ask( bot, update) if states[user(update)].type != ReviewTypes.TRUST else ask( bot, update, start_markup)
def registerApp(self): message = Message() networkMessage = NetworkMessage() networkMessage.senderHost = self.me.host networkMessage.senderListeningPort = self.me.port networkMessage.message.type = Message.Type.APP_REGISTRATION networkMessage.message.appRegistration.owner = self.me.owner networkMessage.message.appRegistration.index = self.me.index message.type = Message.Type.NETWORK_MESSAGE message.networkMessage.CopyFrom(networkMessage) send(self.hub.host, self.hub.port, message)
def exchange_key(client): """ Send this socket's public key to the connecting socket, receiver the connecting socket's public key :param client: the connecting socket :return: RSA public keys of connecting socket """ mess = str(public_key) utils.send(mess, client) mess_in = utils.recv_full_mess(client) client_n, client_d = re.findall(r"\d+", mess_in) client_keys = {'n': int(client_n), 'd': int(client_d)} return client_keys
def on_receive_message_7(client, userdata, msg): """ If Device has input, we will receive a code so we compare it with the verificationCode obtained before. If it has not input, we will receive a confimation, and if everything is ok, we will send the data_topic and key_topic. """ global encriptor, newDevice global symmetricAlgorithm, verificationCode if encriptor != None: validDevice = False deviceType = msg.get("type", "") if deviceType != "" and deviceType == "I": if verificationCode == msg.get("code", ""): validDevice = True else: if msg.get("status", "ERROR") == "OK": validDevice = True if validDevice: new_key = msg.get("new_key", "") if new_key != "": # Get the new_key to encrypt next message. encriptor = utils.modify_encriptor(new_key, symmetricAlgorithm) data_topic = "data-" + msg.get( "id" ) + "-" +\ str( round( random() * 1000000 ) ) key_topic = "key-" + msg.get( "id" ) + "-" +\ str( round( random() * 1000000 ) ) topic_message = {"data_topic": data_topic, "key_topic": key_topic} # Generate the new key to be used by the platform to encrypt\ # next message. topic_message["new_key"] = utils.generate_new_key( symmetricAlgorithm) message = add_header_message( topic_message, userdata,\ REGISTRATION_TOPIC, 8 ) utils.send(client, encriptor, message) # After sending the message, modify encriptor with the new # key before generated. encriptor = utils.modify_encriptor( topic_message["new_key"],\ symmetricAlgorithm ) newDevice = { "id": msg.get("id"), "type": deviceType, "data_topic": data_topic, "key_topic": key_topic, "symmetric": symmetricAlgorithm, "shared_key": topic_message["new_key"] } return True return False
def openClose(): global isOpen isOpen = "Open" sleep(10) isOpen = "Closed" utils.send( s, "The giveaway is closed! You may no longer enter.") sleep(1) utils.send(s, "/me is rolling the dice...") findWinner()
def end(bot, update): if not states[user(update)].wrong_answers: send(update, say.completed) review_quit(bot, update) return ConversationStates.QUIT send( update, say.inter_results(len(states[user(update)].right_answers), len(states[user(update)].wrong_answers))) states[user(update)].move(update) return ask(bot, update)
def setting_clear(update, context, section): old_settings = [] for item, count in sorted(context.user_data.get(section, {}).items()): if count: old_settings.append(f'{item},{count}') else: old_settings.append(item) previous = f'\n Previously <code>/{section} {" ".join(old_settings)}</code>' if old_settings else '' send(f'Ok, your {section} settings have been cleared{previous}', update, context) context.user_data[section] = {}
def restart(update, context): def stop_and_restart(): """Gracefully stop the Updater and replace the current process with a new one""" persistence.flush() updater.stop() os.execl(sys.executable, sys.executable, *sys.argv) logging.info('Bot is restarting...') send('Bot is restarting...', update, context) Thread(target=stop_and_restart).start() logging.info("...and we're back") send("...and we're back", update, context)
def exchange_key(socket): """Send this socket's public key to the connecting socket, receiver the connecting socket's public key :param socket: the connecting socket :return: RSA public keys of connecting socket """ mess_in = utils.recv_full_mess(socket) server_n, server_d = re.findall(r"\d+", mess_in) server_keys = {'n': int(server_n), 'd': int(server_d)} mess_out = str(pubic_key) utils.send(mess_out, socket) return server_keys
def choose_pack_h(bot, update): colon_ind = update.message.text.find(':') try: pack_id = int(update.message.text[:colon_ind]) except ValueError: update.message.reply_text('Invalid') return CHOOSE_PACK if queries.if_added(user(update), pack_id): send(update, say.already_added) return CHOOSE_PACK queries.add_pack(user(update), pack_id) return end(bot, update)
def handle(self): while True: req_data = utils.recv(self.request) if not req_data: break req_obj = json.loads(req_data) resp_obj = self._handle(req_obj) if resp_obj: resp_data = json.dumps(resp_obj) utils.send(self.request, resp_data) self.request.close()
def bango(request): """ Pass the request through to Bango. There's one job: 1) Parse the XML and insert the correct user and password """ namespaces = [ 'com.bango.webservices.billingconfiguration', 'com.bango.webservices.directbilling', 'com.bango.webservices.mozillaexporter' ] new_request = prepare(request) # Alter the XML to include the username and password from the config. root = etree.fromstring(new_request['data']) tags = lambda name: ['{%s}%s' % (n, name) for n in namespaces] username, password = tags('username'), tags('password') changed_username, changed_password = False, False for element in root.iter(): if element.tag in username: element.text = settings.BANGO_AUTH.get('USER', '') changed_username = True elif element.tag in password: element.text = settings.BANGO_AUTH.get('PASSWORD', '') changed_password = True # No point in process the rest of the body if both have # been changed. if changed_username and changed_password: break new_request['data'] = etree.tostring(root) return send(new_request)
def test(self): while True: cmd = raw_input("Enter command or 'exit':") if cmd == 'exit': self.modem.close() exit() elif cmd == 'unread': self.modem.write('AT+CMGL="REC UNREAD"\r') elif 'send' in cmd: message = cmd.split(':')[1] utils.send(self.modem, vuBinh, message) elif cmd == 'listen': self.modem.write('AT+CNMI=2,1,0,0,0\r'); while True: out = self.modem.readline(); #print(out) if "+CMTI" in out: utils.getMessage(self.modem, utils.getMessageIndex(out)) elif "REC UNREAD" in out: body = self.modem.readline() print(body) else: print "wrong cmd"
def braintree(request): """ Pass the request through to Braintree. There are two jobs to do: 1) Add in the Braintree auth into the HTTP headers 2) Ensure that requests will check the correct Braintree crt. """ new_request = prepare(request) # Until https://github.com/mozilla/solitude-auth/pull/3 is merged. new_request['headers']['Content-Type'] = 'application/xml; charset=utf-8' # Add in the correct Braintree Authorization. new_request['headers']['Authorization'] = b"Basic " + encodebytes( settings.BRAINTREE_PUBLIC_KEY.encode('ascii') + b":" + settings.BRAINTREE_PRIVATE_KEY.encode('ascii')).strip() # Taken from http://bit.ly/1cBESdC and ensures that the # crt is passed through to the requests verify parameter. new_request['verify'] = ( Environment.braintree_root() + '/ssl/api_braintreegateway_com.ca.crt') return send(new_request)
def reference(request, reference_name): """ Pass through the request to the reference implementation. We have to: * get the provider from the URL * sign the request with OAuth """ if reference_name not in settings.ZIPPY_CONFIGURATION: raise ValueError('Unknown provider: {}'.format(reference_name)) new_request = prepare(request) new_request['url'] = reference_url(request, new_request, reference_name) sign_request( None, settings.ZIPPY_CONFIGURATION[reference_name]['auth'], headers=new_request['headers'], method=new_request['method'].upper(), params={'oauth_token': 'not-implemented'}, url=new_request['url']) return send(new_request)
def send(self, msg, **params): send(self.topic_id, msg, **params)
def braintree(request): new_request = prepare(request) new_request['headers']['Authorization'] = braintree_authorization() return send(new_request)
cmd = sys.argv[2] requests = { "index": { "type":"index", "value": ["/Users/shun.yu/code/my.properties"] }, "search": { "type": "search", "key": "wd_ho" } } req_data = json.dumps(requests[cmd]) s = socket.socket() s.connect(("", int(sys.argv[1]))) utils.send(s, req_data) resp_data = utils.recv(s) s.close() if resp_data: resp_obj = json.loads(resp_data) print json.dumps(resp_obj)
# # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU General Public License for more details. # # # # You should have received a copy of the GNU General Public License # # along with this program; if not, write to the # # Free Software Foundation, Inc., # # 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # ############################################################################ """ *** Still not used in OpenBot *** """ from utils import messages as send send = send() base = {} class add: def __init__(self): send.system("PHandler's add class is loading...") def init(self, name, receiver): if base.has_key(name): warning("%s was handled before, replacing it" % name) base[name] = receiver class remove: def __init__(self): send.system("PHandler's remove class is loading...") def init(self, name): if base.has_key(name):
def handle_echo(socket, address): expression = receive(socket, 'request') print 'Got one task from client: %s' % expression result = calculate(expression) send(socket, result, 'response') socket.close()
def push_event_created_notification(match_slug, event, **kwargs): send('new-event:{slug}'.format(slug=match_slug), event.to_dict())
def push_match_created_notification(match, **kwargs): send('new-feed', match.to_dict())