Esempio n. 1
0
 def _reconnect(self):
     if not self._enabled:
         try:
             self._rpc = Client(self._client_id)
             self._rpc.start()
             self._enabled = True
         except self._errors:
             self._enabled = False
Esempio n. 2
0
def setup():
    client = Client(client_id)
    client.start()
    auth = client.authorize(client_id, ['rpc'])
    client.close()
    rpcToken = auth["data"]["code"]

    if rpcToken != None:
        headers = {
            "rpcToken": rpcToken,
        }
        user_object = requests.get("https://rich-presence-api.glitch.me/setup",
                                   headers=headers)
        if user_object.status_code == 200:
            user_json = user_object.json()

            with open(os.path.abspath(os.getcwd()) + '\data.json',
                      'w') as outfile:
                json.dump(user_json, outfile)

            return user_json
        else:
            raise RuntimeWarning("One or more of the apis errored.")
    else:
        raise RuntimeWarning("Error when obtaining RPC token.")
def main():
    while True:
        try:
            RPC = Client("806910592983367730")
            show_presence(RPC)
        except KeyboardInterrupt:
            exit()
        except:
            print("rpc connection failed")
Esempio n. 4
0
import signal


def signal_handler(signum, frame):
    raise Exception("TO")


cluster = MongoClient(
    f"mongodb+srv://kingszeto:{config.mongo_password}@cluster0.zfror.mongodb.net/<dbname>?retryWrites=true&w=majority"
)
db = cluster["rootwitch"]
collection = db["teams"]
party = collection.find({"_id": "tlwin2020"})[0]
print(party)
client_id = config.client_id
client = Client(client_id)

client.start()
client.subscribe("ACTIVITY_JOIN")

a = client.set_activity(pid=0, state=f"Watching {party['match']}",\
     details= f"Rooting for {party['team']}",\
     small_image=party['small'], small_text=party['match'],\
     large_image=party['big'], large_text=party['team'], start = time.time(),\
     party_size=[1,10000], party_id=party['_id']+'A', join=party['_id'])

print(a)
print("Begin Loop")
while True:
    time.sleep(1)
    signal.signal(signal.SIGALRM, signal_handler)
Esempio n. 5
0
def main():
    print("Starting RPC...")
    rpc = RPC(673133177274892290)
    rpc.start()

    try:
        start = None
        end = None
        pos = []
        est = "None"
        state = 0

        sys = system()  # Find Minecraft game dir
        if sys == "Windows":
            file = Path("AppData") / "Roaming" / ".minecraft"
        elif sys == "Darwin":
            file = Path("Library") / "Application Support" / "minecraft"
        elif sys == "Linux":
            file = ".minecraft"
        else:
            print("Unknown system, unable to find game dir")
        file = Path.home() / file / "logs" / "latest.log"

        with open(file
                  ) as f:  # TODO: Read previous logs if data is insufficient.
            while True:
                line = f.readline()
                if line:
                    text = line[11:-1]
                    try:
                        t = datetime.combine(date.today(),
                                             time.fromisoformat(
                                                 line[1:9])).timestamp()
                        if text.startswith("[main/INFO]: Connecting to "):
                            end = None
                            est = "None"
                            state = 1
                        elif text == "[main/INFO]: [CHAT] 2b2t is full":
                            start = int(t)
                            pos = []
                            state = 2
                        elif text.startswith(
                                "[main/INFO]: [CHAT] Position in queue: "):
                            p = int(text[39:])
                            pos.append((t, p))
                            if len(pos) == 61:
                                pos[0:1] = []

                            if len(pos) == 60:
                                if pos[0][1] == p:
                                    est = "never"
                                else:
                                    est = ""
                                    seconds = (t - pos[0][0]) / (
                                        pos[0][1] - p
                                    )  # FIXME: Time is negative when you're a time traveller.
                                    seconds = int(
                                        seconds *
                                        p)  # TODO: Rework the estimations.
                                    days = seconds // 86400
                                    if days:
                                        est += f"{days}d "
                                    hours = seconds % 86400 // 3600
                                    if hours:
                                        est += f"{hours}h "
                                    est += f"{seconds % 3600 // 60}m"

                            if state == 2:
                                state = 3
                        elif (text ==
                              "[main/INFO]: [CHAT] Connecting to the server..."
                              or text.startswith("[main/INFO]: Loaded ")):
                            pos = []
                            start = int(t)
                            state = 4
                        elif text.startswith(
                                "[main/INFO]: [CHAT] [SERVER] Server restarting in "
                        ):
                            if text.endswith(" minutes..."):
                                end = int(t) + 600 * int(text[50:-12])
                            elif text.endswith(" seconds..."):
                                end = int(t) + 10 * int(text[50:-11])
                            elif text.endswith(" second..."):
                                end = int(t) + 10 * int(text[50:-10])
                            state = 5
                        elif text == "[main/INFO]: Stopping!":
                            print("Hi!")
                            break
                    except ValueError:
                        pass
                else:
                    if state == 1:
                        rpc.set_activity(
                            large_image="image",
                            large_text="2b2t.org",
                            details="Connecting...",
                        )
                    elif state == 2:
                        rpc.set_activity(
                            large_image="image",
                            large_text="2b2t.org",
                            details="Waiting in queue",
                            start=start,
                        )
                    elif state == 3:
                        rpc.set_activity(
                            large_image="image",
                            large_text="2b2t.org",
                            details=f"Position in queue: {pos[-1][1]}",
                            state="Estimated time: " + est,
                            start=start,
                        )
                        sleep(10)
                    elif state == 4:
                        rpc.set_activity(
                            large_image="image",
                            large_text="2b2t.org",
                            details="Playing",
                            start=start,
                        )
                    elif state == 5:
                        rpc.set_activity(
                            large_image="image",
                            large_text="2b2t.org",
                            details=f"Waiting for restart...",
                            state=f"Position in queue: {pos[-1][1]}",
                            end=end,
                        )
                    if stat(f.fileno()).st_nlink == 0:
                        f.close()
                        f = open(file)
    except KeyboardInterrupt:
        pass
    finally:
        print("\nStopping RPC...")
        rpc.close()
