コード例 #1
0
ファイル: psndiscord.py プロジェクト: t0ry003/psndiscord
import time
import configparser

# get npsso, PSNID from psnconfig.ini (can be created with "config-creator.exe")

config = configparser.ConfigParser()
config.read('psnconfig.ini')
npsso = config['main']['npsso']
PSNID = config['main']['PSNID']

start_time = int(time.time())
oldpresence = ""
psnawp = psnawp.PSNAWP(npsso)
# initial usage => clear status if online

RPC = Presence("829124881324048404", pipe=0)
RPC.connect()

print(f"User: {PSNID} connected!")

while True:
    user_online_id = psnawp.user(online_id=PSNID)
    mainpresence = str(user_online_id.get_presence())
    print(mainpresence)
    start_time = int(time.time())
    if 'offline' in mainpresence:
        print("User is offline, clearing status")
        RPC.clear()
    else:
        if (oldpresence == mainpresence):
            pass
コード例 #2
0
                try:
                    set_presence(entered_location)
                    print(f"Entered {entered_location}")
                except DiscordError:
                    pass


if __name__ == "__main__":
    path = sys.argv[1]
    if not path:
        print("Log path not given, exitting.")
        exit(1)

    begin_time = time.time()
    presence = Presence("655060628582432768")
    observer = Observer()
    event_handler = FileEventHandler()

    observer.schedule(event_handler, path)
    observer.start()
    print("Started file watcher")

    presence.connect()
    print("Started Discord Presence")
    print("=" * 20, end="\n\n")

    # Default presence
    set_presence("Main Menu")

    try:
コード例 #3
0
    elif window["~firstbuttontext~"] == None and not window[
            "~firstbuttonurl~"] == None:
        window.Element("ERROR").Update(
            "An error occured! Please make sure to add a URL!")

    elif window["~firstbuttonurl~"] == None and not window[
            "~firstbuttontext~"] == None:
        window.Element("ERROR").Update(
            "An error occured! Make sure to add a label for your button!")

    else:

        try:

            RPC = Presence(values[0])
            RPC.connect()
            RPC.update(state=values[3],
                       details=values[4],
                       large_image=values[1],
                       small_image=values[2],
                       buttons=[{
                           "label": values[5],
                           "url": values[6]
                       }])  # Set the presence
            window.Element("ERROR").Update(
                "Success! Your rich presence is now up! Make sure to leave this window open.",
                text_color="green")

        except InvalidID:
            window.Element("ERROR").Update(
コード例 #4
0
    # Large image key found
    largeimage = Path("largeImage.txt").read_text()
else:
    # None found, ignore
    largeimage = None

# Remove quotes from path if necessary
vmwarepath = vmwarepath.replace("\"", "")
vmwarepath = vmwarepath.replace("\'", "")

vmrunpath = Path(vmwarepath).joinpath("vmrun.exe")  # Create the path to vmrun

COMMAND = "list"  # Static command to run

# Set up RPC
RPC = Presence(client_ID)
RPC.connect()
print("Connected to RPC.")
# Create last sent status so we don't spam Discord
LASTSTATUS = ""
# Set time to 0 to update on next change
epoch_time = 0

# Warning
print(
    "Please note that Discord has a 15 second ratelimit in sending Rich Presence updates."
)

# Run on a loop
while True:
    # Run vmrun list, capture output, and split it up
コード例 #5
0
ファイル: Valbot.py プロジェクト: danglir/Valbot
def main():

    try:
        RPC = Presence(client_id="772841390467711041")
        RPC.connect()
    except Exception:
        pass
    version = "Valbot v1.8.0"

    versionstripped = version.replace("Valbot ", "")

    activeactivity = "In Launcher"
    os.system('mode con: cols=39 lines=25')
    title = "title " + version
    os.system(title)
    try:

        RPC.update(state=("Running " + version.replace("Valbot ", "")),
                   start=time.time(),
                   large_image="valbotnew",
                   large_text=version,
                   details=activeactivity)

    except Exception:
        pass

    print(
        Fore.RED + """
    ╔╗  ╔╗╔═══╗╔╗   ╔══╗ ╔═══╗╔════╗
    ║╚╗╔╝║║╔═╗║║║   ║╔╗║ ║╔═╗║║╔╗╔╗║
    ╚╗║║╔╝║║ ║║║║   ║╚╝╚╗║║ ║║╚╝║║╚╝
     ║╚╝║ ║╚═╝║║║ ╔╗║╔═╗║║║ ║║  ║║  
     ╚╗╔╝ ║╔═╗║║╚═╝║║╚═╝║║╚═╝║  ║║  
      ╚╝  ╚╝ ╚╝╚═══╝╚═══╝╚═══╝  ╚╝
                             """ + Style.NORMAL + Fore.RED,
        versionstripped + Style.RESET_ALL)

    print(Style.RESET_ALL)
    print(Style.RESET_ALL + Fore.RED + "          By Fums & WolfAnto")
    print(Style.RESET_ALL)
    print(Style.RESET_ALL + Fore.RED +
          "———————————————————————————————————————")

    print(Style.RESET_ALL)
    print(Fore.RED + " [1]", Style.BRIGHT + "Start Bot")
    print(Style.RESET_ALL)
    print(Fore.RED + " [2]", Style.BRIGHT + "Information")
    print(Style.RESET_ALL)
    print(Fore.RED + " [3]", Style.BRIGHT + "Manage Discord Webhook")
    print(Style.RESET_ALL)
    print(Fore.RED + " [4]", Style.BRIGHT + "XP Calculator")
    print(Style.RESET_ALL)
    print(Fore.RED + " [5]", Style.BRIGHT + "Exit Bot")
    print(Style.RESET_ALL)

    print(Fore.YELLOW + "")
    menu = int(input(" > "))

    try:
        if menu == 1:

            print(Style.RESET_ALL)
            print(Fore.YELLOW, "Make sure you have the")
            print(Style.BRIGHT, "Valorant Card",
                  Style.NORMAL + "Player Card equipped")
            print(Style.RESET_ALL)
            print(Fore.YELLOW, "Valorant must be" + Style.BRIGHT, "FULLSCREEN")
            print(Style.NORMAL, "for the bot to function")
            response = requests.get(
                "https://api.github.com/repos/MrFums/Valbot/releases/latest")
            latest2 = response.json()["name"]
            changelog = response.json()["body"]

            latest3 = latest2.replace("Valbot v", "")
            latest4 = latest2.replace("Valbot ", "")
            latest = latest3.replace(".", "")
            latest = int(latest)

            version = version.replace("Valbot v", "")
            version = version.replace(".", "")
            version = int(version)

            if version < latest:
                print(Style.RESET_ALL)
                print(Fore.RED,
                      "Version (" + str(versionstripped) + ") is outdated")
                print(Style.RESET_ALL)
                print(Fore.RED,
                      "Download latest version (" + str(latest4) + ") now")
                print(Style.RESET_ALL)
                time.sleep(5)

            print(Style.RESET_ALL)
            root = str(pathlib.Path(__file__).parent.absolute())
            fullpath = root + "\Valorant.lnk"
            vallnk = Path(fullpath)
            if vallnk.is_file():
                # file exists
                try:
                    RPC.close()
                except Exception:
                    pass
                time.sleep(2)
                os.startfile("bot.py")
                time.sleep(.5)
                quit()
            else:
                print(Fore.RED, 'You do not have a Valorant shortcut')
                print(' named "Valorant" in the directory')
                print(Fore.RED, 'Add one now to continue')
                time.sleep(5)
                print(Style.RESET_ALL)
                if os.path.exists("runtime_values"):
                    os.remove("runtime_values")
                time.sleep(5)
                main()

        elif menu == 2:
            print(Style.RESET_ALL + "")
            print(Fore.RED + " IMPORTANT INFORMATION")
            print("")
            print(Fore.WHITE + " 1)",
                  Fore.CYAN + "Setup your Valorant shortcut")
            print("    and discord webhook (optional)", Style.RESET_ALL)
            print("")
            print(Fore.WHITE + " 2)",
                  Fore.CYAN + "Change your player card to the")
            print("    Valorant Card Player Card")
            print("")
            print(Fore.WHITE + " 3)",
                  Fore.CYAN + "Valorant must be fullscreen")
            print("    and focused")
            print("")
            print(Fore.BLUE + " Discord :", Fore.YELLOW + "Fums#0888")
            print(Fore.CYAN, Fore.BLUE + "Github :",
                  Fore.YELLOW + "https://github.com/MrFums", Style.RESET_ALL)
            print(Style.RESET_ALL)
            print(Style.BRIGHT, Fore.RED)
            print("")
            print(" Input anything to return...")
            print(Fore.YELLOW, Style.NORMAL + "")
            input(" > ")
            main()

        elif menu == 3:
            print(Style.RESET_ALL)
            print(Fore.RED + " WEBHOOK MANAGER")
            print(Style.RESET_ALL)
            print(Fore.WHITE + " 1)",
                  Fore.CYAN + "Open Discord, go to a server where")
            print("    you have permission to create")
            print("    and manage a webhook")
            print("")
            print(Fore.WHITE + " 2)",
                  Fore.CYAN + "Either create and / or edit an ")
            print('    existing channel and go to')
            print('    "Integrations"')
            print("")
            print(Fore.WHITE + " 3)",
                  Fore.CYAN + "Click webhooks and then click")
            print('    "Create Webhook", select the right')
            print('    channel, and then click')
            print('    "Copy Webhook URL"')
            print("")
            print(Fore.WHITE + " 4)", Fore.CYAN + "Paste your webhook below")
            print(Style.RESET_ALL)
            print(Style.BRIGHT, Fore.RED)
            print(" Paste a webhook to save or anything")
            print(" else to cancel")
            print(Style.RESET_ALL)
            print(Style.RESET_ALL)

            urlcheck = "https://discord.com/api/webhooks/"
            print(Fore.YELLOW + "")
            inputwebhook = input(" > ")
            inputwebhook = inputwebhook.replace(
                "https://discordapp.com/api/webhooks/",
                "https://discord.com/api/webhooks/")

            if urlcheck in inputwebhook:
                print(Style.RESET_ALL)

                if os.path.exists("webhook.config"):
                    os.remove("webhook.config")

                f = open("webhook.config", "a+")
                f.write(inputwebhook)
                f.close()
                print(Style.RESET_ALL)
                print(Fore.GREEN + " [√] Webhook added")
                print(Style.RESET_ALL)
                time.sleep(3)
                main()

            else:
                print(Style.RESET_ALL)
                print(Fore.RED +
                      " The input was not a webhook, returning to menu...")
                time.sleep(3)
                main()

        elif menu == 4:
            print(Style.RESET_ALL)
            print(Style.RESET_ALL, Fore.YELLOW + Style.BRIGHT,
                  "How much XP do you need to earn?")
            try:
                print(Style.RESET_ALL)
                print(Fore.YELLOW + "")
                xpai = int(input(" > "))
            except ValueError:
                print(" Error 2: You must enter an integer!")
                time.sleep(2)
                main()

            xpa = xpai / 900
            xpau = (math.ceil(xpa))
            print(Style.RESET_ALL)
            print(Fore.BLUE, "Required Games: " + Style.BRIGHT + str(xpau),
                  Fore.BLUE + "games")
            print(Style.RESET_ALL)
            print(Fore.BLUE, "ETA:", Style.BRIGHT + str(xpau / 4),
                  Fore.BLUE + "hours")

            time.sleep(7)
            print(Style.RESET_ALL)
            main()

        elif menu == 5:
            print(Style.BRIGHT + Fore.RED + " Quitting...")
            time.sleep(1)
            quit()

        else:
            print(" Error 1: Enter a valid integer within the range 1 - 5!")
            time.sleep(2)
            main()

    except ValueError:
        print(" Error 2: You must enter an integer!")
        time.sleep(2)
        main()
コード例 #6
0
ファイル: discord.py プロジェクト: TimothyRLaMora734/amrpc
 def __init__(self, id):
     self.id = id
     self.rpc = Presence(id)
     self.cleared = True
     self.rpc.connect()
コード例 #7
0
ファイル: disco.py プロジェクト: PietroCarrara/disco.py
    )

    prevData = data


