コード例 #1
0
ファイル: main.py プロジェクト: ThoreKr/synapse-reporting-bot
    async def login(self) -> AsyncClient:
        # If there are no previously-saved credentials, we'll use the password
        if not os.path.exists(self.config.state_file):
            self.logger.info(
                "First time use. Did not find credential file. Using environment variables"
            )

            client = AsyncClient(self.config.homeserver,
                                 self.config.account_name)
            resp = await client.login(self.config.account_password,
                                      device_name=self.config.device_name)

            # check that we logged in succesfully
            if (isinstance(resp, LoginResponse)):
                write_details_to_disk(resp, self.config)
            else:
                self.logger.warning(
                    f'homeserver = "{self.config.homeserver}"; user = "******"'
                )
                self.logger.warning(f'Failed to log in: {resp}')
                exit(1)

            self.logger.info(
                'Logged in using a password. Credentials were stored.',
                'Try running the script again to login with credentials')

        # Otherwise the config file exists, so we'll use the stored credentials
        else:
            client = AsyncClient(self.config.homeserver)
            client.access_token = self.access_token
            client.user_id = self.user_id
            client.device_id = self.device_id

        return client
コード例 #2
0
async def main() -> None:
    # If there are no previously-saved credentials, we'll use the password
    if not os.path.exists(CONFIG_FILE):
        print("First time use. Did not find credential file. Asking for "
              "homeserver, user, and password to create credential file.")
        homeserver = "https://matrix.example.org"
        homeserver = input(f"Enter your homeserver URL: [{homeserver}] ")

        if not (homeserver.startswith("https://")
                or homeserver.startswith("http://")):
            homeserver = "https://" + homeserver

        user_id = "@user:example.org"
        user_id = input(f"Enter your full user ID: [{user_id}] ")

        device_name = "matrix-nio"
        device_name = input(f"Choose a name for this device: [{device_name}] ")

        client = AsyncClient(homeserver, user_id)
        pw = getpass.getpass()

        resp = await client.login(pw, device_name=device_name)

        # check that we logged in succesfully
        if (isinstance(resp, LoginResponse)):
            write_details_to_disk(resp, homeserver)
        else:
            print(f"homeserver = \"{homeserver}\"; user = \"{user_id}\"")
            print(f"Failed to log in: {resp}")
            sys.exit(1)

        print(
            "Logged in using a password. Credentials were stored.",
            "Try running the script again to login with credentials."
        )

    # Otherwise the config file exists, so we'll use the stored credentials
    else:
        # open the file in read-only mode
        with open(CONFIG_FILE, "r") as f:
            config = json.load(f)
            client = AsyncClient(config['homeserver'])

            client.access_token = config['access_token']
            client.user_id = config['user_id']
            client.device_id = config['device_id']

        # Now we can send messages as the user
        room_id = "!myfavouriteroomid:example.org"
        room_id = input(f"Enter room id for image message: [{room_id}] ")

        image = "exampledir/samplephoto.jpg"
        image = input(f"Enter file name of image to send: [{image}] ")

        await send_image(client, room_id, image)
        print("Logged in using stored credentials. Sent a test message.")

    # Close the client connection after we are done with it.
    await client.close()
コード例 #3
0
async def main() -> None:
    # If there are no previously-saved credentials, we'll use the password
    if not os.path.exists(CONFIG_FILE):
        print("First time use. Did not find credential file. Asking for "
              "homeserver, user, and password to create credential file.")
        homeserver = "https://matrix.example.org"
        homeserver = input(f"Enter your homeserver URL: [{homeserver}] ")

        if not (homeserver.startswith("https://")
                or homeserver.startswith("http://")):
            homeserver = "https://" + homeserver

        user_id = "@user:example.org"
        user_id = input(f"Enter your full user ID: [{user_id}] ")

        client = AsyncClient(homeserver, user_id)
        pw = getpass.getpass()

        resp = await client.login(pw)

        # check that we logged in succesfully
        if (isinstance(resp, LoginResponse)):
            write_details_to_disk(resp, homeserver)
        else:
            print(f"homeserver = \"{homeserver}\"; user = \"{user_id}\"")
            print(f"Failed to log in: {resp}")
            sys.exit(1)

        print("Logged in using a password. Credentials were stored.",
              "Try running the script again to login with credentials.")

    # Otherwise the config file exists, so we'll use the stored credentials
    else:
        # open the file in read-only mode
        with open(CONFIG_FILE, "r") as f:
            config = json.load(f)
            client = AsyncClient(config['homeserver'])

            client.access_token = config['access_token']
            client.user_id = config['user_id']
            client.device_id = config['device_id']

        # Now we can send messages as the user
        room_id = "!myfavouriteroomid:example.org"
        room_id = input(f"Enter room id for test message: [{room_id}] ")

        await client.room_send(room_id,
                               message_type="m.room.message",
                               content={
                                   "msgtype": "m.text",
                                   "body": "Hello world!"
                               })
        print("Logged in using stored credentials. Sent a test message.")

    # Either way we're logged in here, too
    await client.close()