from pypresence import Client
import time

client_id = "743296148592263240"
RPC = Client(client_id)
RPC.start()


def register_join_event(syncplay_join_group: callable):
    RPC.register_event('activity_join', syncplay_join_group)


def send_presence(
    title: str,
    subtitle: str,
    playback_time: float = None,
    duration: float = None,
    playing: bool = False,
    syncplay_group: str = None,
):
    small_image = "play-dark3" if playing else None
    start = None
    end = None
    if playback_time is not None and duration is not None and playing:
        start = int(time.time() - playback_time)
        end = int(start + duration)
    RPC.set_activity(
        state=subtitle,
        details=title,
        instance=False,
        large_image="jellyfin2",
Esempio n. 7
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]
Esempio n. 8
0
def main():
    def isDiscordRunning():
        counter = 0
        r = os.popen('tasklist /v').read().strip().split('\n')
        for i in range(len(r)):
            s = r[i]
            if "Discord.exe" in r[i]:
                counter = counter + 1
        if counter >= 4:
            return True
        else:
            return False

    client_id = "696685746832277534"

    previous = {
        "details": None,
        "state": None,
        "image": None,
        "gameSize": None,
        "gameId": None,
    }
    start = None
    activityCleared = True

    client = None
    ClientClosed = True

    try:
        with open(os.path.abspath(os.getcwd()) + '\data.json') as json_file:
            data = json.load(json_file)
    except FileNotFoundError:
        data = setup()

    discordToken = data["discordToken"]
    robloxId = data["robloxId"]

    while True:
        while isDiscordRunning() == True:
            if ClientClosed == True:
                client = Client(client_id)
                client.start()
                client.authenticate(discordToken)
                ClientClosed = False

            headers = {
                "previous": json.dumps(previous),
                "robloxId": str(robloxId),
            }
            rawData = requests.get(
                "https://rich-presence-api.glitch.me/getStatus",
                headers=headers)
            if rawData.status_code == 200:
                data = rawData.json()
                details = data["details"]
                state = data["state"]
                image = data["image"]
                gameSize = data["gameSize"]
                gameId = data["gameId"]

                if details == None:
                    if activityCleared == False:
                        client.clear_activity()
                        activityCleared = True
                    else:
                        time.sleep(5)
                else:
                    if data != previous:
                        if details != previous["details"] or state != previous[
                                "state"] or gameId != previous["gameId"]:
                            start = round(time.time())
                        if details == "Playing":
                            client.set_activity(
                                state=state,
                                details=details,
                                start=start,
                                large_image=image,
                                party_size=gameSize,
                                large_text="Made by Tweakified")
                        else:
                            client.set_activity(
                                state=state,
                                details=details,
                                start=start,
                                large_image=image,
                                large_text="Made by Tweakified")
                        activityCleared = False
                        time.sleep(15)
                    else:
                        time.sleep(5)
                previous = data

        if ClientClosed == False:
            if client != None:
                client.close()
                ClientClosed = True