# Initialize config
load_dotenv()

token = login(os.getenv('username'), os.getenv('password'))

if not token:
    print('Login attempt failed. Exiting...')
    sys.exit(1)

appID = os.getenv('appid')

# Check if is running in interactive mode
if not sys.flags.interactive:
    presence = Presence(appID)
    presence.connect()

    player = Playerctl.Player()
    player.connect('metadata', lambda p, m: updateMusic())

    updateMusic()

    # wait for events
    main = GLib.MainLoop()
    main.run()

    presence.close()
コード例 #8
0
ファイル: presence.py プロジェクト: Apache-HB/Custom-Presence
b = -1
for a in default:
    b += 1
    print(b, '-', a['name'])

index = int(input('select index for game\n'))

d = -1
for c in default[index]['states']:
    d += 1
    print(d, '-', c['name'])

subindex = int(input('select which state to use\n'))

client = Presence(default[index]['id'])
client.connect()

print(client.update(
    state=default[index]['states'][subindex].get('state'),
    details=default[index]['states'][subindex].get('details'),
    small_image=default[index]['states'][subindex].get('small_image'),
    small_text=default[index]['states'][subindex].get('small_text'),
    large_image=default[index]['states'][subindex].get('large_image'),
    large_text=default[index]['states'][subindex].get('large_text'),
    start=int(time())
))

window = tkinter.Tk()
window.title(default[index]['name'])
window.geometry('300x20')
コード例 #9
0
def main():
    consoleargs = parser.parse_args()

    switch_ip = consoleargs.ip
    client_id = consoleargs.client_id

    if not checkIP(switch_ip):
        print('Invalid IP')
        exit()

    rpc = Presence(str(client_id))
    try:
        rpc.connect()
        rpc.clear()
    except:
        print('Unable to start RPC!')

    switch_server_address = (switch_ip, TCP_PORT)
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    try:
        sock.connect(switch_server_address)
        print('Successfully connected to %s' % switch_ip + ':' + str(TCP_PORT))
    except:
        print('Error connection to %s refused' % switch_ip + ':' + str(TCP_PORT))
        exit()

    lastProgramName = ''
    startTimer = 0

    while True:
        data = None
        try:
            data = sock.recv(628)
        except:
            print('Could not connect to Server! Retrying...')
            startTimer = 0
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            try:
                sock.connect(switch_server_address)
                print('Successfully reconnected to %s' %
                      repr(switch_server_address))
            except:
                print('Error reconnection to %s refused' %
                      repr(switch_server_address))
                exit()
        title = Title(data)
        if title.magic == PACKETMAGIC:
            if lastProgramName != title.name:
                startTimer = int(time.time())
            if consoleargs.ignore_home_screen and title.name == 'Home Menu':
                rpc.clear()
            else:
                smallimagetext = ''
                largeimagekey = ''
                details = ''
                largeimagetext = title.name
                if int(title.pid) != PACKETMAGIC:
                    smallimagetext = 'SwitchPresence-Rewritten'
                    if title.name not in switchOverrides:
                        largeimagekey = iconFromPid(title.pid)
                        details = 'Playing ' + str(title.name)
                    else:
                        orinfo = switchOverrides[title.name]
                        largeimagekey = orinfo['CustomKey'] or iconFromPid(title.pid)
                        details = orinfo['CustomPrefix'] or 'Playing'
                        details += ' ' + title.name
                else:
                    smallimagetext = 'QuestPresence'
                    if title.name not in questOverrides:
                        largeimagekey = title.name.lower().replace(' ', '')
                        details = 'Playing ' + title.name
                    else:
                        orinfo = questOverrides[title.name]
                        largeimagekey = orinfo['CustomKey'] or title.name.lower().replace(
                            ' ', '')
                        details = orinfo['CustomPrefix'] or 'Playing'
                        details += ' ' + title.name
                if not title.name:
                    title.name = ''
                lastProgramName = title.name
                rpc.update(details=details, start=startTimer, large_image=largeimagekey,
                        large_text=largeimagetext, small_text=smallimagetext)
            time.sleep(1)
        else:
            time.sleep(1)
            rpc.clear()
            rpc.close()
            sock.close()
            exit()
