How to use cmd_list method in localstack

Best Python code snippet using localstack_python

oss_cmd.py

Source:oss_cmd.py Github

copy

Full Screen

1#!/usr/bin/env python2# -*- coding: utf-8 -*-3## ossbrowser4## Author: melory5## Email:imsrch@melory.me6## License: GPL Version 27from oss_api import *8from oss_xml_handler import *9msg_remind = " PLEASE USE # TO SEPERATE EACH INPUT PARAMETER"10msg_quit = "q or quit, will quit out this console"11msg_help = "h or help, will show the message again"12#msg_get_service = "gs means get service , it lists all buckets that user has"13msg_get_service = "gs means get service."14example_get_service = "Input: gs"15GET_SERVICE = "get service"16#msg_put_bucket = "pb means put bucket, it creates bucket"17msg_put_bucket = "pb means put bucket."18example_put_bucket = "Input: pb#bucket||pb#bucket#acl||pb#bucket#acl#headers. "19PUT_BUCKET = "put bucket"20#msg_delete_bucket = "db means delete bucket, it deletes the bucket that user created"21msg_delete_bucket = "db means delete bucket."22example_delete_bucket = "Input: db#bucket"23DELETE_BUCKET = "delete bucket"24#msg_get_bucket = "gb means get bucket, it lists objects in the bucket"25msg_get_bucket = "gb means get bucket."26example_get_bucket = "Input: gb#bucket||gb#bucket#prefix||gb#bucket#prefix#marker||gb#bucket#prefix#marker#delimiter||gb#bucket#prefix#marker#delimiter#maxkeys||gb#bucket#prefix#marker#delimiter#maxkeys#headers"27GET_BUCKET = "get bucket"28#msg_get_bucket_acl = "gba means get bucket acl, it lists bucket acl"29msg_get_bucket_acl = "gba means get bucket acl."30example_get_bucket_acl = "Input: gba#bucket"31GET_BUCKET_ACL = "get bucket acl"32#msg_put_bucket_acl = "pba means put bucket acl, it sets bucket acl"33msg_put_bucket_acl = "pba means put bucket acl."34example_put_bucket_acl = "Input: pba#bucket#acl, Example: pba#mybucket#public-read"35PUT_BUCKET_ACL = "put bucket acl"36#msg_put_object_with_data = "powd means put object with data, it puts object, its content from string data"37msg_put_object_with_data = "powd means put object with data."38example_put_object_with_data = "Input: powd#bucket#object#string_data||powd#bucket#object#string_data#content_type||powd#bucket#object#string_data#content_type#headers, Example: powd#mybucket#myobjcet#abcdefghijk#txt/plain"39PUT_OBJECT_WITH_DATA = "put object with data"40#msg_put_object_from_file = "poff means put object from file, it puts object , its content from file"41msg_put_object_from_file = "poff means put object from file."42example_put_object_from_file = "Input: poff#bucket#object#filename||poff#bucket#object#filename#content_type||poff#bucket#object#filename#content_type#headers, Example: poff#mybucket#myobjcet#myfilename"43PUT_OBJECT_FROM_FILE = "put object from file"44#msg_get_object = "go means get object, it gets object and print its content"45msg_get_object = "go means get object."46example_get_object = "Input: go#bucket#object||go#bucket#object#headers, Example: go#mybucket#myobjcet"47GET_OBJECT = "get object"48#msg_get_object_to_file = "gotf means get object to file, it gets object and save its content to file"49msg_get_object_to_file = "gotf means get object to file."50example_get_object_to_file = "Input: gotf#bucket#object#filename||go#bucket#object#filename#headers, Example: goff#mybucket#myobjcet#tofilename"51GET_OBJECT_TO_FILE = "get object to file"52#msg_delete_object = "do means delete object, it deletes object"53msg_delete_object = "do means delete object."54example_delete_object = "Input: do#bucket#object||do#bucket#object#headers, Example: do#mybucket#myobjcet"55DELETE_OBJECT = "delete object"56#msg_head_object = "ho means head object, it gets meta info of object"57msg_head_object = "ho means head object."58example_head_object = "Input: ho#bucket#object||ho#bucket#object#headers, Example: ho#mybucket#myobject"59HEAD_OBJECT = "head object"60def usage():61 width = 4062 print "=> 1) ", msg_quit.ljust(width)63 print "=> 2) ", msg_help.ljust(width)64 print '***************************************'65 print "NOTE:acl in below means access control level, acl SHOULD be public-read, private, or public-read-write"66 print "headers and parameters below means dic, it SHOULD be dic like a=b c=d"67 print "content type means object type , it is used in headers, default is application/octet-stream"68 print '***************************************'69 print 'bucket operation'70 print "=> 3) ", msg_get_service.ljust(width), example_get_service71 print "=> 4) ", msg_put_bucket.ljust(width), example_put_bucket72 print "=> 5) ", msg_delete_bucket.ljust(width), example_delete_bucket73 print "=> 6) ", msg_get_bucket.ljust(width), example_get_bucket74 print "=> 7) ", msg_get_bucket_acl.ljust(width), example_get_bucket_acl75 print "=> 8) ", msg_put_bucket_acl.ljust(width), example_put_bucket_acl76 print ''77 print '***************************************'78 print 'objcet operation'79 print "=> 9) ", msg_put_object_with_data.ljust(width), example_put_object_with_data80 print "=>10) ", msg_put_object_from_file.ljust(width), example_put_object_from_file81 print "=>11) ", msg_get_object.ljust(width), example_get_object82 print "=>12) ", msg_get_object_to_file.ljust(width), example_get_object_to_file83 print "=>13) ", msg_delete_object.ljust(width), example_delete_object84 print "=>14) ", msg_head_object.ljust(width), example_head_object85 print ''86def print_result(cmd, res):87 if res.status / 100 == 2:88 print cmd, "OK"89 else:90 print "error headers", res.getheaders()91 print "error body", res.read()92 print cmd, "Failed!"93def check_input(cmd_str, cmd_list, min, max):94 if len(cmd_list) < min or len(cmd_list) > max: 95 print "ERROR! ", cmd_str, "needs ", min, "-", max, " paramters"96 if example_map.has_key(cmd_str):97 print example_map[cmd_str]98 return False 99 else:100 return True101def get_cmd(cmd):102 string = cmd 103 tmp_list = string.split('#')104 cmd_list = []105 for i in tmp_list:106 if len(i.strip()) != 0:107 cmd_list.append(i.strip()) 108 return cmd_list109 110def transfer_string_to_dic(string):111 list = string.split() 112 dic = {} 113 for entry in list: 114 key, val = entry.split('=') 115 dic[key.strip()] = val.strip()116 print dic117 return dic118if __name__ == "__main__":119 import sys120 host = ""121 user_name = ""122 access_id = ""123 secret_access_key = ""124 remind = "the method you input is not supported! please input h or help to check method supported"125 126 if len(sys.argv) != 4:127 print '***************************************'128 print 'Please input the parameters like below'129 print '***************************************'130 print 'python ', __file__,' host access_id access_key'131 print 'host is the ip address with port of oss apache server . For Example: 10.249.105.22:8080'132 print 'access_id is public key that oss server provided. For Example: 84792jahfdsah+='133 print 'access_key is private secret key that oss server provided. For Example: atdh+=flahmzhha=+'134 print '***************************************'135 print ''136 print ''137 exit()138 else:139 host = sys.argv[1]140 access_id = sys.argv[2]141 secret_access_key = sys.argv[3]142 oss = OssAPI(host, access_id, secret_access_key)143 usage()144 bucketname = ""145 example_map = {}146 example_map[PUT_BUCKET] = example_put_bucket147 example_map[PUT_BUCKET_ACL] = example_put_bucket_acl148 example_map[GET_SERVICE] = example_get_service149 example_map[GET_BUCKET] = example_get_bucket150 example_map[DELETE_BUCKET] = example_delete_bucket151 example_map[GET_BUCKET_ACL] = example_get_bucket_acl152 example_map[PUT_OBJECT_WITH_DATA] = example_put_object_with_data153 example_map[PUT_OBJECT_FROM_FILE] = example_put_object_from_file154 example_map[GET_OBJECT] = example_get_object155 example_map[GET_OBJECT_TO_FILE] = example_get_object_to_file156 example_map[DELETE_OBJECT] = example_delete_object157 example_map[HEAD_OBJECT] = example_head_object158 159 while True:160 cmd = raw_input(">>")161 cmd = cmd.strip()162 cmd_list = get_cmd(cmd) 163 if ("q" == cmd.lower() or "quit" == cmd.lower()):164 break165 elif ("h" == cmd.lower() or "help" == cmd.lower()):166 usage()167 elif len(cmd_list) > 0:168 if cmd_list[0].lower() == "pb":169 cmd_str = PUT_BUCKET170 min = 2171 max = 4172 if not check_input(cmd_str, cmd_list, min, max):173 pass174 else:175 print "cmd", cmd_list176 bucketname = cmd_list[1]177 if len(cmd_list) == 2:178 res = oss.put_bucket(cmd_list[1])179 elif len(cmd_list) == 3:180 res = oss.put_bucket(cmd_list[1], cmd_list[2])181 elif len(cmd_list) == 4:182 dic = transfer_string_to_dic(cmd_list[3])183 res = oss.put_bucket(cmd_list[1], cmd_list[2], dic)184 print_result(cmd_str, res)185 elif cmd_list[0] == "pba":186 cmd_str = PUT_BUCKET_ACL187 min = 3188 max = 3189 if not check_input(cmd_str, cmd_list, min, max):190 pass191 else:192 print "cmd", cmd_list193 bucketname = cmd_list[1]194 res = oss.put_bucket(cmd_list[1], cmd_list[2])195 print_result(cmd_str, res)196 elif cmd_list[0].lower() == "gs":197 cmd_str = GET_SERVICE198 min = 1199 max = 1200 if not check_input(cmd_str, cmd_list, min, max):201 pass202 else:203 print "cmd", cmd_list204 if len(cmd_list) == 1:205 res = oss.get_service()206 print_result(cmd_str, res)207 if (res.status / 100) == 2:208 body = res.read()209 h = GetServiceXml(body)210 print "bucket list size is: ", len(h.list())211 print "bucket list is: "212 for i in h.list():213 print i214 elif cmd_list[0].lower() == "gb":215 cmd_str = GET_BUCKET216 min = 2217 max = 7218 if not check_input(cmd_str, cmd_list, min, max):219 pass220 else:221 print "cmd", cmd_list222 bucketname = cmd_list[1]223 #get_bucket(bucket, prefix='', marker='', delimiter='', maxkeys='', headers = {}):224 if len(cmd_list) == 2:225 res = oss.get_bucket(cmd_list[1])226 elif len(cmd_list) == 3:227 res = oss.get_bucket(cmd_list[1], cmd_list[2])228 elif len(cmd_list) == 4:229 res = oss.get_bucket(cmd_list[1], cmd_list[2], cmd_list[3])230 elif len(cmd_list) == 5:231 res = oss.get_bucket(cmd_list[1], cmd_list[2], cmd_list[3], cmd_list[4])232 elif len(cmd_list) == 6:233 res = oss.get_bucket(cmd_list[1], cmd_list[2], cmd_list[3], cmd_list[4], cmd_list[5])234 elif len(cmd_list) == 7:235 dic = transfer_string_to_dic(cmd_list[6])236 res = oss.get_bucket(cmd_list[1], cmd_list[2], cmd_list[3], cmd_list[4], cmd_list[5], dic)237 print_result(cmd_str, res)238 if (res.status / 100) == 2:239 body = res.read()240 hh = GetBucketXml(body)241 (fl, pl) = hh.list()242 print "prefix list size is: ", len(pl)243 print "prefix listis: "244 for i in pl:245 print i246 print "file list size is: ", len(fl)247 print "file list is: "248 for i in fl:249 print i250 elif cmd_list[0].lower() == "db":251 cmd_str = DELETE_BUCKET252 print cmd_str253 min = 2 254 max = 2255 if not check_input(cmd_str, cmd_list, min, max):256 pass257 else:258 print "cmd", cmd_list259 if len(cmd_list) == 2:260 res = oss.delete_bucket(cmd_list[1])261 print_result(cmd_str, res)262 elif cmd_list[0].lower() == "gba":263 cmd_str = GET_BUCKET_ACL264 print cmd_str265 266 min = 2267 max = 2268 if not check_input(cmd_str, cmd_list, min, max):269 pass270 else:271 print "cmd", cmd_list272 bucketname = cmd_list[1]273 if len(cmd_list) == 2:274 res = oss.get_bucket_acl(cmd_list[1])275 print_result(cmd_str, res)276 if (res.status / 100) == 2:277 body = res.read()278 h = GetBucketAclXml(body)279 print "bucket ", bucketname, " acl is: ", h.grant280 elif cmd_list[0].lower() == "powd" or cmd_list[0].lower() == "poff":281 if cmd_list[0].lower() == "powd":282 cmd_str = PUT_OBJECT_WITH_DATA283 else:284 cmd_str = PUT_OBJECT_FROM_FILE285 min = 4 286 max = 6287 if not check_input(cmd_str, cmd_list, min, max):288 pass289 else:290 print "cmd", cmd_list291 bucketname = cmd_list[1]292 if isinstance(cmd_list[2], str):293 tmp = unicode(cmd_list[2], 'utf-8')294 cmd_list[2] = tmp295 if len(cmd_list) == 4:296 if cmd_list[0].lower() == "powd":297 res = oss.put_object_with_data(cmd_list[1], cmd_list[2], cmd_list[3])298 else:299 res = oss.put_object_from_file(cmd_list[1], cmd_list[2], cmd_list[3])300 elif len(cmd_list) == 5:301 if cmd_list[0].lower() == "powd":302 res = oss.put_object_with_data(cmd_list[1], cmd_list[2], cmd_list[3], cmd_list[4])303 else:304 res = oss.put_object_from_file(cmd_list[1], cmd_list[2], cmd_list[3], cmd_list[4])305 elif len(cmd_list) == 6:306 if cmd_list[0].lower() == "powd":307 dic = transfer_string_to_dic(cmd_list[5])308 res = oss.put_object_with_data(cmd_list[1], cmd_list[2], cmd_list[3], cmd_list[4], dic)309 else:310 dic = transfer_string_to_dic(cmd_list[5])311 res = oss.put_object_from_file(cmd_list[1], cmd_list[2], cmd_list[3], cmd_list[4], dic)312 print_result(cmd_str, res)313 elif cmd_list[0].lower() == "go":314 cmd_str = GET_OBJECT315 min = 3316 max = 4317 if not check_input(cmd_str, cmd_list, min, max):318 pass319 else:320 print "cmd", cmd_list321 bucketname = cmd_list[1]322 if len(cmd_list) == 3:323 res = oss.get_object(cmd_list[1], cmd_list[2])324 elif len(cmd_list) == 4:325 dic = transfer_string_to_dic(cmd_list[3])326 res = oss.get_object(cmd_list[1], cmd_list[2], dic)327 print_result(cmd_str, res)328 if res.status / 100 == 2:329 print res.read()330 331 elif cmd_list[0].lower() == "gotf":332 cmd_str = GET_OBJECT_TO_FILE333 min = 4334 max = 5335 if not check_input(cmd_str, cmd_list, min, max):336 pass337 else:338 print "cmd", cmd_list339 bucketname = cmd_list[1]340 if len(cmd_list) == 4:341 res = oss.get_object_to_file(cmd_list[1], cmd_list[2], cmd_list[3])342 elif len(cmd_list) == 5:343 dic = transfer_string_to_dic(cmd_list[4])344 res = oss.get_object_to_file(cmd_list[1], cmd_list[2], cmd_list[3], dic)345 print_result(cmd_str, res)346 347 elif cmd_list[0].lower() == "do":348 cmd_str = DELETE_OBJECT349 min = 3350 max = 4351 if not check_input(cmd_str, cmd_list, min, max):352 pass353 else:354 print "cmd", cmd_list355 bucketname = cmd_list[1]356 if len(cmd_list) == 3:357 res = oss.delete_object(cmd_list[1], cmd_list[2])358 elif len(cmd_list) == 4:359 dic = transfer_string_to_dic(cmd_list[3])360 res = oss.delete_object(cmd_list[1], cmd_list[2], dic)361 print_result(cmd_str, res)362 elif cmd_list[0].lower() == "ho":363 cmd_str = HEAD_OBJECT364 min = 3365 max = 4366 if not check_input(cmd_str, cmd_list, min, max):367 pass368 else:369 print "cmd", cmd_list370 bucketname = cmd_list[1]371 if len(cmd_list) == 3:372 res = oss.head_object(cmd_list[1], cmd_list[2])373 elif len(cmd_list) == 4:374 dic = transfer_string_to_dic(cmd_list[3])375 res = oss.head_object(cmd_list[1], cmd_list[2], dic)376 print_result(cmd_str, res)377 if res.status / 100 == 2:378 print res.getheaders()379 else:380 print remind381 else:...