Esempio n. 9
0
            return None
    def set(self, value):
        time = datetime.fromtimestamp(value)
        self.year.set(time.year)
        self.month.set(time.month)
        self.day.set(time.day)
        self.hour.set(time.hour)
        self.minute.set(time.minute)
        self.second.set(time.second)
        self.value = value

def get_config_file():
    home = pathlib.Path.home()
    if sys.platform == "win32":
        return home / "AppData/Roaming/StatusChanger/.StatusChanger.json"
    elif sys.platform == "linux":
        return home / ".local/share/StatusChanger/.StatusChanger.json"
    elif sys.platform == "darwin":
        return home / "Library/Application Support/StatusChanger/.StatusChanger.json"

if __name__ == "__main__":
    configuration = settings.Settings(get_config_file())
    get_id = GetId(configuration)
    id, pipe, trad = get_id.mainloop()
    if not id == 0:
        try:
            RPC = Client(id, pipe=pipe)
            RPC.start()
        except exceptions.InvalidPipe:
            pass
        rpc_tk = RPC_tk(RPC, id, configuration, trad, pipe)
Esempio n. 10
0
try:
    # Import modules
    from pypresence import Presence, Client
    import time

    # Connect to Discord
    cid = 706083923431522316
    auth = "nV7OxD2xpWnolSxsm9VkGYcmy5re5V"
    rpc = Presence(cid)
    client = Client(cid, pipe=0)
    client.start()
    client.authorize(cid, ["rpc", "rpc.notifications.read"])
    #client.authenticate(auth)
    print(client.get_selected_voice_channel())
    #client.authorize(cid)
    rpc.connect()
    rpc.update(state="Rich Presence using pypresence!")

    #client.set_user_voice_settings(cid)
    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.')
Esempio n. 11
0
import requests

from pypresence import Client

CLIENT_ID = "207646673902501888"
TOKEN_URL = "https://streamkit.discord.com/overlay/token"

rpc = Client(CLIENT_ID)


def get_code():
    response = rpc.authorize(CLIENT_ID, ["rpc", "messages.read"])
    data = response["data"]

    return data["code"]


def get_access_token(code):
    response = requests.post(url=TOKEN_URL, json={"code": code})
    data = response.json()

    return data["access_token"]


def get_selected_voice_channel():
    response = rpc.get_selected_voice_channel()
    data = response["data"]

    return data

Esempio n. 12
0
from pypresence import Client
import time
import config
client_id = config.client_id
client = Client(client_id)
client.start()
client.set_activity(pid=1, state="Simping4Alvin", details= "Alvin Simp Sesh", small_image="alvin", small_text="alvin small", large_image="alvin", large_text="alvin big", start = time.time(), party_id='What goes here', party_size = [1, 50000], join="JOINHERE")
while True:
    time.sleep(15)
Esempio n. 13
0
class ExamplePyWindowActivatable(GObject.Object, Gedit.WindowActivatable):
    __gtype_name__ = "ExamplePyWindowActivatable"

    window = GObject.property(type=Gedit.Window)
    _enabled = False
    _rpc = None

    def __init__(self):
        GObject.Object.__init__(self)
        self._client_id = "740171019003756604"
        self._pid = os.getpid()
        self.shall_update = False
        self.props = None

    def tab_change_state(self, data):
        document = self.window.get_active_tab().get_document()
        self.update_status(document)

    def tab_change(self, tab, data):
        document = tab.get_active_tab().get_document()
        self.update_status(document)

    def update_status(self, document):
        if document.props is not self.props:
            self.props = document.props
            self.epoch_start = time.time()
            self.shall_update = True

    def _reconnect(self):
        if not self._enabled:
            try:
                self._rpc = Client(self._client_id)
                self._rpc.start()
                self._enabled = True
            except self._errors:
                self._enabled = False

    def run(self):
        asyncio.set_event_loop(asyncio.new_event_loop())
        while True:
            self._reconnect()
            if self._enabled and self.shall_update:
                self._rpc.set_activity(
                    pid=self._pid,
                    large_image="default",
                    details="Writing " + (self.props.language.get_name()
                                          if self.props.language else '') +
                    " code",
                    state="Editing " + self.props.tepl_short_title,
                    start=self.epoch_start)
                if self.props.language:
                    self.shall_update = False

    def do_activate(self):
        self.window.connect("active-tab-changed", self.tab_change)
        self.window.connect("active-tab-state-changed", self.tab_change_state)

        self.thread = threading.Thread(target=self.run, daemon=True)
        self.thread.start()

    def do_deactivate(self):
        pass

    def do_update_state(self):
        pass