コード例 #10
0
 def __init__(self, client):
     self.rpc = Presence(client)  # Initialize the client class
     self.rpc.connect()  # Start the handshake loop
コード例 #11
0
import obspython as obs
from pypresence import Presence
import datetime

rpc = Presence("831576935863812146")
rpc.connect()
rpc.update(state="Idling", large_image='obs_studio')


def script_description():
    return "OBS RPC for Discord!"


def obs_event(event):
    if event == obs.OBS_FRONTEND_EVENT_EXIT:
        rpc.clear()
        rpc.close()
        return
    key = None
    message = "Idling"
    scene = obs.obs_frontend_get_current_scene()
    if obs.obs_frontend_streaming_active():
        key = 'play_button'
        message = "Streaming"
    if obs.obs_frontend_recording_active():
        key = 'record'
        message = "Recording"
    if obs.obs_frontend_recording_active(
    ) and obs.obs_frontend_streaming_active():
        message = "Streaming and Recording"
    rpc.update(state=message,
コード例 #12
0
 def __init__(self, client_id, pid):
     self.pid = pid
     self.id = client_id
     self.RPC = Presence(self.id, pipe=0)
     self.timeout = 5
     self.thread = None
コード例 #13
0
def GetWeather():
    response = requests.get(URL)
    data = response.json()
    if data['cod'] != 404:
        weather_description = data['weather'][0]['description']
        icon = data['weather'][0]['icon']
        temp = data['main']['temp_min']
        wind = data['wind']['speed']
        humidity = data['main']['humidity']
        return [weather_description, str(temp), icon, str(wind), str(humidity)]
    else:
        return None


if __name__ == '__main__':
    RPC = Presence(CLIENT_ID)
    RPC.connect()

    while True:
        data = GetWeather()
        print(
            RPC.update(state=data[0],
                       details=data[1] + '°F',
                       large_image=data[2],
                       buttons=[{
                           'label': 'Wind 💨: ' + data[3] + ' mph',
                           'url': 'https://github.com/allistairhakim'
                       }, {
                           'label': 'Humidity 🌧️: ' + data[4] + '%',
                           'url': 'https://github.com/allistairhakim'
                       }]))
コード例 #14
0
ファイル: mkwii.py プロジェクト: dotcomboom/mkwii-presence
    cfg_file.close()

if not "friendCode" in config.keys():
    config["friendCode"] = "None"
if not "watchURL" in config.keys():
    config["watchURL"] = "https://wiimmfi.de/mkw/room/p232091239"

if not "client_id" in config.keys():
    config["client_id"] = "662481965840072717"

print("Friend code: " + str(config["friendCode"]))
print("Watch URL: " + str(config["watchURL"]))
print("Client ID: " + str(config["client_id"]))

print()
RPC = Presence(config["client_id"])
RPC.connect()
print("Rich presence connected!")

html = ''

while True:
    details = None
    state = config["friendCode"]
    party_size = None
    large_image = "mario"
    track = None

    try:
        html = requests.get(config["watchURL"]).text
    except:
コード例 #15
0
ファイル: ezdiscordrpc.py プロジェクト: syynicl/ezdiscordrpc
try:
    # Import modules
    from pypresence import Presence
    import time

    # Connect to Discord
    cid = int(input('RPC Client ID: '))
    rpc = Presence(cid)
    rpc.connect()

    # Set RPC
    rpc.update(small_image='small', large_image='large')
    print('RPC set successfully.')

    # Update RPC every 15 seconds
    while True:
        time.sleep(15)

# Custom KeyboardInterrupt message
except KeyboardInterrupt:
    print('\nProgram stopped using Ctrl+C.')
コード例 #16
0
ファイル: pyrpHearts.py プロジェクト: notjl/pyrphearts
                'KH2': 'KINGDOM HEARTS II FINAL MIX.exe',
                'KHBbS': 'KINGDOM HEARTS Birth by Sleep FINAL MIX.exe',
                'KH3': 'KINGDOM HEARTS III.exe',
                'KHL': 'KINGDOM HEARTS HD 1.5+2.5 Launcher.exe',
                'KHM': 'KINGDOM HEARTS HD 1.5+2.5 ReMIX.exe'
                }
IMAGES = {'KH1': 'kh', 'KHCoM': 'khcom', 'KH2': 'kh2', 'KHBbS': 'kh1_5_2_5',
          'KHL': 'kh1_5_2_5', 'KH12': 'kh1_5_2_5', 'KH3': 'kh3', 'KHH': 'khh'
          }
paths = {'KH12': f'{os.path.abspath(os.getcwd())}\KINGDOM HEARTS HD 1.5+2.5 ReMIX.exe',
         'KH3': f'{os.path.abspath(os.getcwd())}\KINGDOM HEARTS III.exe'}

logging.basicConfig(filename='pyrp.log', filemode='w',
                    format='[%(asctime)s]%(levelname)s:\n%(message)s',
                    level=logging.DEBUG)
rpc = Presence()

config_file = 'config.ini'
config = ConfigParser()
config.read(config_file)

if config['Program']['KH12']:
    paths['KH12'] = config['Program']['KH12']

if config['Program']['KH12']:
    paths['KH3'] = config['Program']['KH3']

state = "KINGDOM HEARTS 1.5 and 2.5 ReMIX" if config[
    'State']['KH12'] == '<True>' else "KINGDOM HEARTS III"
logging.info('Running pyrp')
logging.info(f'State: {state} ')
コード例 #17
0
from pypresence import Presence
from threading import Thread
import constants, time, glob, os, sys

rpcClient = Presence('592845025331642389')
rpcClient.connect()

startTime = int(time.time())
isTest = '--test' in sys.argv


def scanLogFile():
    clientType = 'ToontownOnline_TEST' if isTest else 'ToontownOnline'

    directory = 'C:/Program Files (x86)/Disney/Disney Online/{0}'.format(
        clientType)

    newest = max(glob.iglob(directory + '/*.log'), key=os.path.getctime)
    print(constants.READING_LOG.format(newest))

    logFile = open(newest)

    logLines = followLog(logFile)

    haveZone = False
    shardName = 'Unknown Shard'

    for line in logLines:
        if constants.OTP_ENTERING_SHARD in line:
            shardLine = line.split(constants.COMMAND_SPACE)
            shardId = shardLine[-1].rstrip()
