def main(call_api): try: # start logging logging.basicConfig(filename='SprinklrClient.log', level=logging.NOTSET) logging.debug("Starting " + sys.argv[0] + " with " + str(len(sys.argv) - 1) + " actual parameters") #load settings settings = EasySettings("Sprinklr.conf") key = settings.get('key') path = settings.get('path') access_token = settings.get('access_token') if len(path) == 0: path = None # If using a differnent enviornment other that Prod, set path to that value (like 'prod2') client = sc.SprinklrClient(key=key, access_token=access_token, path=path) # make API Call - use process_response (defined in resultprocessor) to display results call_api(client) except Exception as ex: print("Error:" + str(ex))
class ClickBot: def check_for_mouseclick(self): self.config = EasySettings('config.conf') self.key_click_delay = self.config.get("key_click_delay") self.single_click_delay = self.config.get("single_click_delay") state_left = win32api.GetKeyState( 0x01) # Left button down = 0 or 1. Button up = -127 or -128 print(state_left) if state_left != self.old_state_left: self.old_state_left = state_left time.sleep(self.single_click_delay ) # delay to avoid double click on single click state_left = -1 # empty value to avoid unintentional click if state_left == -128 or state_left == -127: # print(shoot_shortcut_key_for_Simulator) try: keyboardSimulator.press(shoot_shortcut_key_for_Simulator) time.sleep(self.key_click_delay) keyboardSimulator.release(shoot_shortcut_key_for_Simulator) time.sleep(self.key_click_delay) except Exception as e: updateMessageBox("Key Not Supported!") print("Key Not Supported " + " ERROR --------->" + str(e)) def bot_loop(self): try: self.old_state_left = win32api.GetKeyState( 0x01) # Left button down = 0 or 1. Button up = -127 or -128 except Exception as e: print( "---------------------------\nError: %s\n---------------------------\n" % str(e)) while 1: try: time.sleep( 0.001) # added small delay to give time to processor if bot_active: if work_on_games_with_hidden_mouse_only: if win32gui.GetCursorInfo( )[0] == win32gui.GetCursorInfo()[1] == 0: # print("Game Active") self.check_for_mouseclick() else: self.check_for_mouseclick() except Exception as e: print( "---------------------------\nError: %s\n---------------------------\n" % str(e))
from easysettings import EasySettings from chronologicon.strings import * LOGS_FILENAME = 'logs.json' STATS_FILENAME = 'stat.json' PRESAVE_FILENAME = 'temp.json' LOGS_DEFAULT = [] CUR_FILEPATH = os.path.dirname(__file__) PREFS = EasySettings(os.path.join(CUR_FILEPATH, 'prefs.conf')) # Logs version check try: LOGS = '' with open(os.path.join(PREFS.get('SAVE_DIR'), LOGS_FILENAME), "r") as LOGS_FILE: LOGS = json.load(LOGS_FILE) if type(LOGS[0]['TIME_START']) is int: Message('initLogsOutdated') input.MigrateLogs() except Exception as e: Message('initVersionCheckFailed', e) # Check any mission-critical files and create missing ones. def Preflights(): global PREFS # Check save directory
EXTRACT_HEADER = r'{}\img\extract_header.png'.format(abs_path) CONVERT_HEADER = r'{}\img\to_pdf_header.tif'.format(abs_path) P_COLOR = "#1481CE" S_COLOR = "#F67E6A" STOP = False CANVAS_W = 147 CANVAS_H = 200 FONT = "Calibre" FONT_SM = ('Segoe UI', 9, 'normal') FONT_MD = ("Calibre", 9, 'normal') SIDBAR_BG = "#F2F2F2" settings = EasySettings('config.conf') DIR = settings.get('DIR') if not DIR: #for direction left to right lang, _ = locale.getdefaultlocale() if lang.startswith('ar_'): DIR = 'rtl' else: DIR = 'ltr' if DIR == 'rtl': START_DIR = 'right' END_DIR = 'left' NW = 'se' TK_E = 'nw' END_PADDING_10 = (10, 0) START_PADDING_24 = (12, 24) START_PADDING_24_0 = (24, 0)
from telethon import TelegramClient, events #from telethon import sync from telethon.tl.functions.channels import CreateChannelRequest, CheckUsernameRequest, UpdateUsernameRequest from telethon.tl.functions.messages import ExportChatInviteRequest from config import API_HASH, API_ID from easysettings import EasySettings import logging logging.basicConfig(format='[%(levelname) 5s/%(asctime)s] %(name)s: %(message)s', level=logging.WARNING) settings = EasySettings("configuration.conf") config_channel = None source_channel = None recepients = settings.get("recepients") wait_for_source_forward = False if not recepients: recepients = [] async def init_config_channel(): try: invite = settings.get("config_channel") config_channel = await client.get_entity(invite) if config_channel: return config_channel except: pass print("Config channel not found creating new one") channel = await client(CreateChannelRequest("config_channel", "Message retranslation control room", megagroup=False))
class MxTool: def __init__(self, server, user, token): self.matrix_server = server self.matrix_user = user self.access_token = token self.quit = False self.settings = EasySettings("matrixtool.conf") async def run_tool(self): if not self.matrix_user: # Not read from env, try settings.. self.access_token = self.settings.get('MATRIX_ACCESS_TOKEN') self.matrix_server = self.settings.get('MATRIX_SERVER') self.matrix_user = self.settings.get('MATRIX_USER') if self.access_token: print('\nUsing access token to authenticate..') self.client = AsyncClient(self.matrix_server, self.matrix_user) self.client.access_token = self.access_token while not self.access_token: print('\nLogin to your matrix account\n') answers = prompt(login_questions) self.matrix_server = answers['server'] self.matrix_user = answers['user'] self.client = AsyncClient(self.matrix_server, self.matrix_user) print('\nLogging in..') res = await self.client.login(answers['password']) if type(res) == LoginResponse: self.access_token = self.client.access_token self.settings.set('MATRIX_USER', self.matrix_user) self.settings.set('MATRIX_SERVER', self.matrix_server) self.settings.set('MATRIX_ACCESS_TOKEN', self.access_token) self.settings.save() else: print(res) while not self.quit: await self.client.sync() print('\nWelcome, ', self.matrix_user, '\n\n') answers = prompt(tool_select) if 'tool' in answers: if (answers['tool'] == 'quit'): self.quit = True if (answers['tool'] == 'plumb ircnet'): await self.plumb_ircnet() if (answers['tool'] == 'leave rooms'): await self.leave_rooms() if (answers['tool'] == 'irc channel tools'): await self.irc_channel_tools() await self.close() async def close(self): await self.client.close() async def wait_until_user_joined(self, user, room): while True: await self.client.sync() for croomid in self.client.rooms: if croomid == room: print('Checking if', user, 'is in', room) roomobj = self.client.rooms[croomid] for roomuser in roomobj.users: if roomuser == user: print('Yes!') return async def plumb_ircnet(self): answers = prompt(plumb_questions) channel = answers['channel'] opnick = answers['opnick'] room_select[0]['choices'] = [] network = irc_networks[0] for croomid in self.client.rooms: roomobj = self.client.rooms[croomid] choice = {'value': croomid, 'name': roomobj.display_name} room_select[0]['choices'].append(choice) print('Choose a room to plumb:\n') answers = prompt(room_select) plumbroom = answers['room'] bot = network['bot'] print('Inviting', bot, 'to', plumbroom) rir = await self.client.room_invite(plumbroom, bot) if type(rir) != RoomInviteResponse: print( 'Room invite seemed to fail - press ctrl-c to abort if you want to do so now: ', rir) input("Press Enter to continue...") await self.wait_until_user_joined(bot, plumbroom) print('Bot joined, please give it PL100 in the Matrix room') input("Press Enter to continue...") # self.client.room_put_state(plumbroom, ) # TODO: figure out how to set PL url = network['provision_url'] post_data = { "remote_room_server": network['server'], "remote_room_channel": channel, "matrix_room_id": plumbroom, "op_nick": opnick, "user_id": self.matrix_user } headers = {'content-type': 'application/json'} print('POST', json.dumps(post_data)) res = requests.post(url, data=json.dumps(post_data), headers=headers) if res.status_code != 200: print('Plumbing failed:', res.text) else: print('Almost finished! IRC user', opnick, 'must now reply to the bot to finish plumbing.') input("Press Enter") async def leave_rooms(self): leave_questions[0]['choices'] = [] for croomid in self.client.rooms: roomobj = self.client.rooms[croomid] choice = {'value': croomid, 'name': roomobj.display_name} leave_questions[0]['choices'].append(choice) answers = prompt(leave_questions) for roomid in answers['rooms']: roomname = self.client.rooms[roomid].display_name print('Leaving room', roomname, '..') rlr = await self.client.room_leave(roomid) if type(rlr) != RoomLeaveResponse: print(rlr) print( '\nNote: due to bug #46 in nio library, the rooms do not appear to be left until you restart the tool.\n' ) def pick_room(self): room_select[0]['choices'] = [] for croomid in self.client.rooms: roomobj = self.client.rooms[croomid] choice = {'value': croomid, 'name': roomobj.display_name} room_select[0]['choices'].append(choice) answer = prompt(room_select) return answer['room'], self.client.rooms[answer['room']] async def irc_channel_tools(self): network = irc_networks[0] # Hardcoded .. botroomid = self.find_chat_with(network['bot']) if not botroomid: print('Please start chat with', network['bot'], 'first!') return roomid, roomobj = self.pick_room() print('Chose room', roomobj.display_name) if not self.user_is_in_room(network['bot'], roomid): print(network['bot'], 'is not in this room - is it really a IRC room?') return print('Bot room:', botroomid, self.client.rooms[botroomid].display_name, network['name']) print('TODO: Figure out how to read this automatrically.\n') ircchannel = input( 'Enter IRC channel name of this room (example: #example): ') if len(ircchannel) == 0: return answer = prompt(irc_channel_tool_select) if (answer['tool'] == 'main menu'): return if (answer['tool'] == 'op' or answer['tool'] == 'deop'): users = self.select_users_in_room(roomobj) for user in users: res = re.compile(network['mxid2nick']).search(user) if res: nick = res.group(1) if len(nick) > 0: print('Opping', user, '..') cmd = f'!cmd MODE {ircchannel} +o {nick}' if answer['tool'] == 'deop': cmd = f'!cmd MODE {ircchannel} -o {nick}' print(cmd) await self.send_text(botroomid, cmd) else: print('Cannot figure out irc nick for', user) def find_chat_with(self, mxid): for croomid in self.client.rooms: roomobj = self.client.rooms[croomid] if len(roomobj.users) == 2: for user in roomobj.users: if user == mxid: return croomid return None def user_is_in_room(self, mxid, roomid): roomobj = self.client.rooms[roomid] for user in roomobj.users: if user == mxid: return True return False def select_users_in_room(self, roomobj): users_select[0]['choices'] = [] for user in roomobj.users: choice = {'value': user, 'name': roomobj.user_name(user)} users_select[0]['choices'].append(choice) answers = prompt(users_select) return answers['users'] async def send_text(self, roomid, body): msg = { "body": body, "msgtype": "m.text", } await self.client.room_send(roomid, 'm.room.message', msg)
class MainWindow(QtWidgets.QWidget): def __init__(self, queue, *args, **kwargs): super(MainWindow, self).__init__(*args, **kwargs) self.setWindowFlags(QtCore.Qt.FramelessWindowHint) self.setWindowTitle(appname) self.shortcutName = appname self.appIcon = QtGui.QIcon(os.path.join(working_directory, 'icon.ico')) self.setWindowIcon(self.appIcon) self.setFixedSize(550, 300) self.center() self.queue = queue self.config = EasySettings('config.conf') self.layout = QVBoxLayout() self.layout.setContentsMargins(0, 0, 0, 0) self.titleLayout = QHBoxLayout() self.titleLayout.setContentsMargins(0, 0, 0, 0) self.title = QLabel(appname) self.title.setFixedSize(200, 20) self.title.setAlignment(QtCore.Qt.AlignCenter) self.title.setObjectName("windowTitle") self.btn_close = QPushButton("x") self.btn_close.clicked.connect(self.close_window) self.btn_close.setFixedSize(25, 20) self.btn_close.setObjectName("closeBtn") self.btn_close.setFocusPolicy(QtCore.Qt.NoFocus) self.btn_closeLay = QVBoxLayout() self.btn_closeLay.addWidget(self.btn_close) self.btn_closeLay.addStretch(1) self.btn_minimise = QPushButton("-") self.btn_minimise.clicked.connect(self.btn_minimise_clicked) self.btn_minimise.setFixedSize(25, 20) self.btn_minimise.setObjectName("minimiseBtn") self.btn_minimise.setFocusPolicy(QtCore.Qt.NoFocus) self.btn_minimiseLay = QVBoxLayout() self.btn_minimiseLay.addWidget(self.btn_minimise) self.btn_minimiseLay.addStretch(1) self.infoBtn = QPushButton('?') self.infoBtn.setObjectName('infoBtn') self.infoBtn.setFocusPolicy(QtCore.Qt.NoFocus) self.infoBtn.clicked.connect(self.openInfoWebpage) self.infoBtnLay = QVBoxLayout() self.infoBtnLay.addWidget(self.infoBtn) self.titleLayout.addLayout(self.btn_closeLay) self.titleLayout.addStretch(1) self.titleLayout.addWidget(self.title) self.titleLayout.addSpacing(-43) self.titleLayout.addLayout(self.infoBtnLay) self.titleLayout.addSpacing(43) self.titleLayout.addStretch(1) self.titleLayout.addLayout(self.btn_minimiseLay) # -------------------------------------------------------------------------------------------------------------- global onoffLabel onoffLabel = QLabel("OFF") onoffLabel.setObjectName("onoffLabel") onoffLabel.setFixedWidth(65) onoffLabel.setAlignment(QtCore.Qt.AlignCenter) self.currentOnOffShortcutLabel = QLabel("On/Off Keyboard Shortcut") self.currentOnOffShortcutLabel.setObjectName("currentShortcutLabel") self.currentOnOffShortcutLabel.setFixedWidth(200) self.currentOnOffShortcutLabel.setToolTip( "Note: The shortcut does not support combinations!") self.currentOnOffShortcutLabel.setToolTipDuration(4000) global currentOnOffShortcutKeyLabel with open( os.path.join(working_directory, 'shortcutRegisters', 'OnOff_Shortcut_Key.txt'), 'r') as file: on_off_shortcut_key_name = file.readlines()[1] currentOnOffShortcutKeyLabel = QLabel(on_off_shortcut_key_name) currentOnOffShortcutKeyLabel.setObjectName("currentShortcutKeyLabel") currentOnOffShortcutKeyLabel.setAlignment(QtCore.Qt.AlignCenter) currentOnOffShortcutKeyLabel.setFixedWidth(140) global recordOnOffShortcut recordOnOffShortcut = QPushButton("Record New") recordOnOffShortcut.setObjectName("recordOnOffshortcutButton") recordOnOffShortcut.pressed.connect(self.disableBotWhileRecording) recordOnOffShortcut.released.connect(self.set_OnOff_shortcut_key) recordOnOffShortcut.setFixedSize(80, 26) recordOnOffShortcut.setStyleSheet( "QPushButton#recordOnOffshortcutButton{color: white; border: 1px solid grey;}QPushButton#recordOnOffshortcutButton:hover{border: 1px solid khaki;color: grey;}" ) recordOnOffShortcut.setFocusPolicy(QtCore.Qt.NoFocus) self.onoffLay = QHBoxLayout() self.onoffLay.addSpacing(10) self.onoffLay.addWidget(onoffLabel) self.onoffLay.addSpacing(5) self.onoffLay.addWidget(self.currentOnOffShortcutLabel) self.onoffLay.addWidget(currentOnOffShortcutKeyLabel) self.onoffLay.addStretch(1) self.onoffLay.addWidget(recordOnOffShortcut) self.onoffLay.addSpacing(30) # -------------------------------------------------------------------------------------------------------------- # -------------------------------------------------------------------------------------------------------------- global onoffButton onoffButton = OnOffslideButton(self, 0) onoffButton.setObjectName("onoffSlideButton") self.currentShootShortcutLabel = QLabel("Game Shoot Keybind") self.currentShootShortcutLabel.setObjectName("currentShortcutLabel") self.currentShootShortcutLabel.setFixedWidth(200) self.currentShootShortcutLabel.setAlignment(QtCore.Qt.AlignCenter) global currentShootShortcutKeyLabel with open( os.path.join(working_directory, 'shortcutRegisters', 'Game_Shoot_Shortcut_Key.txt'), 'r') as file: shoot_shortcut_key_name = file.readlines()[1] currentShootShortcutKeyLabel = QLabel(shoot_shortcut_key_name) currentShootShortcutKeyLabel.setObjectName("currentShortcutKeyLabel") currentShootShortcutKeyLabel.setAlignment(QtCore.Qt.AlignCenter) currentShootShortcutKeyLabel.setFixedWidth(140) global recordShootShortcut recordShootShortcut = QPushButton("Record New") recordShootShortcut.setObjectName("recordShootshortcutButton") recordShootShortcut.pressed.connect(self.disableBotWhileRecording) recordShootShortcut.released.connect(self.set_Shoot_shortcut_key) recordShootShortcut.setFixedSize(80, 26) recordShootShortcut.setStyleSheet( "QPushButton#recordShootshortcutButton{color: white; border: 1px solid grey;}QPushButton#recordShootshortcutButton:hover{border: 1px solid khaki;color: grey;}" ) recordShootShortcut.setFocusPolicy(QtCore.Qt.NoFocus) self.keybindLay = QHBoxLayout() self.keybindLay.addSpacing(10) self.keybindLay.addWidget(onoffButton) self.keybindLay.addSpacing(50) self.keybindLay.addWidget(self.currentShootShortcutLabel) self.keybindLay.addWidget(currentShootShortcutKeyLabel) self.keybindLay.addStretch(1) self.keybindLay.addWidget(recordShootShortcut) self.keybindLay.addSpacing(30) # -------------------------------------------------------------------------------------------------------------- global messageBox messageBox = QLabel() messageBox.setObjectName('messageBoxLabel') self.messageBoxLay = QHBoxLayout() self.messageBoxLay.addSpacing(20) self.messageBoxLay.addWidget(messageBox) # -------------------------------------------------------------------------------------------------------------- self.startOnStartupCheckBox = QCheckBox("Start On Boot") self.startOnStartupCheckBox.clicked.connect(self.setStartOnStartup) self.startOnStartupCheckBox.setObjectName("checkboxes") self.startOnStartupCheckBox.setChecked(self.config.get('startOnBoot')) self.startOnStartupCheckBox.setFocusPolicy(QtCore.Qt.NoFocus) self.startActiveCheckBox = QCheckBox("Start Active") self.startActiveCheckBox.clicked.connect(self.setStartActive) self.startActiveCheckBox.setObjectName("checkboxes") self.startActiveCheckBox.setChecked(self.config.get('startActive')) self.startActiveCheckBox.setFocusPolicy(QtCore.Qt.NoFocus) self.overlayCheckBox = QCheckBox("Show Overlay") self.overlayCheckBox.clicked.connect(self.setShowOverlay) self.overlayCheckBox.setObjectName("checkboxes") self.overlayCheckBox.setChecked(self.config.get('showOverlay')) self.overlayCheckBox.setFocusPolicy(QtCore.Qt.NoFocus) self.gamesOnlyCheckBox = QCheckBox("Active InGame Only") self.gamesOnlyCheckBox.clicked.connect(self.setGamesOnly) self.gamesOnlyCheckBox.setToolTip( "If checked, bot works only in games (when the mouse icon is hidden)." ) self.gamesOnlyCheckBox.setToolTipDuration(4000) self.gamesOnlyCheckBox.setObjectName("checkboxes") self.gamesOnlyCheckBox.setChecked(self.config.get('gamesOnly')) self.gamesOnlyCheckBox.setFocusPolicy(QtCore.Qt.NoFocus) self.checkBoxLay = QHBoxLayout() self.checkBoxLay.addSpacing(10) self.checkBoxLay.addStretch(1) self.checkBoxLay.addWidget(self.overlayCheckBox) self.checkBoxLay.addSpacing(5) self.checkBoxLay.addWidget(self.startOnStartupCheckBox) self.checkBoxLay.addSpacing(5) self.checkBoxLay.addWidget(self.startActiveCheckBox) self.checkBoxLay.addSpacing(5) self.checkBoxLay.addWidget(self.gamesOnlyCheckBox) self.checkBoxLay.addStretch(1) self.checkBoxLay.addSpacing(10) # -------------------------------------------------------------------------------------------------------------- self.layout.addLayout(self.titleLayout) self.layout.addSpacing(20) self.layout.addLayout(self.onoffLay) self.layout.addSpacing(5) self.layout.addLayout(self.keybindLay) self.layout.addSpacing(20) self.layout.addLayout(self.messageBoxLay) self.layout.addStretch(1) self.layout.addLayout(self.checkBoxLay) self.layout.addSpacing(10) self.setLayout(self.layout) self.oldPos = self.pos() menu = QMenu() menu.setStyleSheet( open( os.path.join(working_directory, 'systemTray', 'system_tray_menu_stylesheet.css')).read()) showAction = menu.addAction("Show") showAction.triggered.connect(self.show_window) try: showAction.setIcon( QtGui.QIcon( os.path.join(working_directory, 'systemTray', 'tray_menu_show_app_icon.png'))) except Exception as e: print("Error: " + e) exitAction = menu.addAction("Exit") exitAction.triggered.connect(self.close_window) try: exitAction.setIcon( QtGui.QIcon( os.path.join(working_directory, 'systemTray', 'tray_menu_exit_app_icon.png'))) except Exception as e: print("Error:" + e) self.tray = QSystemTrayIcon() self.tray_icon = QtGui.QIcon( os.path.join(working_directory, 'systemTray', 'tray_icon.png')) self.tray.setIcon(self.tray_icon) self.tray.setToolTip(appname) self.tray.setVisible(1) self.tray.setContextMenu(menu) self.tray.activated.connect( self.system_tray_icon_clicked_or_doubleclicked) global overlayStatus overlayStatus = self.config.get("showOverlay") global work_on_games_with_hidden_mouse_only work_on_games_with_hidden_mouse_only = self.config.get('gamesOnly') if self.config.get("startActive"): onoffButton.click() if not onoffButton.isChecked(): self.turnBotOn() else: self.turnBotOff() def turnBotOn(self): onoffLabel.setText("ON") print("Set Bot: Active") self.queue.put([1, overlayStatus]) global bot_active bot_active = 1 def turnBotOff(self): onoffLabel.setText("OFF") print("Set Bot: Disabled") self.queue.put([0, overlayStatus]) global bot_active bot_active = 0 def setStartOnStartup(self): checked = self.startOnStartupCheckBox.isChecked() self.config.set("startOnBoot", checked) self.config.save() if checked: self.addToStartUp() else: self.removeFromStartup() def setStartActive(self): checked = self.startActiveCheckBox.isChecked() self.config.set("startActive", checked) self.config.save() def setShowOverlay(self): checked = self.overlayCheckBox.isChecked() self.config.set("showOverlay", checked) self.config.save() global overlayStatus if checked: overlayStatus = 1 self.queue.put([int(not onoffButton.isChecked()), overlayStatus]) else: overlayStatus = 0 self.queue.put([2, overlayStatus]) def setGamesOnly(self): checked = self.gamesOnlyCheckBox.isChecked() self.config.set("gamesOnly", checked) self.config.save() global work_on_games_with_hidden_mouse_only work_on_games_with_hidden_mouse_only = checked def addToStartUp(self): self.exe_name = os.path.basename(sys.argv[0]) self.target_exe = (os.path.abspath(sys.argv[0])) self.working_directory = (os.path.abspath( sys.argv[0])).split("\\" + self.exe_name)[0] print("Add to startup" + str(self.exe_name) + str(self.target_exe) + str(self.working_directory)) try: windowsStartupFolder = winshell.startup() shell = win32com.client.Dispatch('WScript.Shell') shortcut = shell.CreateShortCut(windowsStartupFolder + '\%s.lnk' % self.shortcutName) shortcut.Targetpath = r'%s' % self.target_exe shortcut.WorkingDirectory = r'%s' % self.working_directory shortcut.save() except Exception as error: print("Error adding shortcut to startup folder. --> " + str(error)) def removeFromStartup(self): windowsStartupFolder = winshell.startup() try: if os.path.exists(windowsStartupFolder + '\%s.lnk' % self.shortcutName): os.remove(windowsStartupFolder + '\%s.lnk' % self.shortcutName) print("--------------> Successfully removed from startup") else: pass except Exception as error: print("Error removing shortcut from startup folder. --> " + str(error)) def disableBotWhileRecording(self): global bot_active bot_active = 0 def set_OnOff_shortcut_key(self): recordShootShortcut.setDisabled(1) onoffButton.setDisabled(1) recordOnOffShortcut.setText("Recording") recordOnOffShortcut.setStyleSheet( "QPushButton#recordOnOffshortcutButton{color: red; border: 1px solid grey;}QPushButton#recordOnOffshortcutButton:hover{border: 1px solid khaki;color: grey;}" ) print('--------------> Recording OnOff Shortcut...') global Shortcut_Function Shortcut_Function = 'OnOff_Shortcut_Key' global onoff_recording_step onoff_recording_step = 0 def set_Shoot_shortcut_key(self): recordOnOffShortcut.setDisabled(1) onoffButton.setDisabled(1) recordShootShortcut.setText("Recording") recordShootShortcut.setStyleSheet( "QPushButton#recordShootshortcutButton{color: red; border: 1px solid grey;}QPushButton#recordShootshortcutButton:hover{border: 1px solid khaki;color: grey;}" ) print('--------------> Recording Shoot Shortcut...') global Shortcut_Function Shortcut_Function = 'Game_Shoot_Shortcut_Key' def system_tray_icon_clicked_or_doubleclicked(self, reason): if reason == QSystemTrayIcon.Trigger or reason == QSystemTrayIcon.DoubleClick: self.show_window() def show_window(self): self.show() self.tray.show() self.activateWindow() self.center() def openInfoWebpage(self): webbrowser.open('https://github.com/omega0verride/AutoShoot-Bot') def btn_minimise_clicked(self): self.hide() def close_window(self): self.close() def center(self): qr = self.frameGeometry() cp = QtWidgets.QDesktopWidget().availableGeometry().center() qr.moveCenter(cp) self.move(qr.topLeft()) def mousePressEvent(self, event): self.oldPos = event.globalPos() def mouseMoveEvent(self, event): delta = QtCore.QPoint(event.globalPos() - self.oldPos) self.move(self.x() + delta.x(), self.y() + delta.y()) self.oldPos = event.globalPos()
import locale from easysettings import EasySettings settings = EasySettings("../resources/settings.conf") if not settings.has_option('Language'): if locale.getdefaultlocale() == "fa_IR": settings.set("Language", "Persian") else: settings.set("Language", "English") settings.save() if settings.get('Language') == 'Persian': nameOfProgram = "Movie Sorter" chooseFileName = "انتخاب فایل" quitText = 'خروج' startText = 'شروع دسته بندی' folderForEpisodes = 'فولدر سازی برای قسمت ها' putYearInBrackets = 'قرار دادن سال ساخت داخل پرانتز' moviesText = 'فیلم ها' seriesText = 'سریال ها' unfolderString = 'درووردن فایل ها از فولدر ها' infoText = 'درباره ما' nameFormat = ':فرمت اسم فایل' settingsText = ':تنظیمات' formatsText = ':فرمت ها' getAncher = 'e' first = 'right' last = 'left' chooseDirText = 'انتخاب فولدر مورد نظر' completeMessage = "دسته بندی انجام شد" nameChange = "هم اسم کردن فیلم و زیرنویس" changeLanguage = "English"
def resource_path(relative_path): """used by pyinstaller to see the relative path""" if hasattr(sys, '_MEIPASS'): return os.path.join(sys._MEIPASS, relative_path) return os.path.join(os.path.abspath('.'), relative_path) guifile = resource_path("./gui/main.ui") logo = resource_path("./gui/logo.png") userfold = str(pathlib.Path.home()) config = EasySettings(userfold + "/imageconverter.conf") configGui = resource_path("./gui/config.ui") try: saveLocation = config.get("saveLocation") saveAs = config.get("saveFormat") if saveLocation or saveAs == "": saveLocation = userfold + '/Pictures/' config.set("saveLocation", str(saveLocation)) config.set("saveFormat", 'jpeg') config.save() except FileNotFoundError: pass class GUI(QMainWindow): """main window used by the application""" def __init__(self): super(GUI, self).__init__() UIFile = QFile(guifile)
class Settings: """ Class which handles saving values to a preferences file. """ def __init__(self): filepath = file_utils.settings_path self._settings = EasySettings(filepath) def get_recent_files(self) -> List[str]: files = self._settings.get(_key_recent_files) if files and isinstance(files, str): return [] return files or [] def add_recent_file(self, new_file: str): files = self.get_recent_files() if new_file: if new_file in files: files.remove(new_file) files.insert(0, new_file) self._settings.set(_key_recent_files, files) self._settings.save() def get_recent_freq(self) -> List[float]: freq = self._settings.get(_key_recent_frequencies) return freq or [] def add_recent_freq(self, new_freq: float): freq = self.get_recent_freq() if new_freq is not None: if new_freq in freq: freq.remove(new_freq) freq.insert(0, new_freq) self._settings.set(_key_recent_frequencies, freq) self._settings.save() def is_runtime_warning_enabled(self) -> bool: return self._settings.get(_key_runtime_warning, True) def set_runtime_warning_enabled(self, enabled: bool) -> None: self._settings.set(_key_runtime_warning, enabled) self._settings.save() def get_latest_commits(self) -> Optional[Dict]: """ :returns a dictionary containing the latest commit hash for each branch. """ out = self._settings.get(_key_latest_commit, None) branch = self.get_update_branch() # In older versions, this is a string rather than a dict. if isinstance(out, str): out = {branch: out} return out or {} def get_latest_commit_on_branch(self) -> Optional[str]: """ :returns the latest commit on the branch which is selected as the update source. """ return self.get_latest_commits().get(self.get_update_branch()) def set_latest_commit(self, latest_commit: str) -> None: """ Sets the latest commit hash for the current update branch. :param latest_commit: the latest commit hash """ commits = self.get_latest_commits() commits[self.get_update_branch()] = latest_commit self._settings.set(_key_latest_commit, latest_commit) self._settings.save() def set_update_available(self, value: bool) -> None: available: Dict = self.get_update_available() available[self.get_update_branch()] = value self._settings.set(_key_update_available, available) self._settings.save() def get_update_available_on_branch(self) -> bool: return self.get_update_available().get(self.get_update_branch()) def get_update_available(self) -> Optional[Dict]: out = self._settings.get(_key_update_available, False) branch = self.get_update_branch() if isinstance(out, bool): out = {branch: out} return out def should_check_updates(self) -> bool: return time.time() - self._settings.get(_key_last_update_check, 0.0) > 3600 * 6 def get_last_update_check(self) -> float: return self._settings.get(_key_last_update_check, 0) def set_last_update_check(self, time: float) -> None: self._settings.set(_key_last_update_check, time) self._settings.save() def set_update_source(self, branch: str) -> None: self._settings.set(_key_update_source, branch) self._settings.save() def get_update_branch(self) -> str: return self._settings.get(_key_update_source, "release").lower() def get_save_directory(self) -> str: return self._settings.get(_key_save_dir, os.getcwd()) def set_save_directory(self, save_dir: str) -> None: self._settings.set(_key_save_dir, save_dir) self._settings.save() def get_pymodalib_cache(self) -> Optional[str]: return self._settings.get(_key_pymodalib_cache, None) def set_pymodalib_cache(self, location: str) -> None: self._settings.set(_key_pymodalib_cache, location) self._settings.save() self._settings.reload_file() def set_update_in_progress(self, updating: bool) -> None: self._settings.set(_key_updating, updating) self._settings.save() def get_update_in_progress(self) -> bool: return self._settings.get(_key_updating, False) def get_pymoda_version(self) -> str: return self._settings.get(_key_version, None) def set_pymoda_version(self, version: str) -> None: current = self._settings.get(_key_version) if not current or is_version_newer(new=version, old=current): self._settings.set(_key_version, version) self._settings.save() else: logging.error( f"Trying to set PyMODA version to {version}, but the current value is {current}" ) def set_last_opened_directory(self, directory: str) -> None: self._settings.set(_key_directory, directory) self._settings.save() def get_last_opened_directory(self) -> str: return self._settings.get(_key_directory, None)
class Settings: """ Class which handles saving values to a preferences file. """ def __init__(self): location = Path(os.getcwd()).parent filepath = path.join(location, "settings.conf") self._settings = EasySettings(filepath) def get_recent_files(self) -> List[str]: files = self._settings.get(_key_recent_files) return files or [] def add_recent_file(self, new_file: str): files = self.get_recent_files() if new_file: if new_file in files: files.remove(new_file) files.insert(0, new_file) self._settings.set(_key_recent_files, files) self._settings.save() def get_recent_freq(self) -> List[float]: freq = self._settings.get(_key_recent_frequencies) return freq or [] def add_recent_freq(self, new_freq: float): freq = self.get_recent_freq() if new_freq is not None: if new_freq in freq: freq.remove(new_freq) freq.insert(0, new_freq) self._settings.set(_key_recent_frequencies, freq) self._settings.save() def is_runtime_warning_enabled(self) -> bool: return self._settings.get(_key_runtime_warning, True) def set_runtime_warning_enabled(self, enabled: bool) -> None: self._settings.set(_key_runtime_warning, enabled) self._settings.save() def get_latest_commit(self) -> Optional[str]: return self._settings.get(_key_latest_commit, None) def set_latest_commit(self, latest_commit: str) -> None: self._settings.set(_key_latest_commit, latest_commit) self._settings.save() def set_update_available(self, value: bool) -> None: self._settings.set(_key_update_available, value) self._settings.save() def get_update_available(self) -> bool: return self._settings.get(_key_update_available, False) def should_check_updates(self) -> bool: return time.time() - self._settings.get(_key_last_update_check, 0.0) > 3600 * 6 def set_last_update_check(self, time: float) -> None: self._settings.set(_key_last_update_check, time) self._settings.save()
def main(): global settings global client try: logging.basicConfig(filename='SprinklrClient.log', level=logging.DEBUG) logging.debug("Starting SprinklrClientTest with " + str(len(sys.argv) - 1) + " actual parameters") settings = EasySettings("Sprinklr.conf") key = settings.get('key') path = settings.get('path') access_token = settings.get('access_token') if len(path) == 0: path = None # If using a differnent enviornment other that Prod, set path to that value (like 'prod2') client = sc.SprinklrClient(key=key, access_token=access_token, path=path) if len(sys.argv) > 1: command = str(sys.argv[1]).upper() if command == 'ADDCOMMENTTOCASE': add_comment_to_case(sys.argv[2], sys.argv[3]) elif command == 'AUTHORIZE': if len(sys.argv) > 5: print( "Invalid command line - Usage: SprinklrClientTest Authorize {apikey} {redirect_uri} [environment]" ) else: key = sys.argv[2] redirect_uri = sys.argv[3] if len(sys.argv) == 5: path = sys.argv[4] else: path = None client = sc.SprinklrClient(key) authorize(key, redirect_uri, path) elif command == "CUSTOMFIELDADDOPTION": custom_field_add_option(sys.argv[2], sys.argv[3]) elif command == "CUSTOMFIELDDELETEOPTION": custom_field_delete_option(sys.argv[2], sys.argv[3]) elif command == 'FETCHALLDASHBOARDS': fetch_all_dashboards() elif command == 'FETCHACCESSTOKEN': if len(sys.argv) != 6: print( "Invalid command line - Usage: SprinklrClientTest GetAccessToken {path} {apikey} {secret} " "{code} {redirect URI}") else: path = sys.argv[2] key = sys.argv[3] secret = sys.argv[4] code = sys.argv[5] redirect = sys.argv[6] client = sc.SprinklrClient(key, path) success = client.fetch_access_token(secret=secret, code=code, redirect_uri=redirect) if success: settings.set('access_token', client.access_token) settings.set('refresh_token', client.refresh_token) settings.set('redirect_uri', redirect) settings.set('key', key) settings.set('secret', secret) settings.set('path', path), settings.save() print("Success") else: print(client.result) key = settings.get('key') access_token = settings.get('access_token') client = sc.SprinklrClient(key=key, access_token=access_token) elif command == 'FETCHACCESSIBLEUSERS': fetch_accessible_users() elif command == 'FETCHACCOUNT': fetch_account(sys.argv[2], sys.argv[3]) elif command == 'FETCHACCOUNTCUSTOMFIELDS': fetch_account_custom_fields() elif command == 'FETCHARCHIVEDCASES': fetch_archived_cases() elif command == "FETCHCASEBYNUMBER": fetch_case_by_number(sys.argv[2]) elif command == "FETCHCASECOMMENT": fetch_case_comment(sys.argv[2], sys.argv[3]) elif command == "FETCHCASECOMMENTS": fetch_case_comments(sys.argv[2]) elif command == "FETCHCASEMESSAGESBYID": fetch_case_messages(sys.argv[2]) elif command == "FETCHCLIENTS": fetch_clients() elif command == 'FETCHCLIENTPROFILELISTS': fetch_client_profile_lists() elif command == "FETCHCLIENTURLSHORTNERS": fetch_client_url_shortners() elif command == 'FETCHCLIENTQUEUES': fetch_client_queues() elif command == 'FETCHCLIENTUSERS': fetch_client_users() elif command == 'FETCHDASHBOARDBYNAME': if len(sys.argv) != 3: print( "Invalid command line - Usage: SprinklrClientTest GetDashboardByName {name}" ) else: fetch_dashboard_by_name(sys.argv[2]) elif command == 'FETCHDASHBOARDSTREAM': fetch_dashboard_stream(sys.argv[2], sys.argv[3], sys.argv[4]) elif command == 'FETCHINBOUNDCUSTOMFIELDS': fetch_inbound_custom_fields() elif command == 'FETCHLISTENINGTOPICS': fetch_listening_topics() elif command == 'FETCHLISTENINGSTREAM': if len(sys.argv) == 5: fetch_listening_stream(sys.argv[2], sys.argv[3], sys.argv[4]) elif len(sys.argv) == 6: fetch_listening_stream(sys.argv[2], sys.argv[3], sys.argv[4], echo_request=sys.argv[5]) elif command == 'FETCHMACROS': fetch_macros() elif command == 'FETCHMEDIAASSETCUSTOMFIELDS': fetch_media_asset_custom_fields() elif command == 'FETCHMESSAGEBYUMID': fetch_message_by_umid(sys.argv[2]) elif command == 'FETCHOUTBOUNDCUSTOMFIELDS': fetch_outbound_custom_fields() elif command == 'FETCHPARTNERACCOUNTGROUPS': fetch_partner_account_groups() elif command == 'FETCHPARTNERACCOUNTS': fetch_partner_accounts() elif command == 'FETCHPARTNERCAMPAIGNS': fetch_partner_campaigns() elif command == 'FETCHPARTNERQUEUES': fetch_partner_queues() elif command == 'FETCHPARTNERUSERS': fetch_partner_users() elif command == 'FETCHPERMISSIONS': fetch_permissions() elif command == 'FETCHPROFILECUSTOMFIELDS': fetch_profile_custom_fields() elif command == "FETCHREPORTBYFILE": fetch_report_by_file(sys.argv[2]) elif command == 'FETCHRESOURCES': fetch_resources(sys.argv[2]) elif command == 'FETCHUSER': fetch_user() elif command == 'FETCHUSERBYID': fetch_user_by_id(sys.argv[2]) elif command == 'FETCHUMPRIORITIES': fetch_um_priorities() elif command == 'FETCHUMSTATUSES': fetch_um_statuses() elif command == "FETCHUSERGROUPS": fetch_user_groups() elif command == "FETCHWEBHOOKTYPES": fetch_webhook_types() elif command == "REFRESHACCESSTOKEN": key = settings.get('key') secret = settings.get('secret') redirect = settings.get('redirect_uri') refresh_access_token = settings.get('refresh_token') path = settings.get('path') client = sc.SprinklrClient(key) success = client.refresh_access_token(secret, redirect, refresh_access_token) if success: settings.set('access_token', client.access_token) settings.set('refresh_token', client.refresh_token) settings.set('redirect_uri', redirect) settings.set('key', key) settings.set('secret', secret) settings.save() print("Success") else: print(client.result) elif command == "SENDEMAIL": send_email(sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5]) else: print_usage() else: print_usage() except Exception as ex: print("Error:" + str(ex)) print_usage()
def get(name, values): """The showrunner, where all the magic happens This function (this whole module really) is designed to do one thing: abstract away all the noise and complexity of configuration management. Rather than handle user input and figuring out where and how to store that input and wrestling with file permission (or lack thereof), just let this module take care of it for you! When you run this function for the first time, here's what happens: - a config file is created in a folder named after your app, in ~/.config (linux XDG standard location for user-specific config files) - the user gets prompted to answer a set of questions defined by you - the answers to those questions are stored in the config file - If any of those questions are marked optional, the following happens: after the user is prompted to answer the question, they will be asked to save their response. If they answer yes, the value will be saved as normal. If they answer no, the value will not be saved, and they will be prompted to answer the question again the next time this function is called. - The user will be notified that a config file has been created for them, and reminded to set appropriate permissions for this file if it contains any sensitive info. - if we can't save the config file (due to permission errors or something else), we warn the user of the issue, and treat all values gathered as optional. The next time this function runs, the user will be prompted for those values again just as if this function had never been called before. This behaviour will continue until the problem preventing config file saving is resolved. - this function returns an object containing all the values that were gathered from the user Any time this function is called afterwards: - all the values specified are retrieved from the config file that was created the first time around. - any value marked as optional which wasn't saved last time will be prompted for again, and the user will once again be given the option to save it - this function returns an object containing all the values that were gathered from the user Args: name (str): The name of the application to store / retrieve config for values (Sequence[Dict[str, str]]): The values to get / set in our config file, in the form of: [ { value (str): The value to get / set prompt (str): If the value hasn't been set yet, and user input is required, what question or prompt should be displayed for the user to respond to? optional (bool): if True, prompt if user wants to save the value in config file, or prompt for it every time (ie. passwords) sensitive (bool): if True, getpass will be used to record the answer to this question (meaning that any text typed in as response to this question will not be printed onto the screen }, ... ] Returns: Dict[str, str]: a dictionary of all the values that were gathered from either the user or the config file Raises: #TODO: flesh this out Examples: >>>values = [ ... { ... 'value': 'url', ... 'prompt': "Please enter the full URL of your " ... "phpIPAM installation including the API app_id " ... "\\nex. https://phpipam.mycompanyserver.com" ... "/api/app_id/ \\nURL> ", ... 'optional': False, ... 'sensitive': False ... }, ... { ... 'value': 'username', ... 'prompt': "Please enter your phpIPAM username: "******"\\nUsername> ", ... 'optional': True, ... 'sensitive': False ... }, ... { ... 'value': 'password', ... 'prompt': "Please enter your phpIPAM password: "******"\\nPassword> ", ... 'optional': True, ... 'sensitive': True ... }, ... ] >>>get('phpipam', values) # Called for the first time Please enter the full URL of your phpIPAM installation including the API app_id ex. https://phpipam.mycompanyserver.com/api/app_id/ URL> >? https://my.domain.com/phpipam/api/my_app_id/ Please enter your phpIPAM username: Username> >? mytestuser Would you like to save this for later use? (yes/no)> >? yes Warning: Password input may be echoed. Please enter your phpIPAM password: Password> >? mysupersecretpassword Would you like to save this for later use? (yes/no)> >? no {'password': '******', 'username': '******', 'url': 'https://my.domain.com/phpipam/api/my_app_id/'} >>>get('phpipam', values) # Called again {'password': '******', 'username': '******', 'url': 'https://my.domain.com/phpipam/api/my_app_id/'} """ settings_file = os.path.expanduser(SETTINGS_FILE_ROOT + name + '/config') if not os.path.exists(settings_file): os.makedirs(os.path.dirname(settings_file), mode=0o700) settings = EasySettings(settings_file) result = dict() for item in values: key_name = item['value'] result[key_name] = settings.get(item['value'], default=None) if not result[key_name]: sensitive = item['sensitive'] # bool result[key_name] = get_user_input(item['prompt'], sensitive) if item['optional']: choice = get_user_input("Would you like to save this for later " "use? \n(yes/no)> ", sensitive=False) if choice[0] == 'y' or choice[0] == 'Y': settings.setsave(key_name, result[key_name]) else: settings.setsave(key_name, result[key_name]) return result