コード例 #4
0
ファイル: dailypicture.py プロジェクト: krithin/dailypicture
async def post_picture_to_room(matrix_config: MatrixConfig,
                               image: Image) -> None:
    client = AsyncClient(matrix_config.homeserver_url)
    client.access_token = matrix_config.access_token
    client.user_id = matrix_config.mxid
    client.device_id = matrix_config.device_id

    room_id = matrix_config.target_room

    f = io.BytesIO()

    image.save(f, format="JPEG", optimize=True, progressive=True)

    # Get the (post-resize) file size
    f.seek(0, io.SEEK_END)
    image_file_size = f.tell()
    print(f"Image resized down to {image_file_size} bytes")
    f.seek(0)  # rewind to the start

    # First upload the image and get an MXC URI in response
    resp, _maybe_keys = await client.upload(
        lambda _got_429, _got_timeouts:
        f,  # No need to really use aiofiles when we have a BytesIO
        content_type="image/jpeg",
        filesize=image_file_size)

    if not isinstance(resp, UploadResponse):
        raise RuntimeError(f"Failed to send image: {resp}")

    # Then send a (image) message to the room pointing to the uploaded image's MXC URI.
    today_str = str(datetime.date.today())
    content = {
        "body": f"Image of the day {today_str}",
        "info": {
            "size": image_file_size,
            "mimetype": "image/jpeg",
            "w": image.width,
            "h": image.height,
            "thumbnail_info": None,
            "thumbnail_url": None,
        },
        "msgtype": "m.image",
        "url": resp.content_uri,
    }

    await client.room_send(room_id,
                           message_type="m.room.message",
                           content=content)

    f.close()
    await client.close()
コード例 #5
0
async def do_sendmsg(roomid, message, path, endpoint) -> None:
    full_path = os.path.join(path, CONFIG_FILE)
    if not os.path.exists(full_path):
        print(f"Didn't find {full_path}, perhaps you should run init first")
        return

    # open the file in read-only mode
    with open(full_path, "r") as f:
        config = json.load(f)
        client = AsyncClient(config["homeserver"])
        client.access_token = config["access_token"]
        client.user_id = config["user_id"]
        client.device_id = config["device_id"]

        if not roomid:
            try:
                roomid = config["room_id"]
            except KeyError:
                print("Must either specify roomid or put it config file")
                raise

        if endpoint:
            do_check_health(endpoint, 10)
        else:
            try:
                endpoint = config["endpoint"]
            except KeyError:
                pass
            else:
                do_check_health(endpoint, 10)

        resp = await client.room_send(
            roomid,
            message_type="m.room.message",
            content={
                "msgtype": "m.text",
                "body": message,
            },
        )

    if isinstance(resp, RoomSendResponse):
        print("Logged in using stored credentials. Sent message.")
    else:
        print(f"Bad response: {resp}")
    await client.close()
コード例 #6
0
async def login() -> None:
    try:
        with open(CREDS_FILE) as f:
            creds = json.load(f)
            client = AsyncClient(creds["homeserver"])
            client.access_token = creds["access_token"]
            client.user_id = creds["user_id"]
            client.device_id = creds["device_id"]
    except (FileNotFoundError, json.JSONDecodeError, KeyError):
        print(f"Did not find credentials in {CREDS_FILE}. "
              "Asking for login info.")
        matrix_server_str = "matrix.org"
        matrix_server_str = (input("Enter your matrix server URL "
                                   f"(default = {matrix_server_str!r}): ")
                             or matrix_server_str)

        url = urlsplit(matrix_server_str)
        url = (url._replace(scheme=url.scheme or "https")._replace(
            netloc=url.netloc or url.path)._replace(path=""))
        matrix_server = urlunsplit(url)

        user_id = input("Enter your user ID: ")
        user, *server_maybe = user_id.lstrip("@").split(":", 1)
        user_id = f"@{user}:" + (server_maybe[0]
                                 if server_maybe else url.netloc)

        device_name = "diplomatrix_client"
        device_name = (input("Choose a name for this device "
                             f"(default = {device_name!r}): ") or device_name)

        client = AsyncClient(matrix_server, user_id)
        pw = getpass.getpass()
        resp = await client.login(pw, device_name=device_name)

        if isinstance(resp, LoginResponse):
            save_login(resp, matrix_server)
            print(f"Logged in. Credentials saved to {CREDS_FILE!r}")
        else:
            print(f'server = "{matrix_server}"; user = "******"')
            print(f"Failed to log in: {resp}")
            sys.exit(1)

    await client.close()
コード例 #7
0
async def main() -> None:
    client = AsyncClient("https://the-apothecary.club",
                         "@bot-sync:the-apothecary.club")

    # imports login data
    with open(CONFIG_FILE, "r") as f:
        config = json.load(f)
        client.access_token = config["access_token"]
        client.user_id = config["user_id"]
        client.device_id = config["device_id"]

    # import room data
    with open(ROOMS_FILE, "r") as f:
        config = json.load(f)
        bot_control_room = config["control_room"]
        bot_template_room = config["template_room"]
        bot_rooms = config["rooms"]

    ## await bot_send_msg(client, "Online", bot_control_room)

    # get room state
    room_state = await client.room_get_state(bot_template_room)

    ## print(room_state)

    # execute in each room
    for room in bot_rooms:

        # logs room cycle
        print("Syncing state in:", room["id"])

        # join rooms if not already joined
        await client.join(room["id"])

        # sends a test message
        ##resp = await bot_send_msg(client, "Syncing...", room["id"])
        ##print(resp)
        # sends a test state event
        resp = await bot_set_emote(client, room["id"])
        print(resp)
        # ends the connection
        await client.close()
コード例 #8
0
ファイル: main.py プロジェクト: sugaroidbot/sugaroid-matrix
async def main(sugaroid: Sugaroid) -> None:
    config = Config.from_environment()
    client = AsyncClient(config['homeserver'])
    client.access_token = config['access_token']
    client.user_id = config['user_id']
    client.device_id = config['device_id']

    print("Status: sleeping for 30000")
    await client.sync(30000)
    print("Resuming:")
    cb = Callbacks(client, sugaroid=sugaroid)
    client.add_event_callback(cb.message, RoomMessageText)
    while True:
        try:
            await client.sync_forever(timeout=30000, full_state=True)
        except KeyboardInterrupt:
            break
        except (ClientConnectionError, ServerDisconnectedError):
            print("Unable to connect to homeserver, retrying in 15s")
            time.sleep(15)
        finally:
            await client.close()
コード例 #9
0
async def main() -> None:
    client = AsyncClient("https://matrix.example.org", "@alice:example.org")

    # If there are no previously-saved credentials, we'll use the password
    if not os.path.exists(CONFIG_FILE):
        resp = await client.login("hunter2")
        # check that we logged in succesfully
        if (isinstance(resp, LoginResponse)):
            write_details_to_disk(resp)
        else:
            print(f"Failed to log in: {resp}")
            sys.exit(1)

        print("Logged in using a password.",
              "Try running the script again to login with an access token")

    # Otherwise the config file exists, so we'll use the stored credentials
    else:
        # open the file in read-only mode
        with open(CONFIG_FILE, "r") as f:
            config = json.load(f)
            client.access_token = config['access_token']
            client.user_id = config['user_id']
            client.device_id = config['device_id']

        # Now we can send messages as the user
        await client.room_send(room_id="!myfavouriteroomid:example.org",
                               message_type="m.room.message",
                               content={
                                   "msgtype": "m.text",
                                   "body": "Hello world!"
                               })
        print("Logged in using stored credentials")

    # Either way we're logged in here, too
    await client.close()