コード例 #18
0
try:
	from pypresence import Client as Presence
except:
	import os
	os.system("python -m pip install pypresence")
	from pypresence import Client as Presence
import time
CONF_FILE = "discord_presence.conf"
RPC = Presence(750271599248408606)
print("reading config file...")
import configparser
config = configparser.ConfigParser()
if not CONF_FILE in config.read(CONF_FILE):
	print("config file not found,create conf file...")
	config["BUTTONS"] = {"button_example":"https://natribu.org/ru/"}
	config["DESC"] = {"desc":"example of desc"}
	with open(CONF_FILE, 'w') as configfile:
		config.write(configfile)
buttons = []
buttons_tmp = dict()
desc = None
if "BUTTONS" in config:
	for key in config["BUTTONS"]:
		buttons_tmp["label"] = key
		buttons_tmp["url"] = config["BUTTONS"][key]
		buttons.append(buttons_tmp)
		buttons_tmp = dict()
else:
	buttons = None
if "DESC" in config:
	desc = list(config["DESC"].keys())[0]
コード例 #19
0
 def __init__(self, filename):
     self.rp = Presence(CLIENT_ID)
     self.config_file_name = filename
     self.config = None
     self.embeds = None
     self.i = 0
コード例 #20
0
from pypresence import Presence
import time
import requests

client_id = ""
rpc = Presence(client_id)
rpc.connect()

url = "https://r-a-d.io/api"
rpc.clear()

while True:
    r = requests.get(url=url)
    data = r.json()
    np = data['main']['np']
    dj = data['main']['dj']['djname']
    dj_image = data['main']['dj']['djimage']
    thread = data['main']['thread']
    if dj == "Hanyuu-sama":
        large_image = "hanyuu"
    elif dj == "Claud":
        large_image = "claud"
    elif dj == "apt-get":
        large_image = "apt-get"
    elif dj == "kipukun":
        large_image = "kipukun"
    elif dj == "Suzubrah":
        large_image = "suzubrah"
    elif dj == "exci":
        large_image = "exci"
    elif dj == "Wessie":
コード例 #21
0
        print(f'\n\x1b[38;5;213m[\033[37m!\x1b[38;5;213m]\033[37m Creating Channels..')
        
        for i in range(channel_amount):
            createchan = functools.partial(Seraph.CreateChannel, guild.id)

            Thread(target=createchan).start()
        
        time.sleep(2)
        await menu()

    if choice == "9":
        print(f'\n\x1b[38;5;213m[\033[37m?\x1b[38;5;213m]\033[37m Type \x1b[38;5;213m{prefix}scrape\033[37m in the Guild that you want to Scrape.\n')


try:
    RPC = Presence("801856024088281088") 
    RPC.connect() 

    RPC.update(details="Main Menu", large_image="seraph", small_image="seraph", large_text="Seraph Nuker", start=time.time())
except:
    pass

@client.event
async def on_ready():
    if token_type == "bot":
        #try:
            await menu()
        #except:
            #pass

@client.event
コード例 #22
0
import pylast
from pypresence import Presence
import time
import variables as var

network = pylast.LastFMNetwork(api_key=var.key, api_secret=var.secret)
user = network.get_user(var.username)
RPC = Presence("748506372215275640")
RPC.connect()
genre_blacklist = ["seen live", "soundtrack", "female vocalists","nsbm","composer","video game music","robertitus global","boner inducing","takeshi kobayashi", "silent hill", "za rus v rot ebus", "underground", "usa","anime", "rac"]
countries = ["afghanistan","åland islands","albania","algeria","american samoa","andorra","angola","anguilla","antarctica","antigua & barbuda","argentina","armenia","aruba","australia","austria","azerbaijan","bahamas","bahrain","bangladesh","barbados","belarus","belgium","belize","benin","bermuda","bhutan","bolivia","bosnia & herzegovina","botswana","bouvet island","brazil","british indian ocean territory","british virgin islands","brunei","bulgaria","burkina faso","burundi","cambodia","cameroon","canada","cape verde","caribbean netherlands","cayman islands","central african republic","chad","chile","china","christmas island","cocos (keeling) islands","colombia","comoros","congo - brazzaville","congo - kinshasa","cook islands","costa rica","côte d’ivoire","croatia","cuba","curaçao","cyprus","czechia","denmark","djibouti","dominica","dominican republic","ecuador","egypt","el salvador","equatorial guinea","eritrea","estonia","eswatini","ethiopia","falkland islands","faroe islands","fiji","finland","france","french guiana","french polynesia","french southern territories","gabon","gambia","georgia","germany","ghana","gibraltar","greece","greenland","grenada","guadeloupe","guam","guatemala","guernsey","guinea","guinea-bissau","guyana","haiti","heard & mcdonald islands","honduras","hong kong sar china","hungary","iceland","india","indonesia","iran","iraq","ireland","isle of man","israel","italy","jamaica","japan","jersey","jordan","kazakhstan","kenya","kiribati","kuwait","kyrgyzstan","laos","latvia","lebanon","lesotho","liberia","libya","liechtenstein","lithuania","luxembourg","macao sar china","madagascar","malawi","malaysia","maldives","mali","malta","marshall islands","martinique","mauritania","mauritius","mayotte","mexico","micronesia","moldova","monaco","mongolia","montenegro","montserrat","morocco","mozambique","myanmar (burma)","namibia","nauru","nepal","netherlands","nederlands","new caledonia","new zealand","nicaragua","niger","nigeria","niue","norfolk island","north korea","north macedonia","northern mariana islands","norway","oman","pakistan","palau","palestinian territories","panama","papua new guinea","paraguay","peru","philippines","pitcairn islands","poland","portugal","puerto rico","qatar","réunion","romania","russia","rwanda","samoa","san marino","são tomé & príncipe","saudi arabia","senegal","serbia","seychelles","sierra leone","singapore","sint maarten","slovakia","slovenia","solomon islands","somalia","south africa","south georgia & south sandwich islands","south korea","south sudan","spain","sri lanka","st. barthélemy","st. helena","st. kitts & nevis","st. lucia","st. martin","st. pierre & miquelon","st. vincent & grenadines","sudan","suriname","svalbard & jan mayen","sweden","switzerland","syria","taiwan","tajikistan","tanzania","thailand","timor-leste","togo","tokelau","tonga","trinidad & tobago","tunisia","turkey","turkmenistan","turks & caicos islands","tuvalu","u.s. outlying islands","u.s. virgin islands","uganda","ukraine","united arab emirates","united kingdom","united states","uruguay","uzbekistan","vanuatu","vatican city","venezuela","vietnam","wallis & futuna","western sahara","yemen","zambia","zimbabwe"]
nationalities = ['afghan', 'albanian', 'algerian', 'american', 'andorran', 'angolan', 'antiguans', 'arabic', 'argentinean', 'armenian', 'australian', 'austrian', 'azerbaijani', 'bahamian', 'bahraini', 'bangladeshi', 'barbadian', 'barbudans', 'batswana', 'belarusian', 'belgian', 'belizean', 'beninese', 'bhutanese', 'bolivian', 'bosnian', 'brazilian', 'british', 'bruneian', 'bulgarian', 'burkinabe', 'burmese', 'burundian', 'cambodian', 'cameroonian', 'canadian', 'cape verdean', 'central african', 'chadian', 'chilean', 'chinese', 'colombian', 'comoran',  'congolese', 'costa rican', 'croatian', 'cuban', 'cypriot', 'czech', 'danish', 'djibouti', 'dominican', 'dutch', 'dutchman', 'dutchwoman', 'east timorese', 'ecuadorean', 'egyptian', 'emirian', 'equatorial guinean', 'eritrean', 'estonian', 'ethiopian', 'fijian', 'filipino', 'finnish', 'french', 'gabonese', 'gambian', 'georgian', 'german', 'ghanaian', 'greek', 'grenadian', 'guatemalan', 'guinea-bissauan', 'guinean', 'guyanese', 'haitian', 'herzegovinian', 'honduran', 'hungarian', 'i-kiribati', 'icelander', 'indian', 'indonesian', 'iranian', 'iraqi', 'irish', 'israeli', 'italian', 'ivorian', 'jamaican', 'japanese', 'jordanian', 'kazakhstani', 'kenyan', 'kittian and nevisian', 'kuwaiti', 'kyrgyz', 'laotian', 'latvian', 'lebanese', 'liberian', 'libyan', 'liechtensteiner', 'lithuanian', 'luxembourger', 'macedonian', 'malagasy', 'malawian', 'malaysian', 'maldivan', 'malian', 'maltese', 'marshallese', 'mauritanian', 'mauritian', 'mexican', 'micronesian', 'moldovan', 'monacan', 'mongolian', 'moroccan', 'mosotho', 'motswana', 'mozambican', 'namibian', 'nauruan', 'nepalese', 'netherlander', 'new zealander', 'ni-vanuatu', 'nicaraguan', 'nigerian', 'nigerien', 'north korean', 'northern irish', 'norwegian', 'omani', 'pakistani', 'palauan', 'panamanian', 'papua new guinean', 'paraguayan', 'peruvian', 'polish', 'portuguese', 'qatari', 'romanian', 'russian', 'rwandan', 'saint lucian', 'salvadoran', 'samoan', 'san marinese', 'sao tomean', 'saudi', 'scottish', 'senegalese', 'serbian', 'seychellois', 'sierra leonean', 'singaporean', 'slovakian', 'slovenian', 'solomon islander', 'somali', 'south african', 'south korean', 'spanish', 'sri lankan', 'sudanese', 'surinamer', 'swazi', 'swedish', 'swiss', 'syrian', 'taiwanese', 'tajik', 'tanzanian', 'thai', 'togolese', 'tongan', 'trinidadian or tobagonian', 'tunisian', 'turkish', 'tuvaluan', 'ugandan', 'ukrainian', 'uruguayan', 'uzbekistani', 'venezuelan', 'vietnamese', 'welsh', 'yemenite', 'zambian', 'zimbabwean']
genre_blacklist += countries + nationalities