Full Screen

Full Screen

admin.py

Source:admin.py Github

copy

Full Screen

1import requests2from requests.exceptions import HTTPError3import json4from utilities import clear_screen5from utilities import psr678def admin_loop(usr):9 cmd = ''1011 while cmd != 'logout':12 try:13 cmd = (input(f'{usr}> '))14 cmd_list = cmd.split()1516 if len(cmd_list) == 3 and cmd_list[0] == 'adad':17 add_account(cmd_list, 'ADMIN')18 19 elif cmd_list[0] == 'edad':20 edit_account(cmd_list, 'ADMIN')2122 elif len(cmd_list) == 3 and cmd_list[0] == 'delad':23 del_account(cmd_list)2425 elif cmd_list[0] == 'adfac':26 add_account(cmd_list, 'FACULTY')2728 elif cmd_list[0] == 'edfac':29 edit_account(cmd_list, 'FACULTY')3031 elif cmd_list[0] == 'delfac':32 del_account(cmd_list)3334 elif cmd_list[0] == 'adtut':35 add_account(cmd_list, 'TUTOR')3637 elif cmd_list[0] == 'edtut':38 edit_account(cmd_list, 'TUTOR')3940 elif cmd_list[0] == 'deltut':41 del_account(cmd_list)4243 elif len(cmd_list) == 9 and cmd_list[0] == 'adts':44 adts(cmd_list)4546 elif cmd_list[0] == 'edts':47 edts()48 49 elif cmd_list[0] == 'delts':50 delts()5152 elif cmd_list[0] == 'psa':53 psa(cmd_list)5455 elif cmd_list[0] == 'papt':56 papt()5758 elif cmd_list[0] == 'psr':59 psr(usr)6061 elif cmd_list[0] == 'rnrpt':62 rnrpt()6364 elif cmd_list[0] == 'srpt':65 srpt()6667 elif len(cmd_list) == 1 and cmd_list[0] == '--help':68 gethelp()6970 elif len(cmd_list) == 1 and cmd_list[0] == 'clear':71 clear_screen()72 73 elif cmd != 'logout':74 print('Error: Invalid command')75 76 except IndexError as ind:77 if cmd == '\r' or '\n': continue78 else:79 print('Error: Wrong number of arguments')80 continue81 except HTTPError as http_err:82 print(f'HTTP Error: {http_err}')83 continue84 except KeyboardInterrupt as kybrd:85 cmd = 'logout'86 print()87 except Exception as err:88 print(f'Error: {err}')89 continue90 919293def add_account(cmd_list, new_role):94 if cmd_list[1] == '-u':95 usr_name = str(cmd_list[2])96 pswrd = 'Leo'97 pswrd = pswrd + usr_name + '!'98 email = usr_name + '@una.edu'99100 url = 'https://quanthu.life/tutorapp/users'101 data = {'username': usr_name,102 'email': email,103 'password': pswrd,104 'phone': "",105 'role': new_role106 }107 req = requests.post(url, json = data)108 resp = json.loads(req.text)109110 if resp['errorCode'] == 200:111 print('New user has been successfully created')112 elif resp['errorCode'] == 404:113 print(resp['message'])114 115 else:116 print('Error: invalid arguement(s)')117118119120def del_account(cmd_list):121 if cmd_list[1] == '-u':122 is_found = True123 users_url = 'https://quanthu.life/tutorapp/users/'124 125 req = requests.get(users_url)126 users = json.loads(req.text)127 128 if users['errorCode'] == 200:129 for item in users['data']:130 if cmd_list[2] == item['username']:131 is_found = True132 _id = item['_id']133 del_url = users_url + _id134 del_usr = requests.delete(del_url)135 del_resp = json.loads(del_usr.text)136 137 if del_resp['errorCode'] == 200:138 print('User has been successfully deleted')139 else:140 print(del_resp['message'])141 else: is_found = False142143 if is_found == False:144 print('Invalid username')145 146 elif users['errorCode'] == 404:147 print(users['message'])148 else:149 print('Error: invalid arguement(s)')150 151152#edad -u usrname -n newUsr -p phones153def edit_account(cmdlist, role):154 url = 'https://quanthu.life/tutorapp/users/role/' + role155 usrs = requests.get(url)156 usrs_resp = json.loads(usrs.text)157 158 data = {}159 is_found, _id = True, ''160161 if cmdlist[1] == '-u' and cmdlist[3] == '-n' and cmdlist[5] == '-p':162 for item in usrs_resp['data']:163 if cmdlist[2] == item['username']:164 165 data = {'_id': item['_id'],166 'username': cmdlist[4],167 'email': item['email'],168 'password': item['password'],169 'phone': cmdlist[6],170 'role': item['role'],171 'lastActivityDateTime': item['lastActivityDateTime'],172 'isActive': item['isActive']}173 is_found = True174 175 url = 'https://quanthu.life/tutorapp/users/' + item['_id']176 put_req = requests.put(url, json = data)177 resp = json.loads(put_req.text)178 if resp['errorCode'] == 200:179 print('Your account has been successfully edited')180 else:181 print('Your account was not edited successfully') 182 break183 else: is_found = False184 185186 #update username187188 else:189 print('Error: Wrong argument passed')190191192193#adts -u hbrown5 -d <dateTime> -f <fromTime> -e <endTime>194def adts(cmd_list):195 if cmd_list[1] == '-u' and cmd_list[3] == '-d' and cmd_list[5] == '-f'\196 and cmd_list[7] == '-e':197 is_found = True198 users_url = 'https://quanthu.life/tutorapp/users'199 sched_url = 'https://quanthu.life/tutorapp/schedule'200 201 req = requests.get(users_url)202 users = json.loads(req.text)203204 if users['errorCode'] == 200:205 for item in users['data']:206 if str(cmd_list[2]) == item['username']:207 is_found = True208 tutor_id = item['username']209 data = {'_id': item['_id'],210 'tutor_id': tutor_id,211 'weekday': str(cmd_list[4]),212 'from_time': str(cmd_list[6]),213 'end_time': str(cmd_list[8]),214 'isActive': True}215 216 sched_req = requests.post(sched_url, json = data)217 sched_resp = json.loads(sched_req.text)218 219 if sched_resp['errorCode'] == 200:220 print('New schedule has been created')221 else:222 print(sched_resp['message'])223 break224 225 else: is_found = False226 227 if is_found == False:228 print('Invalid username')229 230 elif users['errorCode'] == 404:231 print(users['message'])232 else:233 print('Error: invalid arguement(s)')234235 236237def edts():238 print("Change a given tutor's availability schedule\n")239240241242#delts -u hbrown5243#The Deletion server command is not working properly244def delts(cmd_list):245 print("Deleting tutor's schedule\n")246247248249# psa -e hbrown5@una.edu250def psa(cmd_list):251 url = 'https://quanthu.life/tutorapp/users/role/STUDENT'252 is_found = True253 254 if cmd_list[1] == '-e':255 req = requests.get(url)256 students = json.loads(req.text)257258 if students['errorCode'] == 200:259 for student in students['data']:260 if cmd_list[2] == student['email']:261 is_found = True262 del_id = student['_id']263 del_url = 'https://quanthu.life/tutorapp/users/' + del_id264 del_stud = requests.delete(del_url)265 del_resp = json.loads(del_stud.text)266 267 if del_resp['errorCode'] == 200:268 print('User has been successfully deleted')269 else:270 print(del_resp['message'])271 272 else: is_found = False273 274 if is_found == False:275 print('Invalid student account')276277 elif students['errorCode'] == 404:278 print(students['errorCode'])279280 else:281 print('Error: Invalid argument(s)')282283 284 285286def papt():287 print("Purge an appointment by given date\n")288289290291def rnrpt():292 if cmd_list == '-a':293 print('List of admins/n')294295 elif cmd_list == '-f':296 print('List of faculty members/n')297298 elif cmd_list == '-s':299 print('List of distinct students tutored by date range/n')300301 elif cmd_list == '-t':302 print('List of tutoring appointments by date range/n')303304 elif cmd_list == '-d':305 print('List of distinct students tutored by tutor and date range/n')306307 elif cmd_list == '-u':308 print('Total number of hours unused by tutor by date range/n')309310 elif cmd_list == '-c':311 print('Total hours available by course by date range/n')312313 elif cmd_list[1] == '-l':314 print('List of tutors and their availability schedules/n')315316 elif cmd_list == '-p':317 print('Student activity by date range and course(scheduled and completed)/n')318319 elif cmd_list == '-r':320 print('Tutor activity by date range and course (scheduled and completed)/n')321322 else:323 print('Error: Invalid argument(s)')324325def srpt():326 print("Schedule a report to be emailed periodically")327328def gethelp():329 infile = open("help_faculty.txt", "r")330 lines = infile.readlines()331332 for line in lines:333 print(line, end = "")334335 print() 336 infile.close() ...

