def __init__(self): try: import unidecode except ImportError: PluginInstaller().installPackages(['unidecode']) try: from discoIPC import ipc except ImportError: PluginInstaller().installPackages(['discoIPC']) from discoIPC import ipc self.discord = ipc.DiscordIPC( "504997049226362891") # 450824928841957386 try: self.discord.connect() except: ts3lib.logMessage("Discord not running!", ts3defines.LogLevel.LogLevel_WARNING, "pyTSon Discord Rich Presence", 0) self.timer.timeout.connect(self.tick) self.timer.setTimerType(2) schid = ts3lib.getCurrentServerConnectionHandlerID() self.onTabChangedEvent(schid) self.timer.start(1000) """ (err, status) = ts3lib.getConnectionStatus(schid) if status == ts3defines.ConnectStatus.STATUS_CONNECTION_ESTABLISHED: self.updateServer(schid); self.updateChannel(schid); self.updateVoice(schid);self.updateClient(schid) """ if PluginHost.cfg.getboolean("general", "verbose"): ts3lib.printMessageToCurrentTab( "{0}[color=orange]{1}[/color] Plugin for pyTSon by [url=https://github.com/{2}]{2}[/url] loaded." .format(timestamp(), self.name, self.author))
def init_important(): config = configparser.ConfigParser() config.read('config.ini') _client = ipc.DiscordIPC(config['CLIENT']['client_id']) installer = ChromeDriverManager().install() options = Options() options.headless = True _driver = webdriver.Chrome(installer, options=options) _driver.get('https://developer.microsoft.com/en-us/graph/graph-explorer') _driver.find_element_by_xpath( '/html/body/div[4]/div/div[2]/div[1]/div[2]/div[1]/div/button/span' ).click() _driver.switch_to.window(_driver.window_handles[1]) _driver.implicitly_wait(5) _driver.find_element_by_xpath( '/html/body/div/form[1]/div/div/div[2]/div/div/div[1]/div[2]/div[2]/div/div/div/div[2]/div[2]/div/input[1]' ).send_keys('org_email') _driver.find_element_by_xpath( '/html/body/div/form[1]/div/div/div[2]/div/div/div[1]/div[2]/div[2]/div/div/div/div[4]/div/div/div/div[2]/input' ).click() _driver.find_element_by_xpath('/html/body/div/div[2]/div/form/div[3]/input' ).send_keys('org_username') _driver.find_element_by_xpath('/html/body/div/div[2]/div/form/div[5]/input' ).send_keys('org_password') _driver.find_element_by_xpath( '/html/body/div/div[2]/div/form/div[6]/a').click() time.sleep(15) _driver.switch_to.window(_driver.window_handles[0]) time.sleep(3) return [_client, _driver]
def send_rpc_activity(self): try: if not self.client_connected: # connects to Discord self.log.debug("Connecting to Discord IPC...") self.rpc_client = ipc.DiscordIPC(utils.get_api_key('discord2')) self.rpc_client.connect() self.log.debug("Connection successful") self.game_state.update_rpc = True self.rpc_client.update_activity(self.activity) self.log.info(f"Sent over RPC: {self.activity}") client_state: tuple = (self.rpc_client.client_id, self.rpc_client.connected, self.rpc_client.ipc_path, self.rpc_client.pid, self.rpc_client.platform, self.rpc_client.socket) self.log.debug(f"Client state: {client_state}") self.client_connected = True except Exception as client_connect_error: if str(client_connect_error) in ( "Can't send data to Discord via IPC.", "Can't connect to Discord Client."): # often happens when Discord is in the middle of starting up self.handle_rpc_error(str(client_connect_error)) else: raise
def main(): """Riddles. A small text-based riddle game with Discord Rich Presence.""" client = ipc.DiscordIPC(config['CLIENT']['client_id']) # Connect to Discord Client client.connect() print('\nStarting Riddles...\n') time.sleep(5) # Level 1. client.update_activity(set_activity(1)) # Update Activity while True: print('A merchant can place 8 large boxes or 10 small boxes into a ' + 'carton for shipping. In one shipment, he sent a total of 96 ' + 'boxes. If there are more large boxes than small boxes, how ' + 'many cartons did he ship?\n') answer = input('Answer: ') # Answer is 11: # 7 large boxes (7 * 8 = 56 boxes) # 4 small boxes (4 10 = 40 boxes # 11 total cartons and 96 boxes if answer == '11': print('\nCorrect! Let\'s move on to the next riddle.\n') break else: print('\nWrong answer! Let\'s try again.\n') # Level 2. client.update_activity(set_activity(2)) # Update Activity while True: print('If 9999 = 4, 8888 = 8, 1816 = 6, 1212 = 0, then 1919 =\n') answer = input('Answer: ') # Answer is 4: # Look at how many closed areas are there. # - 9999 has 4 closed areas (the top of the '9') # - 8888 has 8 closed areas, the top and bottom parts of the 8 and # there are no other digits # - 1816 has 3 closed areas, (top and bottom of 8 and bottom of 6, # and it has 2 other digits ( 3*2=6) # - 1212 has 0 closed areas,(0*4=0) if answer == '4': print('\nCorrect! That\'s the end, thanks for playing.\n') break else: print('\nWrong answer! Let\'s try again.\n') # The End! client.disconnect()
def main(): client = ipc.DiscordIPC(config['CLIENT']['client_id']) # Connect to Discord Client client.connect() print('\nStarting Custom Activity...\n') time.sleep(5) try: client.update_activity(set_activity()) # Update Activity while True: input('\nConnected! ') # Do nothing except KeyboardInterrupt: print('Disconnecting...\n') client.disconnect()
def test_discoipc(self): # this test fails if Discord isn't running test_process_scanner = processes.ProcessScanner(self.log) if not test_process_scanner.scan()['Discord']['running']: self.skipTest("Discord needs to be running") activity = { 'details': "Testing TF2 Rich Presence", 'timestamps': { 'start': int(time.time()) }, 'assets': { 'small_image': 'tf2_icon_small', 'small_text': 'Team Fortress 2', 'large_image': 'main_menu', 'large_text': 'In menus' }, 'state': "(Probably don't actually have the game open)" } client = ipc.DiscordIPC('429389143756374017') time.sleep(0.1) # this fix works? seriously? client.connect() client.update_activity(activity) client_state = (client.client_id, client.connected, client.ipc_path, isinstance(client.pid, int), client.platform, isinstance(client.socket, io.BufferedRandom), client.socket.name) self.assertEqual( client_state, ('429389143756374017', True, '\\\\?\\pipe\\discord-ipc-0', True, 'windows', True, '\\\\?\\pipe\\discord-ipc-0')) client.disconnect() client_state = (client.client_id, client.connected, client.ipc_path, isinstance(client.pid, int), client.platform, client.socket) self.assertEqual(client_state, ('429389143756374017', False, '\\\\?\\pipe\\discord-ipc-0', True, 'windows', None))
'large_image': 'blender', 'large_text': 'Blender ' + bpy.app.version_string.split(" ")[0], 'small_image': 'default_file', 'small_text': '(Untitled)' }, 'timestamps': {}, } pid = os.getpid() objcount = 0 timeElapsed = int(time.time()) active = 0 rendering = 0 rendertime = 0 client = ipc.DiscordIPC( '000000000000000000') # Replace your clientID with the 18 digit template client.connect() print('\nStarting Discord ICP ...\n') @atexit.register def disconnect(): main() print('Disconnecting Discord ICP ...\n') client.disconnect() @persistent def main(): client.update_activity(set_activity())
config = configparser.ConfigParser() config.read('config.ini') base_activity = { 'assets': { 'large_image': 'example-big', 'large_text': 'Example big', 'small_image': 'example-small', 'small_text': 'Example small', }, 'timestamps': {} } timeElapsed = int(time.time()) client = ipc.DiscordIPC(config['CLIENT']['client_id']) client.connect() print('\nStarting ICP...\n') def set_activity(): activity = base_activity activity['details'] = 'Example' activity['state'] = 'example' activity['timestamps']['start'] = timeElapsed return activity try: while True:
def main(): old_data = {} client = ipc.DiscordIPC('407579153060331521') client.connect() bus = SessionBus() while True: try: remote_object = bus.get('org.mpris.MediaPlayer2.cmus', '/org/mpris/MediaPlayer2') except Error as ex: if ex.args[ 0] == 'GDBus.Error:org.freedesktop.DBus.Error.ServiceUnknown: The name org.mpris.MediaPlayer2.cmus was not provided by any .service files': print( 'cmus is compiled without mpris support or is not running, sleeping for 10s...' ) time.sleep(10) continue metadata = remote_object.Metadata status = remote_object.PlaybackStatus if config['loop'] == True: loop = loop_check(remote_object.LoopStatus) else: loop = None paused = False icon = 'playing' timestamp = None try: position = int(time.time() + remote_object.Position / 1000000) if config['timestamp'] == 'status': duration = str( datetime.timedelta( microseconds=int(metadata['mpris:length']))) position = str( datetime.timedelta( microseconds=int(remote_object.Position))) elif status != 'Paused': duration = int(time.time() + metadata['mpris:length'] / 1000000) timestamp = duration - position elif status == 'Paused': paused = True duration = 0 except KeyError: print( 'no song is playing or timing failed, sleeping for 5 seconds...' ) time.sleep(5) continue try: if config['kbps'] == False: kbps = None else: kbps = '{} kbps'.format(str(metadata['cmus:bitrate'])[:-3]) except KeyError: print( "hey!! your cmus version isn't my fork.. whatever, continuing.." ) kbps = None try: if config['artist'] == False: artist = None else: artist = artist_string(metadata['xesam:artist']) except KeyError: artist = '?' try: track = metadata['xesam:title'] except KeyError: try: # god has left us track = song_file_path(metadata['cmus:file_path']) except KeyError: track = '?' artist_track = '{} - {}'.format(artist, track) if config["timestamp"] == "status": status_thing = status_string(loop, kbps, status, "{}/{}".format(position, duration)) else: status_thing = status_string(loop, kbps, status, None) if status == 'Paused': icon = 'paused' data = { 'artist_track': artist_track, 'status_kbps': status_thing, 'icon': icon, 'status': status, 'timestamp': timestamp, 'paused': paused } if data != old_data or config['skip_data_checks_hack'] is True: client.update_activity(update_presence(data)) old_data = data time.sleep(15) else: time.sleep(5)
if __name__ == "__main__": print("Starting Nuclear Throne RPC") if RUN_TUTORIAL: if input( "Please confirm that your Stream Key is %s, type Y to continue\n" % STREAM_KEY).lower() != "y": sys.exit() if input( "Please confirm that your Steam64ID is %s, type Y to continue\n" % STEAM_64_ID).lower() != "y": sys.exit() s = Session(STREAM_KEY, STEAM_64_ID) client = ipc.DiscordIPC(DISCORD_CLIENT_ID) client.connect() print("Started Nuclear Throne RPC") while True: try: s.update() client.update_activity(s.generate_presence()) time.sleep(UPDATE_INTERVAL) print("[%s]: Updated Discord with game info" % time.strftime("%X")) except KeyboardInterrupt: print("Exiting Nuclear Throne RPC") client.disconnect() sys.exit()
'assets': { 'large_image': 'blender', 'large_text': 'Blender', }, 'timestamps': {}, } pid = os.getpid() filename = '' objcount = 0 timeElapsed = int(time.time()) active = 0 rendering = 0 rendertime = 0 client = ipc.DiscordIPC('${clientID}') # Replace the template ID with your ID client.connect() print('\nStarting Discord ICP ...\n') @atexit.register def disconnect(): main() print('Disconnecting Discord ICP ...\n') client.disconnect() @persistent def main(): client.update_activity(set_activity()) @persistent def resetTime(scene):
def main(): output_log_txt_path = "{}\\AppData\\LocalLow\\Hopoo Games, LLC\\Risk of Rain 2\\output_log.txt".format(os.getenv('UserProfile')) start_time = int(time.time()) activity = {'details': 'Loading game', # this is what gets modified and sent to Discord via discoIPC 'timestamps': {'start': start_time}, 'assets': {'small_image': ' ', 'small_text': 'Risk of Rain 2', 'large_image': 'logo', 'large_text': 'Risk of Rain 2'}, 'state': 'Not in lobby'} client_connected = False has_mention_not_running = False process_scanner = processes.ProcessScanner() while True: next_delay = 5 p_data = process_scanner.scan() activity['timestamps']['start'] = p_data['ROR2']['time'] if p_data['ROR2']['running'] and p_data['Discord']['running']: if not client_connected: # connects to Discord client = ipc.DiscordIPC('566395208858861569') client.connect() client_connected = True with open(output_log_txt_path, 'r', errors='replace') as output_log_txt: output_log = output_log_txt.readlines() old_details_state = copy.copy((activity['details'], activity['state'])) for line in output_log: if 'Loaded scene' in line: activity = switch_image_mode(activity) if 'title' in line: activity['details'] = "Main menu" activity['state'] = "Not in lobby" elif 'lobby loadSceneMode=Single' in line: activity['details'] = "In lobby" activity['state'] = "Singleplayer" elif 'crystalworld' in line: activity['state'] = "Prismatic Trials" elif 'golemplains' in line: activity = switch_image_mode(activity, ('golemplains', 'Titanic Plains')) elif 'blackbeach' in line: activity = switch_image_mode(activity, ('blackbeach', 'Distant Roost')) elif 'goolake' in line: activity = switch_image_mode(activity, ('goolake', 'Abandoned Aquaduct')) elif 'frozenwall' in line: activity = switch_image_mode(activity, ('frozenwall', 'Rallypoint Delta')) elif 'dampcavesimple' in line: activity = switch_image_mode(activity, ('dampcavesimple', 'Abyssal Depths')) elif 'mysteryspace' in line: activity = switch_image_mode(activity, ('mysteryspace', 'Hidden Realm: A Moment, Fractured')) elif 'bazaar' in line: activity = switch_image_mode(activity, ('bazaar', 'Hidden Realm: Bazaar Between Time')) elif 'foggyswamp' in line: activity = switch_image_mode(activity, ('foggyswamp', 'Wetland Aspect')) elif 'wispgraveyard' in line: activity = switch_image_mode(activity, ('wispgraveyard', 'Scorched Acres')) elif 'goldshores' in line: activity = switch_image_mode(activity, ('goldshores', 'Gilded Coast')) elif 'lobby creation succeeded' in line: activity['details'] = "In lobby" activity['state'] = "Multiplayer" activity = switch_image_mode(activity) elif 'Left lobby' in line: activity['details'] = "Main menu" activity['state'] = "Not in lobby" activity = switch_image_mode(activity) if time.time() - start_time < 10: activity['details'] = "Loading game" if old_details_state != (activity['details'], activity['state']): next_delay = 2 print(activity['details']) print(activity['state']) time_elapsed = time.time() - start_time print("{:02}:{:02} elapsed\n".format(int(time_elapsed / 60), round(time_elapsed % 60))) if not os.path.exists('history.txt'): open('history.txt', 'w').close() activity_str = f'{activity}\n' with open('history.txt', 'r') as history_file_r: history = history_file_r.readlines() if activity_str not in history: with open('history.txt', 'a') as history_file_a: history_file_a.write(activity_str) # send everything to discord client.update_activity(activity) elif not p_data['Discord']['running']: print("{}\nDiscord isn't running\n") else: if client_connected: try: client.disconnect() # doesn't work... except: pass raise SystemExit # ...but this does else: if not has_mention_not_running: print("Risk of Rain 2 isn't running\n") has_mention_not_running = True # to prevent connecting when already connected client_connected = False time.sleep(next_delay)