t = False

def get_info(track):
    artist = network.get_artist(track.artist)

    if not(artist):
        return "unknown genre"

    if "acoustic" in track.title.lower():
        genren = "acoustic"
        print("Genres: acoustic")

    else:
        try:    
            genre = artist.get_top_tags()
        except:
            return "unknown genre"
コード例 #23
0
# A TF2 RPC script by EmeraldSnorlax
# https://github.com/EmeraldSnorlax
# https://steamcommunity.com/id/EmeraldSnorlax/
#

import tkinter
import easygui as gui
import os
import time
import sys
from pypresence import Presence
import tailer

# RPC Client ID. Do not change.
CLIENT_ID = '635786070625091584'
RPC = Presence(client_id=CLIENT_ID)
RPC.connect()


def msg(text):
    gui.msgbox(text, 'TF2 RPC')


# Grab the log file from tf_path.txt. Encoding is utterly scuffed, for some reason. Perhaps it's just my machine...
f = open('tf_path.txt', 'r', encoding="ISO-8859-15")
tf_folder = f.read()
log_file = tf_folder.rstrip('\n') + 'tf/console.log'
f.close()

# Check if the log file actually exists.
if os.path.isfile(log_file):
コード例 #24
0
def start_mainloop():
    logging.info('Mainloop started')

    count = 0

    rpc = Presence(CLIENT_ID)
    rpc.connect()

    lichess = Lichess(config.get_lichess_username())
    chesscom = Chesscom(config.get_chesscom_username())

    platforms = []

    while states.running:

        updated = False

        lichess.update_username(config.get_lichess_username())
        chesscom.update_username(config.get_chesscom_username())

        if lichess.is_available():
            platforms.append(lichess)

        if chesscom.is_available():
            print('available', chesscom.username)
            platforms.append(chesscom)

        print(platforms)

        if len(platforms) == 0:
            logging.warning('Missing information -> update config')
            rpc.clear()
            utils.open_webpage()

            while config.get_temp_data() == {} or all(
                    config.get_temp_data()[key] is None
                    for key in config.get_temp_data()):
                time.sleep(1)
            else:
                continue

        count += 1
        logging.info(f'Presence updated ({count})')

        for platform in platforms:

            platform.update_data()

            status = platform.get_status()

            if status is OFFLINE:
                continue

            if status is PLAYING:
                platform.display_playing(rpc)
                updated = True
                break

            if status is ONLINE:
                platform.display_online(rpc)
                updated = True
                break

        if not updated:
            rpc.clear()

        platforms.clear()
        time.sleep(15)

    rpc.clear()
    logging.info('Mainloop ended')
コード例 #25
0
def main():
    logger.info("Checking for updates...")
    os.system("git pull")
    logger.info(
        "If updates were done, restart this script by using CTRL-C to terminate it, and re run it."
    )

    # Make connection to Discord
    try:
        RPC = Presence(client_id)  # Initialize the Presence class
        RPC.connect()  # Start the handshake loop
    except pypresence.exceptions.InvalidPipe:
        logger.error(
            "Could not connect to the discord pipe. Please ensure it's running."
        )
        exit(1)
    except FileNotFoundError:
        logger.error(
            "Could not connect to the discord pipe. Please ensure it's running."
        )
        exit(1)

    # Load our current config
    config = nso_functions.get_config_file()
    logger.info("Check discord!")

    # Get friend code from config, and add config option if does not exist
    try:
        friend_code = config['friend_code']
    except KeyError:
        config['friend_code'] = 'Unset'
        config_f = open("config.txt", "w")
        config_f.write(json.dumps(
            config,
            sort_keys=True,
            indent=4,
        ))
        config_f.close()
        friend_code = config['friend_code']

    while True:  # The presence will stay on as long as the program is running

        for i in range(0, 5):
            minutes_since, last_match = get_minutes_since()

            # Calculating the secs/hours/days since Last Match/Run
            seconds_since = int(minutes_since * 60)
            hours_since = int(minutes_since / 60)
            days_since = int(minutes_since / 1440)

            # When Previous Match was Salmon Run
            # job_result is only present in salmon run JSON
            if last_match.get('job_result') is not None:

                # Sets Gamemode Key in order to change the Picture
                gamemode_key = "salmon_run"

                # Decides if last Run is shown in days, hours, minutes or seconds
                # In Days
                if minutes_since >= 1440:
                    details = "Last Run: {} day{} ago".format(
                        days_since, plural_logic(days_since))

                # In Hours
                elif minutes_since >= 60:
                    details = "Last Run: {} h{} ago".format(
                        hours_since, plural_logic(hours_since))

                # In Minutes
                elif minutes_since > 1:
                    details = "Last Run: {} min{} ago".format(
                        math.floor(minutes_since),
                        plural_logic(math.floor(minutes_since)))

                # In Seconds
                else:
                    details = "Last Run: {} sec{} ago".format(
                        seconds_since, plural_logic(seconds_since))

                # Deciding the Result
                if last_match['job_result']['is_clear']:
                    outcome = "WON"
                else:
                    outcome = "LOST"

                ### Checks how many waves were played on last Run
                # If all 3 Waves were played
                if last_match["wave_details"][2]:
                    goldEgg = last_match["wave_details"][0]["golden_ikura_num"] + \
                        last_match["wave_details"][1]["golden_ikura_num"] + \
                        last_match["wave_details"][2]["golden_ikura_num"]
                    powEgg = last_match["wave_details"][0]["ikura_num"] + \
                        last_match["wave_details"][1]["ikura_num"] + \
                        last_match["wave_details"][2]["ikura_num"]

                # If only 2 Waves were played
                elif not last_match["wave_details"][2] and last_match[
                        "wave_details"][1]:
                    goldEgg = last_match["wave_details"][0][
                        "golden_ikura_num"] + last_match["wave_details"][1][
                            "golden_ikura_num"]
                    powEgg = last_match["wave_details"][0][
                        "ikura_num"] + last_match["wave_details"][1][
                            "ikura_num"]

                # If only 1 Wave was played
                else:
                    goldEgg = last_match["wave_details"][0]["golden_ikura_num"]
                    powEgg = last_match["wave_details"][0]["ikura_num"]

                # When hovering on the Picture
                large_text = "Last match was Salmon Run on {}".format(
                    last_match['schedule']['stage']['name'])

                # IGN and Salmon Run Rank
                if i == 0:
                    details = "IGN: {}".format(last_match["my_result"]["name"])
                    state = "{} {}".format((last_match["grade"])["long_name"],
                                           last_match["grade_point"])

                # Friend code
                elif i == 1:
                    if not friend_code:
                        state = "FC: Not Given"
                    else:
                        state = "FC: {}".format(friend_code)

                # Hazard Level
                elif i == 2:
                    state = "Hazard Level: {}".format(
                        str(last_match["danger_rate"]) + "%")

                # Result and Total Collected Golden Eggs / Power Eggs
                elif i == 3:
                    details = "GoldEgg/PowEgg ({})".format(outcome)

                    state = "{} / {}".format(goldEgg, powEgg)

                # Save / Death Ratio
                elif i == 4:
                    state = "Save/Death Ratio: {}/{}".format(
                        last_match["my_result"]["help_count"],
                        last_match["my_result"]["dead_count"])

                if minutes_since < timeout_minutes:
                    RPC.update(details=details,
                               state=state,
                               large_image=gamemode_key,
                               small_image="default",
                               large_text=large_text)
                else:
                    RPC.clear()
                    logger.debug("RPC cleared, not in game long enough")
                time.sleep(time_interval)

            # When Previous Match was Turf, Ranked, League or Private
            else:

                # Decides if last Match is shown in days, hours, minutes or seconds
                # In Days
                if minutes_since >= 1440:
                    details = "Last Match: {} day{} ago".format(
                        days_since, plural_logic(days_since))

                # In Hours
                elif minutes_since >= 60:
                    details = "Last Match: {} h{} ago".format(
                        hours_since, plural_logic(hours_since))

                # In Minutes
                elif minutes_since > 1:
                    details = "Last Match: {} min{} ago".format(
                        math.floor(minutes_since),
                        plural_logic(math.floor(minutes_since)))

                # In Seconds
                else:
                    details = "Last Match: {} sec{} ago".format(
                        seconds_since, plural_logic(seconds_since))

                # When hovering on the Picture
                large_text = "Last match was {}, {} on {}".format(
                    last_match["game_mode"]["name"],
                    last_match["rule"]["name"], last_match["stage"]["name"])

                # Gets Gamemode Key in order to change the Picture
                gamemode_key = last_match["rule"]["key"]

                # Gets Lobby Key
                lobby_key = last_match["game_mode"]["key"]

                # IGN and Level (+ Rank)
                if i == 0:
                    details = "IGN: {}".format(
                        last_match["player_result"]["player"]["nickname"])

                    # Checks if player has a Level Star
                    # If player has no Level Star (yet XP)
                    if not last_match["star_rank"]:

                        # If last match was in a Regular Lobby (Turf War) or Private Lobby
                        if lobby_key == "regular" or lobby_key == "private":
                            state = "Level: {}".format(
                                last_match["player_result"]["player"]
                                ["player_rank"], )

                        # If last match was in a Ranked Solo Lobby
                        elif lobby_key == "gachi":

                            # If last match was Splat Zones
                            if gamemode_key == "splat_zones":

                                # If player has S+ Rank
                                if last_match["udemae"]["name"] == "S+":
                                    state = "Lvl: {}/R(SZ): {}{}".format(
                                        last_match["player_result"]["player"]
                                        ["player_rank"],
                                        last_match["udemae"]["name"],
                                        last_match["udemae"]["s_plus_number"])

                                # If player has X Rank
                                elif last_match["udemae"]["name"] == "X":

                                    # Checks if Player has any X Power
                                    # If Player has no X Power (yet XP)
                                    if not last_match["x_power"]:
                                        state = "Lvl: {}/R(SZ): X(TBD)".format(
                                            last_match["player_result"]
                                            ["player"]["player_rank"], )

                                    # If Player has X Power
                                    else:
                                        state = "Lvl: {}/R(SZ): X({})".format(
                                            last_match["player_result"]
                                            ["player"]["player_rank"],
                                            last_match["x_power"])

                                # If player has other Ranks
                                else:
                                    state = "Lvl: {}/R(SZ): {}".format(
                                        last_match["player_result"]["player"]
                                        ["player_rank"],
                                        last_match["udemae"]["name"])

                            # If last match was Tower Control
                            elif gamemode_key == "tower_control":

                                # If player has S+ Rank
                                if last_match["udemae"]["name"] == "S+":
                                    state = "Lvl: {}/R(TC): {}{}".format(
                                        last_match["player_result"]["player"]
                                        ["player_rank"],
                                        last_match["udemae"]["name"],
                                        last_match["udemae"]["s_plus_number"])

                                # If player has X Rank
                                elif last_match["udemae"]["name"] == "X":

                                    # Checks if Player has any X Power
                                    # If Player has no X Power (yet XP)
                                    if not last_match["x_power"]:
                                        state = "Lvl: {}/R(TC): X(TBD)".format(
                                            last_match["player_result"]
                                            ["player"]["player_rank"], )

                                    # If Player has X Power
                                    else:
                                        state = "Lvl: {}/R(TC): X({})".format(
                                            last_match["player_result"]
                                            ["player"]["player_rank"],
                                            last_match["x_power"])

                                # If player has other Ranks
                                else:
                                    state = "Lvl: {}/R(TC): {}".format(
                                        last_match["player_result"]["player"]
                                        ["player_rank"],
                                        last_match["udemae"]["name"])

                            # If last match was Rainmaker
                            elif gamemode_key == "rainmaker":

                                # If player has S+ Rank
                                if last_match["udemae"]["name"] == "S+":
                                    state = "Lvl: {}/R(RM): {}{}".format(
                                        last_match["player_result"]["player"]
                                        ["player_rank"],
                                        last_match["udemae"]["name"],
                                        last_match["udemae"]["s_plus_number"])

                                # If player has X Rank
                                elif last_match["udemae"]["name"] == "X":

                                    # Checks if Player has any X Power
                                    # If Player has no X Power (yet XP)
                                    if not last_match["x_power"]:
                                        state = "Lvl: {}/R(RM): X(TBD)".format(
                                            last_match["player_result"]
                                            ["player"]["player_rank"], )

                                    # If Player has X Power
                                    else:
                                        state = "Lvl: {}/R(RM): X({})".format(
                                            last_match["player_result"]
                                            ["player"]["player_rank"],
                                            last_match["x_power"])

                                # If player has other Ranks
                                else:
                                    state = "Lvl: {}/R(RM): {}".format(
                                        last_match["player_result"]["player"]
                                        ["player_rank"],
                                        last_match["udemae"]["name"])

                            # If last match was Clam Blitz
                            else:

                                # If player has S+ Rank
                                if last_match["udemae"]["name"] == "S+":
                                    state = "Lvl: {}/R(CB): {}{}".format(
                                        last_match["player_result"]["player"]
                                        ["player_rank"],
                                        last_match["udemae"]["name"],
                                        last_match["udemae"]["s_plus_number"])

                                # If player has X Rank
                                elif last_match["udemae"]["name"] == "X":

                                    # Checks if Player has any X Power
                                    # If Player has no X Power (yet XP)
                                    if not last_match["x_power"]:
                                        state = "Lvl: {}/R(CB): X(TBD)".format(
                                            last_match["player_result"]
                                            ["player"]["player_rank"], )

                                    # If Player has X Power
                                    else:
                                        state = "Lvl: {}/R(CB): X({})".format(
                                            last_match["player_result"]
                                            ["player"]["player_rank"],
                                            last_match["x_power"])

                                # If player has other Ranks
                                else:
                                    state = "Lvl: {}/R(CB): {}".format(
                                        last_match["player_result"]["player"]
                                        ["player_rank"],
                                        last_match["udemae"]["name"])

                        # If last match was in a League Pair/Team Lobby
                        elif lobby_key == "league_pair" or lobby_key == "league_team":

                            # Checks if Player has League Power
                            # If Player has no League Power (yet XP)
                            if not last_match["league_point"]:
                                state = "Lvl: {}/Power: TBD".format(
                                    last_match["player_result"]["player"]
                                    ["player_rank"])

                            # If Player has League Power
                            else:
                                state = "Lvl: {}/Power: {}".format(
                                    last_match["player_result"]["player"]
                                    ["player_rank"],
                                    last_match["league_point"])

                    # If player has a Level Star
                    else:

                        # If last match was in a Regular Lobby (Turf War) or Private Lobby
                        if lobby_key == "regular" or lobby_key == "private":
                            state = "Level: {}☆{}".format(
                                last_match["player_result"]["player"]
                                ["player_rank"],
                                last_match["player_result"]["player"]
                                ["star_rank"],
                            )

                        # If last match was in a Ranked Solo Lobby
                        elif lobby_key == "gachi":

                            # If last match was Splat Zones
                            if gamemode_key == "splat_zones":

                                # If player has S+ Rank
                                if last_match["udemae"]["name"] == "S+":
                                    state = "Lvl: {}☆{}/R(SZ): {}{}".format(
                                        last_match["player_result"]["player"]
                                        ["player_rank"],
                                        last_match["player_result"]["player"]
                                        ["star_rank"],
                                        last_match["udemae"]["name"],
                                        last_match["udemae"]["s_plus_number"])

                                # If player has X Rank
                                elif last_match["udemae"]["name"] == "X":

                                    # Checks if Player has any X Power
                                    # If Player has no X Power (yet XP)
                                    if not last_match["x_power"]:
                                        state = "Lvl: {}☆{}/R(SZ): X(TBD)".format(
                                            last_match["player_result"]
                                            ["player"]["player_rank"],
                                            last_match["player_result"]
                                            ["player"]["star_rank"],
                                        )

                                    # If Player has X Power
                                    else:
                                        state = "Lvl: {}☆{}/R(SZ): X({})".format(
                                            last_match["player_result"]
                                            ["player"]["player_rank"],
                                            last_match["player_result"]
                                            ["player"]["star_rank"],
                                            last_match["x_power"])

                                # If player has other Ranks
                                else:
                                    state = "Lvl: {}☆{}/R(SZ): {}".format(
                                        last_match["player_result"]["player"]
                                        ["player_rank"],
                                        last_match["player_result"]["player"]
                                        ["star_rank"],
                                        last_match["udemae"]["name"])

                            # If last match was Tower Control
                            elif gamemode_key == "tower_control":

                                # If player has S+ Rank
                                if last_match["udemae"]["name"] == "S+":
                                    state = "Lvl: {}☆{}/R(TC): {}{}".format(
                                        last_match["player_result"]["player"]
                                        ["player_rank"],
                                        last_match["player_result"]["player"]
                                        ["star_rank"],
                                        last_match["udemae"]["name"],
                                        last_match["udemae"]["s_plus_number"])

                                # If player has X Rank
                                elif last_match["udemae"]["name"] == "X":

                                    # Checks if Player has any X Power
                                    # If Player has no X Power (yet XP)
                                    if not last_match["x_power"]:
                                        state = "Lvl: {}☆{}/R(TC): X(TBD)".format(
                                            last_match["player_result"]
                                            ["player"]["player_rank"],
                                            last_match["player_result"]
                                            ["player"]["star_rank"],
                                        )

                                    # If Player has X Power
                                    else:
                                        state = "Lvl: {}☆{}/R(TC): X({})".format(
                                            last_match["player_result"]
                                            ["player"]["player_rank"],
                                            last_match["player_result"]
                                            ["player"]["star_rank"],
                                            last_match["x_power"])

                                # If player has other Ranks
                                else:
                                    state = "Lvl: {}☆{}/R(TC): {}".format(
                                        last_match["player_result"]["player"]
                                        ["player_rank"],
                                        last_match["player_result"]["player"]
                                        ["star_rank"],
                                        last_match["udemae"]["name"])

                            # If last match was Rainmaker
                            elif gamemode_key == "rainmaker":

                                # If player has S+ Rank
                                if last_match["udemae"]["name"] == "S+":
                                    state = "Lvl: {}☆{}/R(RM): {}{}".format(
                                        last_match["player_result"]["player"]
                                        ["player_rank"],
                                        last_match["player_result"]["player"]
                                        ["star_rank"],
                                        last_match["udemae"]["name"],
                                        last_match["udemae"]["s_plus_number"])

                                # If player has X Rank
                                elif last_match["udemae"]["name"] == "X":

                                    # Checks if Player has any X Power
                                    # If Player has no X Power (yet XP)
                                    if not last_match["x_power"]:
                                        state = "Lvl: {}☆{}/R(RM): X(TBD)".format(
                                            last_match["player_result"]
                                            ["player"]["player_rank"],
                                            last_match["player_result"]
                                            ["player"]["star_rank"],
                                        )

                                    # If Player has X Power
                                    else:
                                        state = "Lvl: {}☆{}/R(RM): X({})".format(
                                            last_match["player_result"]
                                            ["player"]["player_rank"],
                                            last_match["player_result"]
                                            ["player"]["star_rank"],
                                            last_match["x_power"])

                                # If player has other Ranks
                                else:
                                    state = "Lvl: {}☆{}/R(RM): {}".format(
                                        last_match["player_result"]["player"]
                                        ["player_rank"],
                                        last_match["player_result"]["player"]
                                        ["star_rank"],
                                        last_match["udemae"]["name"])

                            # If last match was Clam Blitz
                            elif gamemode_key == "clam_blitz":

                                # If player has S+ Rank
                                if last_match["udemae"]["name"] == "S+":
                                    state = "Lvl: {}☆{}/R(CZ): {}{}".format(
                                        last_match["player_result"]["player"]
                                        ["player_rank"],
                                        last_match["player_result"]["player"]
                                        ["star_rank"],
                                        last_match["udemae"]["name"],
                                        last_match["udemae"]["s_plus_number"])

                                # If player has X Rank
                                elif last_match["udemae"]["name"] == "X":

                                    # Checks if Player has any X Power
                                    # If Player has no X Power (yet XP)
                                    if not last_match["x_power"]:
                                        state = "Lvl: {}☆{}/R(CZ): X(TBD)".format(
                                            last_match["player_result"]
                                            ["player"]["player_rank"],
                                            last_match["player_result"]
                                            ["player"]["star_rank"],
                                        )

                                    # If Player has X Power
                                    else:
                                        state = "Lvl: {}☆{}/R(CZ): X({})".format(
                                            last_match["player_result"]
                                            ["player"]["player_rank"],
                                            last_match["player_result"]
                                            ["player"]["star_rank"],
                                            last_match["x_power"])

                                # If player has other Ranks
                                else:
                                    state = "Lvl: {}☆{}/R(CZ): {}".format(
                                        last_match["player_result"]["player"]
                                        ["player_rank"],
                                        last_match["player_result"]["player"]
                                        ["star_rank"],
                                        last_match["udemae"]["name"])

                        # If last match was in a League Pair/Team Lobby
                        elif lobby_key == "league_pair" or lobby_key == "league_team":

                            # Checks if Player has League Power
                            # If Player has no League Power (yet XP)
                            if not last_match["league_point"]:
                                state = "Lvl: {}☆{}/Power: TBD".format(
                                    last_match["player_result"]["player"]
                                    ["player_rank"],
                                    last_match["player_result"]["player"]
                                    ["star_rank"],
                                )

                            # If Player has League Power
                            else:
                                state = "Lvl: {}☆{}/Power: {}".format(
                                    last_match["player_result"]["player"]
                                    ["player_rank"],
                                    last_match["player_result"]["player"]
                                    ["star_rank"], last_match["league_point"])

                # Friend Code
                elif i == 1:
                    if not friend_code:
                        state = "FC: Not Given"
                    else:
                        state = "FC: {}".format(friend_code)

                # Kill (Assist) / Death Ratio
                elif i == 2:
                    state = "K(A)/D: {}({})/{}".format(
                        last_match["player_result"]["kill_count"],
                        last_match["player_result"]["assist_count"],
                        last_match["player_result"]["death_count"])

                # Result and Percentages
                elif i == 3:
                    details = last_match["my_team_result"]["name"]
                    try:
                        state = "{}% vs {}%".format(
                            last_match["my_team_percentage"],
                            last_match["other_team_percentage"])
                    except KeyError:
                        try:
                            state = "{} vs {}".format(
                                last_match["my_team_count"],
                                last_match["other_team_count"])
                        except KeyError:
                            state = "Gamemode not yet supported"

                # Used Weapon and Total Points
                elif i == 4:
                    state = "{}p".format(
                        last_match["player_result"]["game_paint_point"])

                    if show_weapon:
                        details = "{}".format(last_match["player_result"]
                                              ["player"]["weapon"]["name"])
                    else:
                        pass

                if minutes_since < timeout_minutes:
                    RPC.update(details=details,
                               state=state,
                               large_image=gamemode_key,
                               small_image="default",
                               large_text=large_text)
                else:
                    RPC.clear()
                    logger.debug("RPC cleared, not in game long enough")
                time.sleep(time_interval)