Full Screen

Full Screen

parse_cmd.py

Source:parse_cmd.py Github

copy

Full Screen

1import os2import random3import discord4from validator import *5from messages import *6from search import get_search_results7from init_tracker import init_parse8from character_sheet import character_parse9from spellbook_builder import spellbook_parse10ERROR_NO_PREV_COMMAND = "You have not run a `!dnd` command yet!"11INVALID_CHANNEL = "Sorry, this cannot be run in a public channel, please re-run this command in a direct message to me"12INVALID_FORMAT = "Invalid formatting, you must enter valid die roll"13last_cmd_for_user = {}14# parses user messages 15def parse(msg) -> str:16 cmd_list = msg.content[5:].split(" ")17 # runs the last command the user ran, if they have a last run command18 if (cmd_list[0] == ''):19 pass20 # return run_last_command(msg.author.id)21 # user wants to roll some dice22 if (cmd_list[0] == "roll" or cmd_list[0] == "r"): 23 last_cmd_for_user[msg.author.id] = msg24 return roll_dice(cmd_list[1:])25 # user wants to view the help message26 elif (cmd_list[0] == "help"): 27 last_cmd_for_user[msg.author.id] = msg28 return build_help_message()29 # user wants to search for some dnd related text30 elif (cmd_list[0] == "search" or cmd_list[0] == "s"): 31 last_cmd_for_user[msg.author.id] = msg32 return search_helper(cmd_list[1:])33 # user wants to do something with initiative tracking34 elif (cmd_list[0] == "initiative" or cmd_list[0] == "init" or cmd_list[0] == "i"):35 last_cmd_for_user[msg.author.id] = msg36 return init_helper(cmd_list[1:], msg)37 # user wants to do something with characters38 elif (cmd_list[0] == "character" or cmd_list[0] == "c"):39 last_cmd_for_user[msg.author.id] = msg40 return character_helper(cmd_list[1:], msg)41 elif (cmd_list[0] == "sb"):42 last_cmd_for_user[msg.author.id] = msg43 return spellbook_helper(cmd_list[1:], msg)44 # user wants to do something that the bot can't do 45 else:46 return "Sorry, that command doesn't exist!\nType `!dnd help` to view commands"47# re-runs the last command for a user48def run_last_command(user_id):49 try:50 return parse(last_cmd_for_user[user_id])51 except:52 return ERROR_NO_PREV_COMMAND53# helper for spellbook54def spellbook_helper(cmd_list, msg):55 if (not isinstance(msg.channel, discord.channel.DMChannel)):56 return INVALID_CHANNEL57 else:58 return spellbook_parse(cmd_list, msg.author)59# helper for characters60def character_helper(cmd_list, msg):61 if (not isinstance(msg.channel, discord.channel.DMChannel)):62 return INVALID_CHANNEL63 else:64 return character_parse(cmd_list, msg.author)65# helper for initiative66def init_helper(cmd_list, msg):67 if (not isinstance(msg.channel, discord.channel.DMChannel)):68 return INVALID_CHANNEL69 else:70 return init_parse(cmd_list, msg.author)71# helper for searching72def search_helper(cmd_list) -> str:73 if (len(cmd_list) < 1):74 return INVALID_FORMAT + ", you must enter a value after 'search'"75 76 # if the query contains spaces, convert the spaces to -'s77 if (len(cmd_list) > 1):78 query = ""79 for i in range(len(cmd_list)):80 query += cmd_list[i]81 if (i != len(cmd_list) - 1):82 query += "-"83 # contained no spaces84 else:85 query = cmd_list[0]86 return get_search_results(query)87# parses the roll command and does error handling88def roll_dice(cmd_list) -> str:89 # ensures they typed the command correctly90 if (len(cmd_list) < 1):91 return INVALID_FORMAT92 # makes sure the user formatted the first parameter correctly93 if (len(cmd_list[0].split("d")) > 1):94 value = 095 # gets the number of dice and die type96 num_dice = cmd_list[0].split("d")[0]97 die_type = cmd_list[0].split("d")[1]98 99 # makes sure these values are valid100 res = validate_dice(num_dice, die_type)101 if (res != "valid"):102 return res103 add = False104 modifier = 0105 # advantage value (n, a, d)106 advantage_val = "n"107 # checks to see if users inputed a modifier OR advantage/disadvantage108 if (len(cmd_list) > 1):109 advantage = False110 # gets the modifier type111 if (cmd_list[1] == "+"):112 add = True113 elif (cmd_list[1] == "-"):114 add = False115 elif (cmd_list[1] == "a"):116 advantage = True117 advantage_val = "a"118 elif (cmd_list[1] == "d"):119 advantage = True120 advantage_val = "d"121 else:122 # anything besides +, -, a, d is invalid123 return INVALID_FORMAT + ", invalid operation: `" + cmd_list[1] + "`"124 # if the user inputted an operator, but no modifier125 if(len(cmd_list) < 3 and not advantage):126 return INVALID_FORMAT + ", operator exists, but no modifier"127 128 # checks to make sure the modifier is valid129 if (not advantage):130 try:131 modifier = int(cmd_list[2])132 except:133 return INVALID_FORMAT + ", modifier: `" + cmd_list[2] + "`"134 135 # handle advantage or disadvantage136 if (len(cmd_list) == 4):137 if (cmd_list[3].lower() != 'a' and cmd_list[3].lower() != 'd'):138 return INVALID_FORMAT + ", invalid advantage/disadvantage: `" + cmd_list[3] + "`"139 140 advantage_val = cmd_list[3].lower()141 # user has advantage142 if (advantage_val == "a"):143 value = max([roll(num_dice, die_type), roll(num_dice, die_type)])144 # user has disadvantage145 elif (advantage_val == "d"):146 value = min([roll(num_dice, die_type), roll(num_dice, die_type)])147 # neither advantage or disadvantage148 else:149 value = roll(num_dice, die_type)150 # if there is a modifier, we add it or subtract it151 if (add):152 value += modifier153 else:154 value -= modifier155 # don't want to show negative or 0 to the user156 if (value <= 0):157 value = "You rolled a: 1, oof"158 return "You rolled: " + str(value)159 else:160 return INVALID_FORMAT + "invalid roll type: `" + cmd_list[0] + "`"161# rolls a set a of dice162def roll(num_dice, die_type):163 value = 0164 for i in range(int(num_dice)):165 value += random.randint(1, int(die_type))...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run localstack automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful