示例#1
0
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)
    signal.alarm(1)
    try:
        a = client.read_output()
        a = client.loop.run_until_complete(a)
    except:
        print("No event calls")
    if a['evt'] == 'ACTIVITY_JOIN':
示例#2
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()
示例#3
0
end (int) – epoch time for game end

large_image (str) – name of the uploaded image for the large profile artwork

large_text (str) – tooltip for the large image

small_image (str) – name of the uploaded image for the small profile artwork

small_text (str) – tootltip for the small image

party_id (str) – id of the player’s party, lobby, or group

party_size (list) – current size of the player’s party, lobby, or group, and the max in this format: [1,4]

join (str) – unique hashed string for chat invitations and ask to join

spectate (str) – unique hashed string for spectate button

match (str) – unique hashed string for spectate and join

buttons (list) – list of dicts for buttons on your profile in the format [{"label": "My Website", "url": "https://qtqt.cf"}, ...], can list up to two buttons

instance (bool) – marks the match as a game session with a specific beginning and end

Return type
pypresence.Response
"""
RPC.set_activity(buttons=buttons,state=desc)
while True:
	time.sleep(15)
示例#4
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
示例#5
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)
示例#6
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