コード例 #26
0
Options:
    --path=<path> Path to your PCSX2 directory, optional.

"""

__version__ = '0.1.0'

import getpass
import time

from docopt import docopt
from pypresence import Presence

from .utils import latest_game

presence = Presence('540759287379525632')
presence.connect()


def main():
    start = int(time.time())
    arguments = docopt(__doc__, version=f'discordrp_pcsx2 {__version__}')
    path = arguments.get('--path')
    if path is None:
        path = f'/home/{getpass.getuser()}/.config/PCSX2'
    while True:
        game = latest_game(path)
        presence.update(large_image=game.image,
                        large_text=game.description,
                        small_image='pcsx2',
                        small_text='PCSX2 Emulator',
コード例 #27
0
ファイル: pygdrpc.py プロジェクト: spookybear0/PyGDRPC
        print("Created conifg file! Please reopen the program to start")
        Wait(5, True)
        exit()

try:
    memory = gd.memory.get_memory()
except RuntimeError:
    print("Run GD first!")
    Wait(5, True)
    exit()

smallimage = "none"  # fallback in case of the difficulty face not being returned
client = gd.Client()
editorlevel = False
client_id = "703049428822655048"
RPC = Presence(client_id)
if data.get("logs") == "Visible": print("Connecting...")
RPC.connect()


async def get_difficulty(level: gd.Level) -> str:
    try:
        level = await client.get_level(lid)
    except gd.MissingAccess:
        editorlevel = True
    else:
        editorlevel = False
        base = level.difficulty.name.lower().split("_")
        if level.is_epic():
            base.append("epic")
        elif level.is_featured():
コード例 #28
0
if os.path.exists(os.getcwd() + '/config.json'):
    # if json file exist, read it!
    with open("./config.json") as f:
        configData = json.load(f)
else:
    # if json file not exist, create new one with these template
    configTemplate = {"Client_ID": ""}
    # write the template
    with open(os.getcwd() + '/config.json', 'w+') as f:
        json.dump(configTemplate, f, indent=4, sort_keys=False)

# Load uid on json
myClientID = configData["Client_ID"]

# Start the RPC
RPC = Presence(str(myClientID))
RPC.connect()

# Window
app = tk.Tk()  # Application Name
app.iconbitmap('E:\Icons\Applications\Icon.ico')
app.title("AX.Discord Rich Presence")  # Label
app.geometry("290x310")  # Size

# Label
label_state = ttk.Label(app, text="State:")  # Click event
label_state.place(x=5, y=5)

label_details = ttk.Label(app, text="Details:")  # Click event
label_details.place(x=5, y=50)  # +45
コード例 #29
0
    # get minutes since last match
    minutes_since = time_to_last_match.hour * 60 + \
        time_to_last_match.minute + time_to_last_match.second / 60
    return minutes_since


if __name__ == "__main__":
    logger.info("Checking for updates...")
    os.system("git pull")
    logger.info(
        "If updates were done, restart this script by using CTRL-C to terminate it, and re run it."
    )

    # Make connection to Discord
    try:
        RPC = Presence(client_id)  # Initialize the Presence class
        RPC.connect()  # Start the handshake loop
    except pypresence.exceptions.InvalidPipe:
        logger.error(
            "Could not connect to the discord pipe. Please ensure it's running."
        )
        exit(1)
    except FileNotFoundError:
        logger.error(
            "Could not connect to the discord pipe. Please ensure it's running."
        )
        exit(1)

    # Load our current config

    config = nso_functions.get_config_file()
コード例 #30
0
from pypresence import Presence
import handler
import time

client_id = "482150417455775755"
rich_presence = Presence(client_id)


def connect():
    return rich_presence.connect()


def connect_loop(retries=0):
    if retries > 10:
        return
    try:
        connect()
    except:
        print("Error connecting to Discord")
        time.sleep(10)
        retries += 1
        connect_loop(retries)
    else:
        update_loop()


print("Started Adobe RPC")


def update_loop():
    start_time = int(time.time())