import numpy as np import numpy.fft as fft import alsaaudio as aa from pykeyboard import PyKeyboard kbd = PyKeyboard() CHUNKSIZE = 256 #CHUNKSIZE = 512 RATE = 44100 FREQ_SIZE = CHUNKSIZE // 2 + 1 MEM_SIZE = 5 inp = aa.PCM(aa.PCM_CAPTURE) inp.setchannels(1) inp.setrate(RATE) inp.setformat(aa.PCM_FORMAT_S16_LE) inp.setperiodsize(CHUNKSIZE) mem = np.zeros(MEM_SIZE) state = 0 steps = 0 def proc(rec): global mem, state, steps f = fft.rfft(rec) fr = np.abs(f) n = rec.size timestep = 1 / RATE
def __init__(self): # 实例化鼠标,键盘对象 self.mouse = PyMouse() self.keyboard = PyKeyboard()
def __init__(self, browser, configuration_file_download): logger.info( "========================================================测试开始========================================================" ) self.driver = self.__open_browser(browser, configuration_file_download) self.pkb = PyKeyboard()
def __init__(self): self.mouse = PyMouse() self.keyboard = PyKeyboard() self.sleep = 0.5 time.sleep(1)
#coding=utf-8 from selenium import webdriver from selenium.webdriver.support.select import Select from pykeyboard import PyKeyboard import time driver = webdriver.Chrome() pykey = PyKeyboard() driver.get('http://www.imooc.com') element = driver.find_element_by_id("js-signin-btn") element.click() time.sleep(3) driver.find_element_by_name("email").send_keys('*****@*****.**') element = driver.find_element_by_name('password') element.send_keys('xu221168') driver.find_element_by_class_name("moco-btn-lg").click() time.sleep(2) driver.get("https://www.imooc.com/user/setprofile") time.sleep(5) element = driver.find_element_by_xpath( "//a[@class='avator-btn-fake']/following-sibling::input[1]") #driver.find_element_by_id("upload").send_keys("C:\\Users\\KYB\\Desktop\\12.png") time.sleep(5) element.send_keys('C:\\Users\\KYB\\Desktop\\12.png') ''' time.sleep(10) pykey.tap_key(pykey.shift_key) pykey.type_string('C:\\Users\\KYB\\Desktop\\12.png') time.sleep(2) pykey.tap_key(pykey.enter_key) '''
class AutoAlterac: k = PyKeyboard() m = PyMouse() JoinImgFlg = Image.open("JoinImgFlg.png") LeaveImgFlg = Image.open("LeaveImgFlg.png") EscapeIcon = Image.open("EscapeIcon.png") PrepareImgFlg = [] BATTLE_FINISHED = 0 BATTLE_ESCAPED = 1 fieldNum = 0 def __init__(self): for i in range(0, 5): self.PrepareImgFlg.append(Image.open(utils.PrepareImgName[i])) def battle_field(self): while True: self.__target_npc() time.sleep(0.2) self.__interact_npc() time.sleep(0.2) self.__queue_for_battle() time.sleep(0.2) t = self.__wait_to_join(120) if t >= 0: if self.__check_new_field(): print "Prepare to join battle field...." for i in range(3, 0, -1): print i time.sleep(1) self.__join_to_battle() return t else: print "No new field! Reset!" self.__leave_battle_queue() else: self.__leave_battle_queue(1) continue def __leave_battle_queue(self, t=0): print "start leave battle queue!" time.sleep(1) self.__mouse_click(1978, 230, 2) time.sleep(1) self.k.tap_key(self.k.enter_key) time.sleep(1) if t == 0: self.__mouse_click(2021, 314) else: self.__mouse_click(2021, 295) time.sleep(1) self.k.tap_key(self.k.enter_key) time.sleep(1) print "leave!" def to_bridge(self, wait_time): self.march(2) time.sleep(0.1) self.turn_right(0.28) self.march(8.5) time.sleep(wait_time) self.march(5.5) time.sleep(0.2) self.mount() self.turn_right(0.1) self.march(5.6) self.turn_right(0.3) self.march(12) self.turn_right(0.1) self.march(12) self.mount() self.k.tap_key(self.k.function_keys[4]) time.sleep(2) def defence(self, t): c = 0 while True: self.__speak("For the alliance!") r = random.randint(10, 20) time.sleep(r) c = c + r print 'Field %s:Defence %s' % (self.fieldNum, sec_to_time(c)) if self.check_battle_finish(): print "Battle finished!" self.__leave_battle() time.sleep(30) return self.BATTLE_FINISHED if self.check_escape(): print "Battle escaped!" return self.BATTLE_ESCAPED if c > t: print "Battle timeout , AFK!" self.__afk() time.sleep(30) return self.BATTLE_ESCAPED def away_from_kbd(self, t): c = 0 while c < t: self.k.tap_key(self.k.space_key) r = random.randint(10, 20) time.sleep(r) c = c + r print "rest:" + sec_to_time(t - c) + " left" def march(self, t): self.k.press_key('w') time.sleep(t) self.k.release_key('w') def turn_right(self, t): self.k.press_key(self.k.right_key) time.sleep(t) self.k.release_key(self.k.right_key) def mount(self): self.k.press_key(self.k.alt_key) self.k.tap_key('t') self.k.release_key(self.k.alt_key) time.sleep(3.5) def check_battle_finish(self): cur_img = utils.grab_leave_dialog_img() sim = utils.calc_similar(cur_img, self.LeaveImgFlg) if sim > 0.95: return True else: return False def check_escape(self): cur_img = utils.grab_escape_icon() sim = utils.calc_similar(cur_img, self.EscapeIcon) if sim > 0.95: return True else: return False def __target_npc(self): self.k.tap_key('9') print "Target NPC" def __interact_npc(self): self.k.tap_key('0') print "interact" def __queue_for_battle(self): self.__click_macro('GossipTitleButton1') # for i in range(0, 30): # self.__mouse_click(386, 436) # time.sleep(0.1) # time.sleep(1) # self.__mouse_click(196, 454) # time.sleep(1) time.sleep(0.2) self.__click_macro('BattlefieldFrameJoinButton') def __check_new_field(self): self.__target_npc() time.sleep(0.2) self.__interact_npc() time.sleep(0.2) self.__click_macro('GossipTitleButton1') time.sleep(0.2) for i in range(0, 30): self.__mouse_click(386, 436) time.sleep(0.1) print "Check new field...." for i in range(0, 5): cur_image = utils.grab_prepare_img(i) sim = utils.calc_similar(cur_image, self.PrepareImgFlg[i]) print i, sim if sim > 0.95: return True return False def __wait_to_join(self, limit): t = 0 while True: if t > limit: return -1 print "wait ti join...." time.sleep(2) t = t + 2 cur_img = utils.grab_join_dialog_img() sim = utils.calc_similar(cur_img, self.JoinImgFlg) print sim if sim > 0.8: return t def __join_to_battle(self): self.__click_macro('StaticPopup1Button1') self.fieldNum += 1 print "Join battle field!" def __afk(self): self.k.tap_key(self.k.enter_key) time.sleep(0.2) self.k.type_string('/afk') time.sleep(0.2) self.k.tap_key(self.k.enter_key) def __leave_battle(self): print "Leave battle!" self.__click_macro('WorldStateScoreFrameLeaveButton') def __click_macro(self, s): self.k.tap_key(self.k.enter_key) time.sleep(0.2) self.k.type_string('/click') time.sleep(0.2) self.k.tap_key(self.k.space_key) time.sleep(0.2) self.k.type_string(s) time.sleep(0.2) self.k.tap_key(self.k.enter_key) def __speak(self, s): self.k.tap_key(self.k.enter_key) time.sleep(0.2) self.k.type_string('/5') time.sleep(0.2) self.k.tap_key(self.k.space_key) time.sleep(0.2) self.k.type_string(s) time.sleep(0.2) self.k.tap_key(self.k.enter_key) def __mouse_click(self, x, y, btn=1): self.m.click(utils.to_real_pos(x), utils.to_real_pos(y), btn) def __mouse_move(self, x, y): self.m.move(utils.to_real_pos(x), utils.to_real_pos(y))
def __init__(self, user_name, user_pwd): self._user_name = user_name self._user_pwd = user_pwd self.keyboard = PyKeyboard() self.mouse = PyMouse()
def computer_type_input(my_string): '''模拟键盘输入字符串''' # 定义鼠标键盘实例 k = PyKeyboard() k.type_string(my_string)
def main(): global Icq1List global Icq2List global PAcurrentList # 配置线损 lossName = PM.query("CONFigure:BASE:FDCorrection:CTABle:CATalog?") time.sleep(1) if lossName.find("CMW_loss") != -1: PM.write("CONFigure:BASE:FDCorrection:CTABle:DELete 'CMW_loss'") PM.write( "CONFigure:BASE:FDCorrection:CTABle:CREate 'CMW_loss', 1920000000, 0.8, 1980000000, 0.8, \ 2110000000, 0.8, 2170000000, 0.8, 1850000000, 0.8 1910000000, 0.8, 1930000000, 0.8, 1990000000, 0.8,\ 824000000, 0.5, 849000000, 0.5, 869000000, 0.5, 894000000, 0.5, 925000000, 0.5, 960000000, 0.5, \ 880000000, 0.5, 915000000, 0.5, 2350000000, 0.9, 2535000000, 0.9, 2593000000, 0.9" ) PM.write("CONFigure:FDCorrection:ACTivate RF1C, 'CMW_loss', RXTX, RF1" ) #配置RF1 Common口的Tx Rx方向损耗 PM.write("CONFigure:FDCorrection:ACTivate RF1O, 'CMW_loss', TX, RF1" ) #配置RF1 OUT口的Tx方向损耗 if PAcurrentGenerateMode == 0: Icq1 = int(PAcurrentInitial / 256) Icq2 = int(PAcurrentInitial - Icq1 * 256) Icq1List = [] Icq2List = [] for ii in range(-LeftExtendPeriodIcq1, RightExtendPeriodIcq1 + 1): Temp_Icq1 = list( range(Icq1 + ii * period - ScanRangeIcq1, Icq1 + ii * period + ScanRangeIcq1 + 1)) Icq1List.extend(Temp_Icq1) for ii in range(-LeftExtendPeriodIcq2, RightExtendPeriodIcq2 + 1): Temp_Icq2 = list( range(Icq2 + ii * period - ScanRangeIcq2, Icq2 + ii * period + ScanRangeIcq2 + 1)) Icq2List.extend(Temp_Icq2) if PAcurrentGenerateMode < 2: PAcurrentList = zeros(len(Icq1List) * len(Icq2List)) for ii in range(len(Icq1List)): for jj in range(len(Icq2List)): PAcurrentList[ii + jj * len(Icq1List)] = (Icq1List[ii] * 256 + Icq2List[jj]) PAcurrentList = list(map(int, PAcurrentList)) print("Icq1List is %s" % Icq1List) print("Icq2List is %s" % Icq2List) if PAcurrentListExtendFlag == 1: PAcurrentList.extend(PAcurrentListExtend) print("PAcurrentList length is %d" % (len(PAcurrentList))) print("PAcurrentList is %s" % PAcurrentList) if ModeChosen in [0, 1]: ChannelList = channelLteList(bandChosen, LteBW, ScanType) elif ModeChosen == 2: ChannelList = channel3GList(bandChosen, ScanType) if ReadCurrentFlag == 0: print("expected test time is %3.1f minutes" % float( len(PAcurrentList) * len(RGIlist) * len(ChannelList) * 16 / 60)) else: print("Reading current needed, expected test time is %3.1f minutes" % float(len(PAcurrentList) * len(RGIlist) * len(ChannelList))) ######################### 获取各个控件的位置 ########################################## ######################### 测试过程中请不要操作鼠标和键盘 ############################### mouse = PyMouse() key = PyKeyboard() input("Move mouse to 'Tear Down' then press Enter") (IsTearDownX, IsTearDownY) = mouse.position() #获取当前坐标的位置 print(IsTearDownX, IsTearDownY) input("Move mouse to 'Tx Channel' then press Enter") (TxChannelX, TxChannelY) = mouse.position() #获取当前坐标的位置 print(TxChannelX, TxChannelY) input("Move mouse to 'Set Radio Config' then press Enter") (SetRadioConfigX, SetRadioConfigY) = mouse.position() #获取当前坐标的位置 print(SetRadioConfigX, SetRadioConfigY) input("Move mouse to 'RGI' then press Enter") (RGIx, RGIy) = mouse.position() #获取当前坐标的位置 print(RGIx, RGIy) input("Move mouse to 'PA current' then press Enter") (PAcurrentX, PAcurrentY) = mouse.position() #获取当前坐标的位置 print(PAcurrentX, PAcurrentY) input("Move mouse to 'Tx Override' then press Enter") (TxOverrideX, TxOverrideY) = mouse.position() #获取当前坐标的位置 print(TxOverrideX, TxOverrideY) ######################### 获取各个控件的位置 ########################################## ######################### 测试过程中请不要操作鼠标和键盘 ############################### TimeStart = time.clock() print("test start. Please check instrument parameters") interpolateTemp = numpy.zeros([len(RGIlist), 4]) #用来做拟合/插值,便于比较 for ii in range(len(bandChosen)): if ModeChosen == 0: PMwrite(PM, "CONFigure:LTE:MEAS:DMODe FDD") elif ModeChosen == 1: PMwrite(PM, "CONFigure:LTE:MEAS:DMODe TDD") if ModeChosen in [0, 1]: PMwrite(PM, "ROUTe:LTE:MEAS:SCENario:SALone RF1C, RX1") PMwrite(PM, "CONFigure:LTE:MEAS:BAND %s" % bandChosen[ii]) PMwrite( PM, "CONFigure:LTE:MEAS:RFSettings:PCC:FREQuency %dCH" % ChannelList[ii][0]) PMwrite(PM, "CONFigure:LTE:MEAS:MEValuation:REPetition SINGleshot") PMwrite(PM, "CONFigure:LTE:MEAS:MEValuation:MSUBframes 0, 10, 2") PMwrite(PM, "CONFigure:LTE:MEAS:PCC:CBANdwidth %s" % LteBW) PMwrite( PM, "TRIGger:LTE:MEAS:MEValuation:SOURce 'Free Run (Fast Sync)'") PMwrite(PM, "CONFigure:LTE:MEAS:RFSettings:ENPMode MANual") PMwrite(PM, "CONFigure:LTE:MEAS:RFSettings:ENPower 24") PMwrite(PM, "CONFigure:LTE:MEAS:RFSettings:UMARgin 12") PMwrite(PM, "CONFigure:LTE:MEAS:MEValuation:MOEXception ON") elif ModeChosen == 2: PMwrite(PM, "ROUTe:WCDMa:MEAS:SCENario:SALone RF1C, RX1") PMwrite(PM, "CONFigure:WCDMa:MEAS:BAND %s" % bandChosen[ii]) PMwrite( PM, "CONFigure:WCDMa:MEAS:RFSettings:FREQuency %d CH" % ChannelList[ii][0]) PMwrite(PM, "CONFigure:WCDMa:MEAS:MEValuation:REPetition SINGleshot") PMwrite(PM, "CONFigure:WCDMa:MEAS:MEValuation:SCOunt:MODulation 10") PMwrite(PM, "CONFigure:WCDMa:MEAS:MEValuation:SCOunt:SPECtrum 10") PMwrite(PM, "CONFigure:WCDMa:MEAS:MEValuation:MOEXception ON") PMwrite( PM, "TRIGger:WCDMa:MEAS:MEValuation:SOURce 'Free Run (Fast Sync)'") PMwrite(PM, "CONFigure:WCDMA:MEAS:RFSettings:ENPower 24") PMwrite(PM, "CONFigure:WCDMA:MEAS:RFSettings:UMARgin 12") os.system("pause") time.sleep(1) for jj in range(len(ChannelList[ii])): mouse.click(IsTearDownX, IsTearDownY, 1) mouse.click(SetRadioConfigX, SetRadioConfigY, 1) time.sleep(3) mouse.click(IsTearDownX, IsTearDownY, 1) mouse.click(TxChannelX, TxChannelY, 1, 2) key.type_string(str(ChannelList[ii][jj])) mouse.click(SetRadioConfigX, SetRadioConfigY, 1) time.sleep(0.2) if ModeChosen in [0, 1]: PMwrite( PM, "CONFigure:LTE:MEAS:RFSettings:PCC:FREQuency %dCH" % ChannelList[ii][jj]) elif ModeChosen == 2: PMwrite( PM, "CONFigure:WCDMa:MEAS:RFSettings:FREQuency %d CH" % ChannelList[ii][jj]) time.sleep(1) for kk in range(len(PAcurrentList)): mouse.click(PAcurrentX, PAcurrentY, 1, 2) key.type_string(str(PAcurrentList[kk])) time.sleep(0.2) Icqq1 = numpy.floor(PAcurrentList[kk] / 256) Icqq2 = PAcurrentList[kk] - Icqq1 * 256 TestFlag = 1 for ll in range(len(RGIlist)): mouse.click(RGIx, RGIy, 1, 2) key.type_string(str(RGIlist[ll])) time.sleep(0.1) mouse.click(TxOverrideX, TxOverrideY, 1) time.sleep(0.1) try: if ModeChosen in [0, 1]: PM.write("ABORt:LTE:MEAS:MEValuation") PM.write("INIT:LTE:MEAS:MEValuation") time.sleep(0.7) LteAclr = PMquery( PM, "FETCh:LTE:MEAS:MEValuation:ACLR:AVERage?" ) #读取UE发射功率 LteAclrList = list(map(float, LteAclr.split(','))) UEPwr = LteAclrList[4] ChPwr = LteAclrList[4] AdjCLRn = LteAclrList[3] AdjCLRp = LteAclrList[5] elif ModeChosen == 2: PMwrite(PM, "ABORt:WCDMa:MEAS:MEValuation") WAclrList = PMqueryWithDelay( PM, "READ:WCDMa:MEAS:MEValuation:SPECtrum:AVERage?" ).split(',') UEPwr = float(WAclrList[15]) ChPwr = float(WAclrList[1]) AdjCLRn = ChPwr - float(WAclrList[3]) AdjCLRp = ChPwr - float(WAclrList[4]) except Exception: print("TxPwr underdriven or overdriven, ignored") TestFlag = -1 break if (AdjCLRn < 30 and ChPwr < 23): print("ACLR too bad, ignored") TestFlag = 0 break if TestFlag == 1: interpolateTemp[ll][0] = AdjCLRn interpolateTemp[ll][1] = ChPwr interpolateTemp[ll][2] = AdjCLRp if ReadCurrentFlag == 1: if ReadCurrentWaitTime == "Manual": os.system("pause") else: time.sleep(int(ReadCurrentWaitTime)) if ModeChosen == 1: CurrentLength = 40 else: CurrentLength = 15 Current = numpy.zeros(CurrentLength) for k in range(CurrentLength): Current[k] = float( PMquery(PM_DCsupply, "MEASure:CURRent?")) print(Current[k]) time.sleep(0.1 + numpy.random.rand() * 0.3) if ModeChosen == 1: temp_current = sorted(Current) interpolateTemp[ll][3] = average( temp_current[2:(CurrentLength - 2)]) else: interpolateTemp[ll][3] = average(Current) else: interpolateTemp[ll][3] = 0.001 print("%-4s %d %s %s %3d %3d %3.2f %3.2f %3.2f %1.3f" %(bandChosen[ii], ChannelList[ii][jj],\ RGIlist[ll],PAcurrentList[kk],Icqq1, Icqq2, AdjCLRn,ChPwr,AdjCLRp,interpolateTemp[ll][3])) elif TestFlag == -1: print("%-4s %d %s %s %3d %3d underdriven or overdriven, ignored" %(bandChosen[ii], ChannelList[ii][jj],\ RGIlist[ll],PAcurrentList[kk],Icqq1, Icqq2)) else: print("%-4s %d %s %s %3d %3d ACLR too bad, ignored" %(bandChosen[ii], ChannelList[ii][jj],\ RGIlist[ll],PAcurrentList[kk],Icqq1, Icqq2)) if TestFlag == 1: Tmp1 = numpy.polyfit(interpolateTemp[:, 1], interpolateTemp[:, 0], len(RGIlist) - 1) Tmp2 = numpy.polyfit(interpolateTemp[:, 1], interpolateTemp[:, 2], len(RGIlist) - 1) Tmp3 = numpy.polyfit(interpolateTemp[:, 1], interpolateTemp[:, 3], len(RGIlist) - 1) interpolateAclrLeft = numpy.polyval(Tmp1, IpNP) interpolateAclrRight = numpy.polyval(Tmp2, IpNP) interpolateCurrent = numpy.polyval(Tmp3, IpNP) print("%-4s %d -- %s %3d %3d %3.2f %3.1f %3.2f %1.3f" %(bandChosen[ii], ChannelList[ii][jj],\ PAcurrentList[kk],Icqq1, Icqq2, interpolateAclrLeft,IpNP,interpolateAclrRight, interpolateCurrent)) LogfileWrite(LogFile, "%-4s %d -- %s %3d %3d %3.2f %3.1f %3.2f %1.3f\n" %(bandChosen[ii], ChannelList[ii][jj],\ PAcurrentList[kk],Icqq1, Icqq2, interpolateAclrLeft,IpNP,interpolateAclrRight, interpolateCurrent)) elif TestFlag == -1: print("%-4s %d -- %s %3d %3d -- %3.1f --" %(bandChosen[ii], ChannelList[ii][jj],\ PAcurrentList[kk],Icqq1, Icqq2, IpNP)) LogfileWrite(LogFile, "%-4s %d -- %s %3d %3d -- %3.1f --\n" %(bandChosen[ii], ChannelList[ii][jj],\ PAcurrentList[kk],Icqq1, Icqq2, IpNP)) else: print("%-4s %d -- %s %3d %3d bad %3.1f bad" %(bandChosen[ii], ChannelList[ii][jj],\ PAcurrentList[kk],Icqq1, Icqq2, IpNP)) LogfileWrite(LogFile, "%-4s %d -- %s %3d %3d bad %3.1f bad\n" %(bandChosen[ii], ChannelList[ii][jj],\ PAcurrentList[kk],Icqq1, Icqq2, IpNP)) ############################## All test end ########################## TimeEnd = time.clock() print("The total test time is %.1f minutes" % ((TimeEnd - TimeStart) / 60)) endtime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) print("Test finished at %s" % endtime) LogfileWrite(LogFile, "Test finished at %s\n\n" % endtime)
def worker2(): global play global pause global flag m = PyMouse() k = PyKeyboard() print("鼠标移动到软件1文本框 按 ctrl") flag = False while (1): #print(flag) if (flag == True): a = m.position() #获取当前坐标的位置 print(a) flag = False break if (mode == 2 or mode == 3): print("鼠标移动到 复制 按 ctrl") while (1): if (flag == True): d = m.position() #获取当前坐标的位置 print(d) flag = False break print("鼠标移动到软件2文本框 按 ctrl") while (1): if (flag == True): b = m.position() #获取当前坐标的位置 print(b) flag = False break print("鼠标移动到 发送 按 ctrl") while (1): if (flag == True): c = m.position() #获取当前坐标的位置 print(c) flag = False break ti1 = float(input("输入检测延时:")) ti = float(input("输入发送延时:")) s = '' while (1): time.sleep(ti1) if (play == True): m.click(a[0], a[1]) #移动并且在(x,y)位置左击 if (mode != 3): k.press_key(k.control_l_key) #全选 k.tap_key('a') k.release_key(k.control_l_key) if (mode == 1): #键盘复制 k.press_key(k.control_l_key) k.tap_key('c') k.release_key(k.control_l_key) if (mode == 2 or mode == 3): #鼠标复制 m.click(a[0] - 5, a[1], 2) time.sleep(1) m.click(d[0] - 5, d[1]) time.sleep(1) if (pyperclip.paste() != s): #转发 print("延迟%s秒" % ti) time.sleep(ti) s = pyperclip.paste() m.click(b[0], b[1]) k.press_key(k.control_l_key) #粘贴 k.tap_key('v') k.release_key(k.control_l_key) time.sleep(0.5) m.click(c[0], c[1]) #发送 if (play == False): while (1): if (play == True): break
def playGame(mod): guess = True global isEscape, sp, counter1, counter2 driver = webdriver.Chrome( '/home/sidharth/Downloads/ChromeDriver/chromedriver') driver.maximize_window() driver.get('http://www.google.com/') time.sleep(5) outer_width = driver.execute_script("return screen.width") outer_height = driver.execute_script("return screen.height") print(outer_width, outer_height) inner_height = driver.execute_script("return window.innerHeight") inner_width = driver.execute_script("return window.innerWidth") print(inner_width, inner_height) element = driver.find_element_by_xpath( "/html/body/div[1]/div[4]/canvas[1]") location = element.location size = element.size titleBarSize = outer_height - inner_height print(titleBarSize) X1 = location['x'] Y1 = location['y'] + titleBarSize X2 = location['x'] + size['width'] Y2 = location['y'] + size['height'] + titleBarSize print(X1, Y1, X2, Y2) sp = ScreenCapture(X1, Y1, X2, Y2, './imgfolder-debug/') print( "The program will start the game play in 5 seconds, please ALT-TAB to your offline Chrome window" ) time.sleep(15) ## Pressing the UP arrow key to start the T-Rex k = PyKeyboard() k.tap_key(k.up_key) counter3 = 0 ## Now you need to start capturing the images based on which predictions will be made while guess: img = sp.capture() counter3 = sp.saveROIImg("test", img, counter3) imgData = np.array((img.resize( (myNN.img_rows, myNN.img_cols))).convert('L')).flatten() #imgData = np.asarray(img) # r, g, b = cv2.split(imgData) # inputData = cv2.merge([b, g, r]) if myNN.img_channels == 1: #image = cv2.cvtColor(inputData, cv2.COLOR_BGR2GRAY) # Resize as per our need # rimage = cv2.resize(imgData, (myNN.img_rows, myNN.img_cols)) retvalue = myNN.guessAction(mod, imgData) print(str(retvalue) + ' ' + str(counter3)) ## If the NN says that jump is required then send jump command if retvalue == 0: k.tap_key(k.up_key) else: ## Adding a small delay to actual key press - this seemed to work better to coordinate actions ## Though I did have some trouble with some intermediate images #time.sleep(0.35) continue
def __init__(self): self.mouse = PyMouse() self.keyboard = PyKeyboard() self.przyciskPSP2klawiatura = {'up': 'w', 'right': 'd', 'down': 's', 'left': 'a', 'triangle': self.keyboard.enter_key, 'circle': 'f', 'cross': 'g', 'square': 'h', 'l': self.keyboard.control_r_key, 'r': self.keyboard.shift_r_key, 'start': 'k', 'select': 'l'}
def main(): global args, move_list, i_step args = parser.parse_args() #move_list = [x.__name__ for x in movement.__dict__.values() # if inspect.isfunction(x)] #move_list.remove('focus') move_list=[] move_list.append('f_roll') move_list.append('idle') move_list.append('r_roll') move_list.append('l_roll') move_list.append('b_roll') move_list.append('light_atk') move_list.append('drink_estus') m = PyMouse(display=':0') k = PyKeyboard(display=':0') sct = mss(display=':0') env = DarkSoulsEnv(sct=sct, m=m, k=k) if args.pretrain: pass else: args.pretrain=None model1 = DQN(action=len(move_list), variables=3, pretrained=args.pretrain) if use_cuda: model1.cuda() # get the number of model parameters print('Number of model parameters: {}'.format( sum([p.data.nelement() for p in model1.parameters()]))) optimizer = optim.Adam(model1.parameters(), lr=args.lr) #optimizer = optim.RMSprop(model.parameters()) #optimizer = optim.SGD(model.parameters(), lr=args.lr, momentum=0.9) i_step = 0 args.start_episode = 0 if args.resume: if os.path.isfile(args.resume): print("=> loading checkpoint '{}'".format(args.resume)) checkpoint = torch.load(args.resume) args.start_episode = checkpoint['episode'] i_step = checkpoint['step'] args.name = checkpoint['name'] model1.load_state_dict(checkpoint['state_dict']) print("=> loaded checkpoint '{}' (epoch {})" .format(args.resume, checkpoint['episode'])) else: print("=> no checkpoint found at '{}'".format(args.resume)) model2 = copy.deepcopy(model1) train(model=model1, model2=model2, env=env, optimizer=optimizer)
def auto_enroll(driver, course_category): url = "https://www.edx.org/course?subject=" + urllib.parse.quote( course_category, safe='') + "&availability=archived&language=English" driver.get(url) #navigate to the page #scroll down the page to retrive all courses scroll(driver) courses = driver.find_elements_by_class_name("course-link") course_urls = [] # all retreived courses for course in courses: course_url = course.get_attribute("href") course_urls.append(course_url) count = 0 print("Total number of courses: {0}".format(len(course_urls))) file_course_categ = open( course_category + ".txt", "a+") # append a new text to the already existing file or the new file for url in course_urls: print(count) print(url) driver.get(url) #navigate to the page try: time.sleep(1) #link_to_enroll is in the following format: #https://courses.edx.org/register?course_id=course-v1%3AGTx%2BMGT1000%2B1T2018&enrollment_action=enroll&email_opt_in=false link_to_enroll = driver.find_element_by_class_name( "js-enroll-btn ").get_attribute( "href") #btn btn-cta txt-center js-enroll-btn link_to_enroll = link_to_enroll.replace("email_opt_in=true", "email_opt_in=false") print(link_to_enroll) #course_link is needed as an input for crawler #course_link is the following format #https://courses.edx.org/courses/course-v1%3AGTx%2BMGT1000%2B1T2018/course/ course_id = re.search('course_id=(.*)&enrollment_action', link_to_enroll).group(1) course_link = "https://courses.edx.org/courses/" + course_id + "/course/" course_title = driver.find_element_by_class_name( "course-intro-heading").text print(course_title) course_title = clean_filename(course_title) file_course_categ.write('{0:80} {1:40} {2}\n'.format( course_title, course_category, course_link)) # Open URL in a new tab, if a browser window is already open. webbrowser.open(link_to_enroll) time.sleep(10) # To Create an ctrl_key+w combo for Linux keyboard = PyKeyboard() keyboard.press_key(keyboard.control_key) keyboard.tap_key('w') keyboard.release_key(keyboard.control_key) count += 1 except Exception as e: print(e) pass
def __init__(self): self.m = PyMouse() self.k = PyKeyboard()
import cv2 import numpy as np #our libraries import util as ut import svm_train as st import hand_util as hu #other dependencies from pymouse import PyMouse from pykeyboard import PyKeyboard import moosegesture as mges #PyMouse the library to control mouse movements from python m1 = PyMouse() k1 = PyKeyboard() #capturing device cam = int(raw_input("Enter Camera Index : ")) cap = cv2.VideoCapture(cam) #training the svm model = st.trainSVM(3, 40, 'TrainData') #initilizing values thresh = 120 frame_count = 0 color = (0, 0, 255) res = ut.get_screen_res() w_screen = int(res['w']) + 200 h_screen = int(res['h']) + 200
def process_request(self, request, spider): k = PyKeyboard() self.driver.get((request.url)) x = request.url[:] #request.headers["Referer"] = "https://antirobot.tianyancha.com/captcha/verify?return_url=https%3A%2F%2Fwww.tianyancha.com%2Fcompany%" + str(request.url[35:]) + "&rnd=" #print(request.headers["Referer"]) time.sleep(random.random()) try: denglu = self.driver.find_element_by_xpath( '//div[@id="J_TLoginInfoHd"]/a[1]') if not denglu: pass else: denglu.click() time.sleep(random.random()) self.driver.find_element_by_xpath( '//a[@class="forget-pwd J_Quick2Static"]').click() time.sleep(0.3) self.driver.find_element_by_xpath( '//input[@id="TPL_username_1"]').send_keys('15123358380') self.driver.find_element_by_xpath( '//input[@id="TPL_password_1"]').send_keys('a135792468') self.driver.find_element_by_xpath( '//button[@id="J_SubmitStatic"]').click() #win32api.SetCursorPos([random.randint(1160,1170),random.randint(590,595)]) #win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP | win32con.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0) #self.mima() # try: # while True: # huakuai = self.driver.find_element_by_xpath('//*[@id="nc_1_n1z"]') # if not huakuai: # break # else: # x = random.randint(975,1010) # y = random.randint(505, 515) # win32api.SetCursorPos([x, y]) # time.sleep(0.1) # win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0) # sum = x # for i in range(9): # sum += random.randint(30, random.randint(40, 65)) # win32api.SetCursorPos([sum, y]) # 为鼠标焦点设定一个位置 # time.sleep(0.1) # win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, 0, 0, 0, 0) # win32api.SetCursorPos([random.randint(1000, 1200), random.randint(560, 565)]) # win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP | win32con.MOUSEEVENTF_LEFTDOWN, 0, 0, 0,0) # time.sleep(random.random()) # self.driver.refresh() # time.sleep(5) # try: # win32api.SetCursorPos([random.randint(1160, 1170), random.randint(590, 595)]) # win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP | win32con.MOUSEEVENTF_LEFTDOWN, 0, 0,0, 0) # except: # pass # self.mima() # except: # pass time.sleep(10) request.url = x[:] self.driver.get((request.url)) except: pass time.sleep(0.5 + random.random()) str = self.driver.page_source a = 0 month_sell = etree.HTML(str).xpath( '//ul[@class="info-list"]/li[1]/em/text()') while (month_sell == ['-'] or month_sell == []): if request.url == 'https://www.fliggy.com/dujia/?spm=181.11358650.0.0.78d5223eYq1rts': break # self.driver.switch_to.frame('sufei-dialog-content') try: y = random.randint(325, 335) x = random.randint(835, 845) win32api.SetCursorPos([x, y]) time.sleep(0.3 + random.random()) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0) sum = x for i in range(9): sum += random.randint(random.randint(25, 30), random.randint(40, 65)) win32api.SetCursorPos([sum, y]) # 为鼠标焦点设定一个位置 time.sleep(random.random() * 0.1) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, 0, 0, 0, 0) # self.driver.switch_to.default_content() str = self.driver.page_source month_sell = etree.HTML(str).xpath( '//ul[@class="info-list"]/li[1]/em/text()') print(month_sell) if (month_sell == ['-'] or month_sell == []): time.sleep(random.random()) self.driver.refresh() a += 1 time.sleep(random.random()) if (a >= 7): self.cursor.execute(self.sql, (request.url)) self.conn.commit() break except: pass source = self.driver.page_source response = HtmlResponse(url=self.driver.current_url, body=source, request=request, encoding='utf-8') return response
def __init__(self): self.mouse = PyMouse() self.keyboard = PyKeyboard() self.opencv = ImageMathOpenCV(0.8)
def main(): arg = argparse.ArgumentParser() simulate_keyboard = PyKeyboard() arg.add_argument("file_name", action="store", help="spcify a hosts file name which need be resolved") arg.add_argument("-o", action="store", help="intput file name") try: arg_result = arg.parse_args() file_name = arg_result.file_name except argparse.ArgumentError: arg.print_help() simulate_keyboard.tap_key("q") exit(0) except argparse.ArgumentTypeError: arg.print_help() simulate_keyboard.tap_key("q") exit(0) except: arg.print_help() simulate_keyboard.tap_key("q") exit(0) local_time = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime()) out_file_name = f"{local_time}.txt" try: file_open = open(file_name, "r") file_write = open(out_file_name, "a") file_write.write( "%-30s\t%-12s\t%-12s\t%-12s\n" % ("webname", "speed(kB/s)", "trans_time(ms)", "dns_time(ms)")) file_write.close() for host_name in file_open.readlines(): file_write = open(out_file_name, "a") url = host_name.strip('\n') if not url: continue web_init = UrlCheck(url) try: print(url) web_init.resolve() except pycurl.error as err: print(err) if web_init.get_http_code() == 200: connect_time = web_init.get_connect_time() * 1000 download_speed = float(web_init.get_download_speed()) / 1024 transmission_time = web_init.get_transmission_time() * 1000 dns_time = web_init.get_dns_time() * 1000 print("建立连接时间:%.2f ms" % connect_time, end=' ') print("下载速度: %.2f kb/s" % download_speed, end=' ') print("传输时间:%.2f ms" % transmission_time, end=' ') print("dns解析时间:%.2f ms" % dns_time) file_write.write("%-30s\t%-16.6s\t%-16.6s\t%-16.6s\n" % (url, str(download_speed), str(transmission_time), str(dns_time))) file_write.close() else: print("HTTP status code %d" % web_init.get_http_code()) file_write.close() file_open.close() except IOError as err: pass simulate_keyboard = PyKeyboard() simulate_keyboard.tap_key("q")
def __init__(self): self.mouse = PyMouse() self.keyboard = PyKeyboard() self.dr = webdriver.Chrome() self.dr.maximize_window() self.dr.get('http://39.106.93.201/signIn')
def __init__(self): self.m = PyMouse() self.k = PyKeyboard() self.SkillCoordi = UIPrase() self.ScreenWidth = win32api.GetSystemMetrics(0) self.ScreenHeight = win32api.GetSystemMetrics(1)
#imports from Tkinter import * from pykeyboard import PyKeyboard from pymouse import PyMouse import tkFileDialog, tkMessageBox import os import time import ctypes import platform #initialize Objects master = Tk() master.wm_title("pyScraper") kb = PyKeyboard() m = PyMouse() #global Vars readyForMouseInput = False if platform.system() == "Darwin": specialkeys = {"Special Keys":""} else: specialkeys= {"Special Keys":"","Tab":kb.tab_key,"Shift":kb.shift_key,"Enter":kb.enter_key,\ "Ctrl":kb.control_key,"Alt":kb.alt_key, "Del":kb.delete_key,\ "Insert":kb.insert_key,"Esc":kb.escape_key,"F1":kb.function_keys[1],\ "F2":kb.function_keys[2],"F3":kb.function_keys[3],"F4":kb.function_keys[4], "F5":kb.function_keys[5],"F6":kb.function_keys[6],"F7":kb.function_keys[7],\ "F8":kb.function_keys[8],"F9":kb.function_keys[9],"F10":kb.function_keys[10],\ "F11":kb.function_keys[11],"F12":kb.function_keys[12]} specialkeysorder= {"Special Keys":1,"Tab":2,"Shift":3,"Enter":4,\ "Ctrl":5,"Alt":6, "Del":7,\ "Insert":8,"Esc":9,"F1":10,\
def __init__(self): self.mouse = PyMouse() self.keyboard = PyKeyboard() self.match = ImageMatchByOpenCV()
def __init__(self, stream, fig, axes, window, scale, dejitter=True): """Init""" self.stream = stream self.window = window self.scale = scale self.dejitter = dejitter self.inlet = StreamInlet(stream, max_chunklen=buf) self.filt = True self.k = PyKeyboard() self.m = PyMouse() self.xdim, self.ydim = self.m.screen_size() info = self.inlet.info() description = info.desc() self.sfreq = info.nominal_srate() self.n_samples = int(self.sfreq * self.window) self.n_chan = info.channel_count() ch = description.child('channels').first_child() ch_names = [ch.child_value('label')] for i in range(self.n_chan): ch = ch.next_sibling() ch_names.append(ch.child_value('label')) self.ch_names = ch_names fig.canvas.mpl_connect('key_press_event', self.OnKeypress) fig.canvas.mpl_connect('button_press_event', self.onclick) self.fig = fig self.axes = axes sns.despine(left=True) self.data = np.zeros((self.n_samples, self.n_chan)) self.times = np.arange(-self.window, 0, 1. / self.sfreq) impedances = np.std(self.data, axis=0) lines = [] for ii in range(self.n_chan): line, = axes.plot(self.times[::subsample], self.data[::subsample, ii] - ii, lw=1) lines.append(line) self.lines = lines axes.set_ylim(-self.n_chan + 0.5, 0.5) ticks = np.arange(0, -self.n_chan, -1) axes.set_xlabel('Time (s)') axes.set_ylabel('Average Voltage (uV)') axes.xaxis.grid(False) axes.set_yticks(ticks) ticks_labels = [ '%s - %.1f' % (ch_names[ii], impedances[ii]) for ii in range(self.n_chan) ] axes.set_yticklabels(ticks_labels) self.display_every = int(0.2 / (12 / self.sfreq)) self.bf, self.af = butter(4, np.array([1, 40]) / (self.sfreq / 2.), 'bandpass') zi = lfilter_zi(self.bf, self.af) self.filt_state = np.tile(zi, (self.n_chan, 1)).transpose() self.data_f = np.zeros((self.n_samples, self.n_chan))
# 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, see <http://www.gnu.org/licenses/>. import argparse from aubio import pitch, source from math import log from pykeyboard import PyKeyboard import json import os KEYBOARD = PyKeyboard() def applyKeyTap(freq, freq_map, dry_run=False): """ Trigger keyboard taps for any frequencies that have a match in the frequency map. """ if freq in freq_map: key = freq_map[freq] if not dry_run: KEYBOARD.tap_key(key) else: print("Tapping key '{}'".format(key)) def applyGranularityFilter(freq, granularity): """ Apply a granularity filter to a frequency. In order for granularity to make sense, the values needs to grow
#Function for Changing a Key def changeKeyState(key, value, key_name): global keyboard_keys #Change Only Neccessary if value != keyboard_keys[key_name]: if value: keyboard.press_key(key) else: keyboard.release_key(key) keyboard_keys[key_name] = value #Specify Keyboard keyboard = PyKeyboard() #Set Accelerometer Values previous_values = microbit.accelerometer.get_values() #Set Keyboard Keys keyboard_keys = {"L": False, "R": False, "F": False, "S": False} #Set Images stable = microbit.Image("00000:00000:99999:00000:00000") images = { "N": microbit.Image.ARROW_N, "NE": microbit.Image.ARROW_NE, "NW": microbit.Image.ARROW_NW, "E": microbit.Image.ARROW_E, "W": microbit.Image.ARROW_W, "": stable }
sys.exit() global end if (end): sys.exit() return True def main(): while True: # 主程序在这 Do() if __name__ == '__main__': k = PyKeyboard() m = PyMouse() end = False start = False excelUrl = r"C:\Users\Administrator\Desktop\cai\P1-分部分项.xlsx" #to do------------- caiExcelUrl = r"C:\Users\Administrator\Desktop\cai\cai.xlsx" #过滤出的名称和特征 excel = xlrd.open_workbook(excelUrl) caiworkbook = xlrd.open_workbook(caiExcelUrl) rowMaxCount = caiworkbook.sheets()[0].nrows table = excel.sheets()[0] rowCount = table.nrows threads = [] t2 = threading.Thread(target=main, args=())
class UserActivity: k = PyKeyboard() def __init__(self): """ Call pymouse and pykeyboard method Set default click event times 1 Set default Interval time bewteen two times 0 """ self.m = PyMouse() self.k = PyKeyboard() self.click_times = 1 self.sleep_times = 0 @get_func_name def click_tab_key(self, sleep_times, run_times=0, *args): try: if run_times: run = run_times else: run = self.click_times mylogs.log_info('clicking tab key will be executed %d times' % run) for _ in range(0, run): if sleep_times: mylogs.log_info( '****Has interval time for {} seconds****'.format( sleep_times)) sleep(sleep_times) self.k.tap_key(self.k.tab_key) else: mylogs.log_info('****No interval time****') self.k.tap_key(self.k.tab_key) except Exception as e: raise e @get_func_name def click_space_key(self, sleep_times, run_times=0, *args): try: if run_times: run = run_times else: run = self.click_times mylogs.log_info('clicking space key will be executed %d times' % run) for _ in range(0, run): if sleep_times: mylogs.log_info( '****Has interval time for {} seconds****'.format( sleep_times)) sleep(sleep_times) self.k.tap_key(self.k.space) else: mylogs.log_info('****No interval time****') self.k.tap_key(self.k.space) except Exception as e: mylogs.log_error('Error happen while clicking space key') raise e @get_func_name def press_ctrl_keys(self, key_name, sleep_times, run_times=0, *args): """ @ param: key_name - [A-Z] @ param: sleep_times - interval time between last click and next click atction @ param: run_times - press or click times totally """ try: if run_times: run = run_times else: run = self.click_times mylogs.log_info('pressing ctrl key will be executed %d times' % run) for _ in range(0, run): if sleep_times: mylogs.log_info( '****Has interval time for {} seconds****'.format( sleep_times)) sleep(sleep_times) self.k.press_key(self.k.control_key) self.k.tap_key(key_name) self.k.release_key(self.k.control_key) else: mylogs.log_info('****No interval time****') self.k.press_key(self.k.control_key) self.k.tap_key(key_name) self.k.release_key(self.k.control_key) except Exception as e: mylogs.log_error( 'Error happen while press ctrl + {} keys'.format(key_name)) raise e # @staticmethod def click_enter_key(self): """ click enter key from keyboard """ print("Start to press enter key") sleep(2) self.k.tap_key(self.k.enter_key) sleep(1) print("press enter key second time") self.k.tap_key(self.k.enter_key) def click_esc_key(self): pass @staticmethod @get_func_name def test_decorator(): mylogs.log_info('test decorator') # @staticmethod def click_connect_btn(self): mylogs.log_info('****Start to click connect button****') try: self.click_tab_key(1, 2) sleep(2) self.click_space_key(1, 1) # sleep(1) # self.click_tab_key(1,1) # self.click_space_key(1,1) except Exception as e: mylogs.log_error('Error occurs due to {}'.format(e)) raise e def close_all_terminals(self): mylogs.log_info('****Start to close all terminals****') try: self.press_ctrl_keys('d', 1) # close ota monitor terminal sleep(1) self.press_ctrl_keys('c', 1) # close esync client terminal sleep(1) self.press_ctrl_keys('c', 1) # close uds server terminal sleep(1) self.press_ctrl_keys('d', 1) sleep(1) self.press_ctrl_keys('d', 1) # close setup dm tree terminal mylogs.log_info( 'Close all terminal include uds and esync and monitor') except Exception as e: mylogs.log_error('Error occur due to {}'.format(e)) raise e def click_download_and_install_btn(self): """ step1: click download button step2: click install button """ mylogs.log_info('****Start to click download button****') self.m.click(250, 500, 1) sleep(2) mylogs.log_info('****Start to click installation button****') self.m.click(600, 500, 1) def click_close_btn(self): """ close ota monitor hmi window """ mylogs.log_info('****Start to click close button****') try: self.m.click(745, 65, 1) except Exception as e: mylogs.log_error('Error occur due to {}'.format(e)) raise e else: pass finally: pass def take_screen_shot(self): try: os.system('gnome-screenshot -wb') mylogs.log_info('****Get screen_shot****') except Exception as e: mylogs.log_error( "Error happen while taking screen_shot due to {}".format(e))
def __init__(self): self.k = PyKeyboard()
def command(com, args, tw_user=None): global e if (e.is_set()): # System Tray Icon exit must trigger this exit(0) if not com or not isinstance(com, str): return False original_com = com global inactive global user_full_name global user_prefix global config_file userin.twitter_user = tw_user com = com.upper() com = re.sub(r'([^\s\w]|_)+', '', com).strip() print("You: " + com) if inactive and com not in ("DRAGONFIRE", "DRAGON FIRE", "WAKE UP", "HEY"): return True if USER_ANSWERING['status']: if com.startswith("FIRST") or com.startswith( "THE FIRST") or com.startswith("SECOND") or com.startswith( "THE SECOND") or com.startswith( "THIRD") or com.startswith("THE THIRD"): USER_ANSWERING['status'] = False selection = None if com.startswith("FIRST") or com.startswith("THE FIRST"): selection = 0 elif com.startswith("SECOND") or com.startswith("THE SECOND"): selection = 1 elif com.startswith("THIRD") or com.startswith("THE THIRD"): selection = 2 if USER_ANSWERING['for'] == 'wikipedia': with nostderr(): search_query = USER_ANSWERING['options'][selection] try: wikiresult = wikipedia.search(search_query) if len(wikiresult) == 0: userin.say( "Sorry, " + user_prefix + ". But I couldn't find anything about " + search_query + " in Wikipedia.") return True wikipage = wikipedia.page(wikiresult[0]) wikicontent = "".join([ i if ord(i) < 128 else ' ' for i in wikipage.content ]) wikicontent = re.sub(r'\([^)]*\)', '', wikicontent) userin.define_and_execute( ["sensible-browser", wikipage.url], search_query) userin.say(wikicontent) return True except requests.exceptions.ConnectionError: userin.define_and_execute( [" "], "Wikipedia connection error.") userin.say( "Sorry, " + user_prefix + ". But I'm unable to connect to Wikipedia servers." ) return True except Exception: return True if com in ("DRAGONFIRE", "DRAGON FIRE", "WAKE UP", "HEY"): tts_kill() inactive = False userin.define([" "], " ") userin.say( choice([ "Yes, " + user_prefix + ".", "Yes. I'm waiting.", "What is your order?", "Ready for the orders!", user_prefix + ", tell me your wish." ])) elif "GO TO SLEEP" == com: tts_kill() inactive = True userin.define_and_execute([ "echo" ], "Dragonfire deactivated. To reactivate say 'Dragonfire!' or 'Wake Up!'" ) userin.say("I'm going to sleep") elif com in ("ENOUGH", "SHUT UP"): print("Dragonfire quiets.") tts_kill() elif VirtualAssistant.exact_match(com): return True # the request has been handled elif VirtualAssistant.in_match(com): return True # the request has been handled elif ("SEARCH" in com or "FIND" in com) and VirtualAssistant.search_command(com): pass # the request has been handled elif com in ("MY TITLE IS LADY", "I'M A LADY", "I'M A WOMAN", "I'M A GIRL"): tts_kill() config_file.update({'gender': 'female'}, Query().datatype == 'gender') user_prefix = "My Lady" userin.define([" "], " ") userin.say("Pardon, " + user_prefix + ".") elif com in ("MY TITLE IS SIR", "I'M A MAN", "I'M A BOY"): tts_kill() config_file.update({'gender': 'male'}, Query().datatype == 'gender') user_prefix = "Sir" userin.define([" "], " ") userin.say("Pardon, " + user_prefix + ".") elif com.startswith("CALL ME "): tts_kill() callme_config = config_file.search(Query().datatype == 'callme') if callme_config: config_file.update({'title': original_com[8:].lower()}, Query().datatype == 'callme') else: config_file.insert({ 'datatype': 'callme', 'title': original_com[8:].lower() }) user_prefix = original_com[8:].lower().encode("utf8") userin.define([" "], " ") userin.say("Pardon, " + user_prefix + ".") # only for The United States today but prepared for all countries. Also # only for celsius degrees today. --> by Radan Liska :-) elif "WHAT" in com and "TEMPERATURE" in com: tts_kill() capture = re.search( "(?:WHAT IS|WHAT'S) THE TEMPERATURE (?:IN|ON|AT|OF)? (?P<city>.*)", com) if capture: city = capture.group('city') owm = pyowm.OWM("16d66c84e82424f0f8e62c3e3b27b574") reg = owm.city_id_registry() weather = owm.weather_at_id( reg.ids_for(city)[0][0]).get_weather() fmt = "The temperature in {} is {} degrees celsius" msg = fmt.format(city, weather.get_temperature('celsius')['temp']) userin.define_and_execute([" "], msg) userin.say(msg) elif "FILE MANAGER" in com or "OPEN FILES" == com: tts_kill() userin.define_and_execute(["dolphin"], "File Manager") # KDE neon userin.define_and_execute(["pantheon-files"], "File Manager") # elementary OS userin.define_and_execute(["nautilus", "--browser"], "File Manager") # Ubuntu userin.say("File Manager") elif "OPEN CAMERA" == com: tts_kill() userin.define_and_execute(["kamoso"], "Camera") # KDE neon userin.define_and_execute(["snap-photobooth"], "Camera") # elementary OS userin.define_and_execute(["cheese"], "Camera") # Ubuntu userin.say("Camera") elif "OPEN CALENDAR" == com: tts_kill() userin.define_and_execute(["korganizer"], "Calendar") # KDE neon userin.define_and_execute(["maya-calendar"], "Calendar") # elementary OS userin.define_and_execute(["orage"], "Calendar") # Ubuntu userin.say("Calendar") elif "OPEN CALCULATOR" == com: tts_kill() userin.define_and_execute(["kcalc"], "Calculator") # KDE neon userin.define_and_execute(["pantheon-calculator"], "Calculator") # elementary OS userin.define_and_execute(["gnome-calculator"], "Calculator") # Ubuntu userin.say("Calculator") elif "SOFTWARE CENTER" in com: tts_kill() userin.define_and_execute(["plasma-discover"], "Software Center") # KDE neon userin.define_and_execute( ["software-center"], "Software Center") # elementary OS & Ubuntu userin.say("Software Center") elif com.startswith("KEYBOARD "): tts_kill() with nostdout(): with nostderr(): k = PyKeyboard() for character in original_com[9:]: k.tap_key(character) k.tap_key(" ") elif com == "ENTER": tts_kill() with nostdout(): with nostderr(): k = PyKeyboard() k.tap_key(k.enter_key) elif com == "NEW TAB": tts_kill() with nostdout(): with nostderr(): k = PyKeyboard() k.press_keys([k.control_l_key, 't']) elif com == "SWITCH TAB": tts_kill() with nostdout(): with nostderr(): k = PyKeyboard() k.press_keys([k.control_l_key, k.tab_key]) elif com in ("CLOSE", "ESCAPE"): tts_kill() with nostdout(): with nostderr(): k = PyKeyboard() k.press_keys([k.control_l_key, 'w']) k.tap_key(k.escape_key) elif com == "GO BACK": tts_kill() with nostdout(): with nostderr(): k = PyKeyboard() k.press_keys([k.alt_l_key, k.left_key]) elif com == "GO FORWARD": tts_kill() with nostdout(): with nostderr(): k = PyKeyboard() k.press_keys([k.alt_l_key, k.right_key]) elif com == "SCROLL LEFT": tts_kill() with nostdout(): with nostderr(): m = PyMouse() m.scroll(0, -5) elif com == "SCROLL RIGHT": tts_kill() with nostdout(): with nostderr(): m = PyMouse() m.scroll(0, 5) elif com == "SCROLL UP": tts_kill() with nostdout(): with nostderr(): m = PyMouse() m.scroll(5, 0) elif com == "SCROLL DOWN": tts_kill() with nostdout(): with nostderr(): m = PyMouse() m.scroll(-5, 0) elif com in ("PLAY", "PAUSE", "SPACEBAR"): tts_kill() with nostdout(): with nostderr(): k = PyKeyboard() k.tap_key(" ") elif "SHUTDOWN THE COMPUTER" == com: tts_kill() userin.define(["sudo", "poweroff"], "Shutting down") userin.say("Shutting down") userin.execute(3) elif com in ("GOODBYE", "GOOD BYE", "BYE BYE", "SEE YOU LATER", "CATCH YOU LATER"): tts_kill() userin.define([" "], " ") userin.say("Goodbye, " + user_prefix) # raise KeyboardInterrupt thread.interrupt_main() elif "WIKIPEDIA" in com and ("SEARCH" in com or "FIND" in com): tts_kill() with nostderr(): capture = re.search( "(?:SEARCH|FIND) (?P<query>.*) (?:IN|ON|AT|USING)? WIKIPEDIA", com) if capture: search_query = capture.group('query') try: wikiresult = wikipedia.search(search_query) if len(wikiresult) == 0: userin.say( "Sorry, " + user_prefix + ". But I couldn't find anything about " + search_query + " in Wikipedia.") return True wikipage = wikipedia.page(wikiresult[0]) wikicontent = "".join([ i if ord(i) < 128 else ' ' for i in wikipage.content ]) wikicontent = re.sub(r'\([^)]*\)', '', wikicontent) userin.define_and_execute( ["sensible-browser", wikipage.url], search_query) userin.say(wikicontent) except requests.exceptions.ConnectionError: userin.define_and_execute( [" "], "Wikipedia connection error.") userin.say( "Sorry, " + user_prefix + ". But I'm unable to connect to Wikipedia servers." ) except wikipedia.exceptions.DisambiguationError as disambiguation: USER_ANSWERING['status'] = True USER_ANSWERING['for'] = 'wikipedia' USER_ANSWERING['reason'] = 'disambiguation' USER_ANSWERING['options'] = disambiguation.options[:3] notify = "Wikipedia disambiguation. Which one of these you meant?:\n - " + \ disambiguation.options[0] message = user_prefix + ", there is a disambiguation. Which one of these you meant? " + \ disambiguation.options[0] for option in disambiguation.options[1:3]: message += ", or " + option notify += "\n - " + option notify += '\nSay, for example: "THE FIRST ONE" to choose.' userin.define_and_execute([" "], notify) userin.say(message) except BaseException: pass elif "YOUTUBE" in com and ("SEARCH" in com or "FIND" in com): tts_kill() with nostdout(): with nostderr(): capture = re.search( "(?:SEARCH|FIND) (?P<query>.*) (?:IN|ON|AT|USING)? YOUTUBE", com) if capture: search_query = capture.group('query') info = youtube_dl.YoutubeDL({}).extract_info( 'ytsearch:' + search_query, download=False, ie_key='YoutubeSearch') if len(info['entries']) > 0: youtube_title = info['entries'][0]['title'] youtube_url = "https://www.youtube.com/watch?v=%s" % ( info['entries'][0]['id']) userin.define(["sensible-browser", youtube_url], youtube_title) youtube_title = "".join([ i if ord(i) < 128 else ' ' for i in youtube_title ]) else: youtube_title = "No video found, " + user_prefix + "." userin.define(" ", " ") userin.execute(0) userin.say(youtube_title) time.sleep(5) k = PyKeyboard() k.tap_key(k.tab_key) k.tap_key(k.tab_key) k.tap_key(k.tab_key) k.tap_key(k.tab_key) k.tap_key('f') elif ("GOOGLE" in com or "WEB" in com) and "IMAGE" not in com and ("SEARCH" in com or "FIND" in com): tts_kill() with nostdout(): with nostderr(): capture = re.search( "(?:SEARCH|FIND) (?P<query>.*) (?:IN|ON|AT|USING)? (?:GOOGLE|WEB)?", com) if capture: search_query = capture.group('query') tab_url = "http://google.com/?#q=" + search_query userin.define_and_execute( ["sensible-browser", tab_url], search_query) userin.say(search_query) elif ("GOOGLE" in com or "WEB" in com) and "IMAGE" in com and ("SEARCH" in com or "FIND" in com): tts_kill() with nostdout(): with nostderr(): capture = re.search( "(?:SEARCH IMAGES OF|FIND IMAGES OF|SEARCH|FIND) " "(?P<query>.*) (?:IN|ON|AT|USING)? " "(?:GOOGLE|WEB|GOOGLE IMAGES|WEB IMAGES)?", com) if capture: search_query = capture.group('query') tab_url = "http://google.com/?#q=" + search_query + "&tbm=isch" userin.define(["sensible-browser", tab_url], search_query) userin.execute(0) userin.say(search_query) else: tts_kill() arithmetic_response = arithmeticParser(com) if arithmetic_response: userin.define([" "], " ") userin.say(arithmetic_response) else: learn_response = learn_.respond(original_com) if learn_response: userin.define([" "], " ") userin.say(learn_response) else: if not omniscient_.respond(original_com, not args["silent"], userin, user_prefix, args["twitter"]): dc_response = dc.respond(original_com, user_prefix) if dc_response: userin.define([" "], " ") userin.say(dc_response)