def parse_response_and_run_command(response, proxies): """Parse response and run command.""" for update in response.json()['result']: chat_id = update['message']['chat']['id'] command = update['message']['text'] commands.run_command(chat_id, command, proxies)
def handle_read(self): char = self.recv(1) if (char == ""): self.unsubscribe() elif (char == '\n'): run_command(self, self._input_buffer) self._input_buffer = '' if self in subscribers: self._interact() else: return elif (char == '\r'): pass elif (char == '\x08'): if len(self._input_buffer) > 0: self.send(' ', False) self._input_buffer = self._input_buffer[:-1] self.send('\r') elif (char == '\x09'): self.send('\r') elif (char == '\x1B'): # TODO: Procesar teclas especiales (utilizan mas de un char, de momento se ignoran). # Utilizarlas para agregar funcionalidad a la consola (historia de comandos, etc). try: self.recv(5) except socket.error: pass elif (char >= '\x20') and (char <= '\x7E'): # TODO: reemplazar por un buffer eficiente self._input_buffer += char
def markdown_to_html_compiler(item, rules): ''' (Item, Rules) -> Item ''' filename = item.filepath.filename command = "pandoc -f markdown -t json -s {path}".format(path=item.filepath.path) json_lst = json.loads(c.run_command(command)) # This will return a dict {'json': ..., 'tags': ...} file_dict = organize_tags(json_lst, tag_synonyms, tag_implications) json_lst = file_dict['json'] tags = [Tag(t) for t in file_dict['tags']] command = "pandoc -f json -t html --mathjax --base-header-level=2" html_output = c.run_command(command, pipe_in=json.dumps(json_lst, separators=(',',':'))).encode('utf-8') env = Environment(loader=FileSystemLoader('.')) skeleton = env.get_template('templates/skeleton.html') # Get metadata ready ctx = Context( title = get_metadata_field(json_lst, "title"), math = get_metadata_field(json_lst, "math"), license = get_metadata_field(json_lst, "license"), ) final_filepath = item.filepath.route_with(rules.route) tags_lst = [] for tag in tags: tag_filepath = Filepath(tag.name).route_with(rules.tags_route) rel_path = tag_filepath.relative_to(final_filepath).path tags_lst.append({'name': tag.name, 'path': rel_path}) new_body = skeleton.render(body=html_output, title=ctx.title, tags=tags_lst, license=ctx.license, math=ctx.math).encode('utf-8') # We keep the original filepath return Item(item.filepath, new_body)
def markdown_to_html_compiler(filepath): ''' Take the filepath of a single markdown file and compile to HTML. ''' global tagsdir filename = os.path.basename(filepath) command = "pandoc -f markdown -t json -s {filepath}".format(filepath=filepath) json_lst = json.loads(c.run_command(command)) # This will return a dict {'json': ..., 'tags': ...} file_dict = organize_tags(json_lst, tag_synonyms, tag_implications) json_lst = file_dict['json'] tags = file_dict['tags'] # all_tags is global #all_tags[routename] = file_dict['tags'] command = "pandoc -f json -t html --mathjax --base-header-level=2" html_output = c.run_command(command, pipe_in=json.dumps(json_lst, separators=(',',':'))).encode('utf-8') env = Environment(loader=FileSystemLoader('.')) skeleton = env.get_template('templates/skeleton.html') # Get metadata ready title = get_metadata_field(json_lst, "title") math = get_metadata_field(json_lst, "math") license = get_metadata_field(json_lst, "license") # Each tag page is going to be at sitedir + tagsdir + tag. But if we reference this location from a file that is in a place other than sitedir, then it will point to sitedir + otherdir + tagsdir + tag or something weird. # To solve this problem, we have to figure out how deep tagsdir is, relative to sitedir. tagsdir_depth = len(split_path(tagsdir[:-1])) # the [:-1] removes the trailing slash final = skeleton.render(body=html_output, title=title, tags=tags, tagsdir=tagsdir_depth*"../"+tagsdir, license=license, math=math).encode('utf-8') return final
def play(): commands.cmd_cls() print("This is PyRPG.") print() print("Type 'help' for guidance.") print() while True: # not heroes.alagos.is_dead(): line = input(">> ").lower() cmd = line.split() cmd.append("EoCMD") cmd.append("EoCMD") commands.run_command(*cmd)
def check_updates(): """Проверка обновлений на сервере и инициация действий, в зависимости от команды""" global offset data = {'offset': offset + 1, 'limit': 10, 'timeout': 5} try: r = requests.post(FULL_URL + '/getUpdates', data=data) except: log_event('Error getting updates') return False if not r.status_code == 200: return False if not r.json()['ok']: return False for update in r.json()['result']: offset = update['update_id'] offset_file = open('offset', 'r') # Грязный хак. TODO пока не будет отслеживания old_offset = int(offset_file.read()) offset_file.close() if old_offset >= offset: continue offset_file = open('offset', 'w') offset_file.write(str(offset)) offset_file.close() if 'message' not in update or 'text' not in update['message']: log_event('Unknown update: %s' % update) continue from_id = update['message']['chat']['id'] if 'username' in update['message']['chat']: username = update['message']['chat']['username'] elif 'first_name' in update['message']['chat']: username = update['message']['chat']['first_name'] elif 'last_name' in update['message']['chat']: username = update['message']['chat']['last_name'] message = update['message']['text'] parameters = (offset, username, from_id, message) log_event('Message (id%s) from %s (id%s): "%s"' % parameters) run_command(*parameters)
def generate_all_tag_data(file_pattern="pages/*.md"): global all_tags # List of all the tag_data where each tag_data is of the form: # tag_data = { # 'tag': <tagname>, # 'pages': [ # {'title': <pagename>, 'url': <page_base_url>}, # ... # ] # } all_tag_data = [] lst_pages = glob.glob(file_pattern) page_data = [] all_tags = [] for page in lst_pages: json_lst = json.loads(c.run_command("pandoc -f markdown -t json {page}".format(page=page))) file_dict = organize_tags(json_lst, tag_synonyms, tag_implications) json_lst = file_dict['json'] title = get_metadata_field(json_lst, "title") url = os.path.splitext(os.path.basename(page))[0] tags = file_dict['tags'] all_tags.extend([i for i in tags]) page_data.append((title, url, tags)) all_tags = list(set(all_tags)) for tag in all_tags: pages = [] for page_tuple in page_data: if tag in page_tuple[2]: pages.append({'title': page_tuple[0], 'url': page_tuple[1]}) all_tag_data.append({'tag': tag, 'pages': pages}) return all_tag_data
def handle_event(event, client, bot_id): if event['type'] != 'message': return if event['user'] == bot_id: return response = run_command(event['text']) client.rtm_send_message(event['channel'], response)
def get_pages_using(self, items): ''' (Tag, [Item]) -> [Item] ''' final = [] for item in items: json_lst = json.loads(c.run_command("pandoc -f markdown -t json", pipe_in=item.body)) if self.name in get_metadata_field(json_lst, "tags"): final.append(item) return final
async def on_message(message): # Ignore messages from this bot if message.author == client.user: return # Find command if message.content.startswith(commands.Prefix): out_message, out_embed = commands.run_command(message) if out_message != '': await client.send_message(message.channel, out_message, embed=out_embed)
def lambda_handler(event, context): command = parse_command_body(event["body"]) response = "parse error" if command['command']: response = run_command(command) return { "statusCode": 200, "body": response, }
def index(): if request.method == 'POST': resp = request.get_json() chat_id = resp['message']['chat']['id'] command = resp['message']['text'][1:].strip() if not is_command(command): return '<h1>Wrong Command</h1>' msg = run_command(command, chat_id) send_message(msg) return jsonify(resp) return '<h1> im bot </h1>'
def run(text): if (re.match('close|exit', text, re.IGNORECASE)): return 'exit' for conf in config: matches = re.search(conf['regex'], text, re.IGNORECASE) if (matches): arg = matches.groups()[-1] if (conf['type'] == 'web-click'): commands.web_click(arg, conf['url']) elif (conf['type'] == 'web'): commands.web(arg, conf['url']) elif (conf['type'] == 'run'): commands.run(arg) elif (conf['type'] == 'run-path'): commands.run_path(conf['path']) elif (conf['type'] == 'command'): commands.run_command(conf['command']) else: print('Unknown type') return print('Unknown command') return
def parse_line(line): global logged_in # Complete command (:name!username@host command {args} :args) full_command = line.split( " ") # [:name!username@host, command{, args}, :args] if len(full_command) < 2: return # Sender info (:name!username@host) sender_info = full_command[0] sender_info = sender_info.lstrip(':').split('!') # [name, username@host] sender = sender_info[0] # name # Message and parameters (command {args} :args) message = full_command[1:] command = message[0] # command ### Numeric replies ### # Initial connection if not logged_in and (command == '439' or 'NOTICE' in command): execute('NICK %s' % config.nickname) execute('USER %s %s %s :%s' % (config.nickname, config.nickname, config.nickname, config.nickname)) # execute('NS GHOST %s %s' % (config.nickname, config.password)) logged_in = True # Start of MOTD elif command == '375': execute('NS IDENTIFY %s' % config.password) time.sleep(2) for channel in config.channels: execute('JOIN %s' % channel) # NAMES list elif command == '353': # message = ['353', bot_nickname, '=', #chan, :nick1, nick2, nick3] channel = message[3] # #chan message[4] = message[4].lstrip(':') # nick1 names_list = message[4:] # [nick1, nick2, nick3] for name in names_list: add_user(channel, name) ### Handle common messages ### elif command == 'KICK': current_channel = full_command[2] user = full_command[3] # Autojoin if user == config.nickname: execute('JOIN %s' % current_channel) # User KICKs else: remove_user(user, current_channel) # User JOINs elif command == 'JOIN' and sender != config.nickname: # message = ['JOIN', {':' + }#chan] current_channel = message[1].lstrip(':') add_user(current_channel, sender) # User PARTs elif command == 'PART': # message = ['PART', #chan, ':' + reason] current_channel = message[1] remove_user(current_channel, sender) # User QUITs elif command == 'QUIT': for channel in config.channels: remove_user(channel, sender) # User NICKs elif command == 'NICK': # message = ['NICK', ':' + new_nickname] new_nickname = message[1].lstrip(':') for channel, nicks in users.items(): if sender in nicks: remove_user(channel, sender) add_user(channel, new_nickname) # User commands elif command == 'PRIVMSG': # message = ['PRIVMSG', #chan, ':' + word1, word2, ...] message[2] = message[2].lstrip(':') current_channel = message[1] if current_channel == config.nickname: current_channel = sender command = None args = None if message[2].startswith("."): command = message[2].lstrip('.') args = message[3:] # List of parameters (split by spaces) full_text = ' '.join(message[2:]) message_data = { "sender": sender, "channel": current_channel, "full_text": full_text, "command": command, "args": args, } parser_logger.info(f"[{current_channel}] {sender}: {full_text}") run_command(message_data)
str_id = str(id) log( "Player ID " + str_id + " has requested a character which is already in " + "the world!", "info") players[id]['name'] = None mud.send_message(id, '<f15>What is your username? ') else: mud.send_message(id, '<f202>Password incorrect!\n') str_id = str(id) log("Player ID " + str_id + " has failed authentication", "info") players[id]['name'] = None mud.send_message(id, '<f15>What is your username? ') else: players[id]['idleStart'] = int(time.time()) if players[id]['exAttribute0'] < 1000: if len(command) > 0: command_lower = command.lower() run_command(command_lower, params, mud, players_db, players, rooms, npcs_db, npcs, items_db, items_in_world, env_db, env, scripted_events_db, event_schedule, id, fights, corpses, blocklist, map_area, character_class_db, spells_db, sentiment_db, guilds_db, clouds, races_db, item_history, markets, cultures_db) previous_timing = \ show_timing(previous_timing, "player commands")
return "True" else: return "False" if isinstance(unic, str): return unic else: return "" pages_pat = "pages/*.md" pages_lst = glob.glob(pages_pat) all_tags = [] page_data = [] for page in pages_lst: #print "on page " + page output = c.run_command("pandoc -f markdown -t json {page}".format(page=page)) json_lst = json.loads(output) file_dict = meta.organize_tags(json_lst, tag_synonyms, tag_implications) tags_lst = meta.get_tags(file_dict['json']) tags_lst = [to_unicode(i) for i in tags_lst] all_tags.extend(tags_lst) json_str = json.dumps(file_dict['json'], separators=(',',':')) body = c.run_command("pandoc -f json -t html --toc --template=templates/toc.html --mathjax --base-header-level=2", pipe_in=json_str).decode('utf-8') title = to_unicode(meta.get_metadata_field(json_lst, "title")) math = to_unicode(meta.get_metadata_field(json_lst, "math")) license = to_unicode(meta.get_metadata_field(json_lst, "license")) env = Environment(loader=FileSystemLoader('.')) skeleton = env.get_template('templates/skeleton.html') tags = [] for tag in tags_lst:
def parse_line(line): global logged_in # Complete command (:name!username@host command {args} :args) full_command = line.split(" ") # [:name!username@host, command{, args}, :args] if len(full_command) < 2: return # Sender info (:name!username@host) sender_info = full_command[0] sender_info = sender_info.lstrip(':').split('!') # [name, username@host] sender = sender_info[0] # name # Message and parameters (command {args} :args) message = full_command[1:] command = message[0] # command ### Numeric replies ### # Initial connection if not logged_in and (command == '439' or 'NOTICE' in command): execute('NICK %s' % config.nickname) execute('USER %s %s %s :%s' % (config.nickname, config.nickname, config.nickname, config.nickname)) # execute('NS GHOST %s %s' % (config.nickname, config.password)) logged_in = True # Start of MOTD elif command == '375': execute('NS IDENTIFY %s' % config.password) time.sleep(2) for channel in config.channels: execute('JOIN %s' % channel) # NAMES list elif command == '353': # message = ['353', bot_nickname, '=', #chan, :nick1, nick2, nick3] channel = message[3] # #chan message[4] = message[4].lstrip(':') # nick1 names_list = message[4:] # [nick1, nick2, nick3] for name in names_list: add_user(channel, name) ### Handle common messages ### elif command == 'KICK': current_channel = full_command[2] user = full_command[3] # Autojoin if user == config.nickname: execute('JOIN %s' % current_channel) # User KICKs else: remove_user(user, current_channel) # User JOINs elif command == 'JOIN' and sender != config.nickname: # message = ['JOIN', {':' + }#chan] current_channel = message[1].lstrip(':') add_user(current_channel, sender) # User PARTs elif command == 'PART': # message = ['PART', #chan, ':' + reason] current_channel = message[1] remove_user(current_channel, sender) # User QUITs elif command == 'QUIT': for channel in config.channels: remove_user(channel, sender) # User commands elif command == 'PRIVMSG': # message = ['PRIVMSG', #chan, ':' + word1, word2, ...] message[2] = message[2].lstrip(':') current_channel = message[1] if current_channel == config.nickname: current_channel = sender command = None args = None if message[2].startswith("."): command = message[2].lstrip('.') args = message[3:] # List of parameters (split by spaces) full_text = ' '.join(message[2:]) message_data = { "sender": sender, "channel": current_channel, "full_text": full_text, "command": command, "args": args, } timestamp = datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S") print(f"{timestamp} [{current_channel}] {sender}: {full_text}") run_command(message_data)
def message(self, msg): if msg['type'] in ('chat', 'normal'): from_peer = msg['from'].bare reply = msg.reply(run_command(msg['body'], from_peer)) reply.send()
def do_POST(self): # Get the post data content_length = int(self.headers['Content-Length']) post_data = self.rfile.read(content_length) # read post body post_data = bytes.decode(post_data) # convert to text post_data = json.loads(post_data) # convert to dictionary # Default message to send back message = {'ok': True} # Process the response if self.path == config_path_telegram: if ('edited_message' in post_data): post_data['message'] = post_data['edited_message'] if ('message' in post_data) and ('text' in post_data['message']): message = post_data['message'] chat_id = message['chat']['id'] text = message['text'] # extract sender information username = '******' first_name = '?' last_name = '?' full_name = '?' if 'from' in message: message_from = message['from'] if 'first_name' in message_from: first_name = message_from['first_name'] full_name = first_name if 'last_name' in message_from: last_name = message_from['last_name'] full_name += ' '+last_name if 'username' in message_from: username = message_from['username'] else: username = first_name # extract information from the text command = text[1:] arg = '' find_space = text.find(' ') find_newline = text.find('\n') if find_space >= 0 or find_newline >= 0: split_index = min(find_space, find_newline) if find_space == -1: split_index = find_newline if find_newline == -1: split_index = find_space command = text[1:split_index] arg = text[split_index+1:] # trim /command@bot down to /command find_at = command.find('@') if find_at >= 0: command = command[0:find_at] # run the command params = {'arg': arg, 'username': username, 'first_name': first_name, 'last_name': last_name, 'full_name': full_name} result = run_command(command, params) if result != None: message = {'method': 'sendMessage', 'disable_web_page_preview': True, 'chat_id': chat_id, 'text': result['text']} elif self.path == config_path_generic: if ('command' in post_data) and ('arg' in post_data): first_name = '?' last_name = '?' username = '******' full_name = '?' if 'first_name' in post_data: first_name = post_data['first_name'] full_name = first_name if 'last_name' in post_data: last_name = post_data['last_name'] full_name += ' '+last_name if 'username' in post_data: username = post_data['username'] # run the command params = {'arg': post_data['arg'], 'username': username, 'first_name': first_name, 'last_name': last_name, 'full_name': full_name} result = run_command(post_data['command'], params) if result != None: message = {'text': result['text']} else: print("Unrecognized path: "+self.path) # Set response code and headers self.send_response(200) self.send_header('Content-type','application/json') self.end_headers() # Send the response self.wfile.write(bytes(json.dumps(message), "utf8")) return
def parse_line(line): global logged_in # Complete command (:name!username@host command {args} :args) full_command = line.split() # [:name!username@host, command{, args}, :args] if len(full_command) < 2: return # Sender info (:name!username@host) sender_info = full_command[0] sender_info = sender_info.lstrip(":").split("!") # [name, username@host] sender = sender_info[0] # name # Message and parameters (command {args} :args) message = full_command[1:] command = message[0] # command ### Numeric replies ### # Initial connection if not logged_in and (command == "439" or "NOTICE" in command): execute("NICK %s" % nickname) execute("USER %s %s %s :%s" % (nickname, nickname, nickname, nickname)) execute("NS IDENTIFY %s" % password) # execute('NS GHOST %s %s' % (nickname, password)) logged_in = True # Start of MOTD elif command == "375": for channel in channels: execute("JOIN %s" % channel) # NAMES list elif command == "353": # message = ['353', bot_nickname, '=', #chan, :nick1, nick2, nick3] channel = message[3] # #chan message[4] = message[4].lstrip(":") # nick1 names_list = message[4:] # [nick1, nick2, nick3] for name in names_list: add_user(channel, name) ### Handle common messages ### elif command == "KICK": current_channel = full_command[2] user = full_command[3] # Autojoin if user == nickname: execute("JOIN %s" % current_channel) # User KICKs else: remove_user(user, current_channel) # User JOINs elif command == "JOIN" and sender != nickname: # message = ['JOIN', {':' + }#chan] current_channel = message[1].lstrip(":") add_user(current_channel, sender) # User PARTs elif command == "PART": # message = ['PART', #chan, ':' + reason] current_channel = message[1] remove_user(current_channel, sender) # User QUITs elif command == "QUIT": for channel in channels: remove_user(channel, sender) # User commands elif command == "PRIVMSG": # message = ['PRIVMSG', #chan, ':' + word1, word2, word3, ...] message[2] = message[2].lstrip(":") current_channel = message[1] if current_channel == nickname: current_channel = sender said = " ".join(message[2:]) params = message[3:] # List of parameters (split by spaces) message_data = {} message_data["sender"] = sender message_data["said"] = said message_data["current_channel"] = current_channel message_data["params"] = params run_command(message_data)
def getCommand(event=''): enteredCommand = entryCommand.get() for i in range(len(enteredCommand)): entryCommand.delete(0) return cmd.run_command(enteredCommand)
def main(): clargs = handle_clargs() from commands import run_command run_command(clargs)
#!/usr/bin/python import settings import commands import sys keep_running = True while keep_running: data = "" while data.find(settings.command_delim) == -1: data += sys.stdin.read(1) if len(data) == 0: break data = data.replace(settings.command_delim, "") if data == "exit": keep_running = False print "goodbye" else: try: commands.run_command(data) except ValueError: print "invalid_command" print settings.response_delim sys.stdout.flush()