示例#1
0
        if not msg.body:
            # do not reflect anything without a body
            return

        # we could also use reply = msg.make_reply() instead
        reply = aioxmpp.Message(
            type_=msg.type_,
            to=msg.from_,
        )

        # make_reply() would not set the body though
        reply.body.update(msg.body)

        self.client.enqueue(reply)

    @asyncio.coroutine
    def run_simple_example(self):
        stop_event = self.make_sigint_event()

        self.client.stream.register_message_callback(
            aioxmpp.MessageType.CHAT,
            None,
            self.message_received,
        )
        print("echoing... (press Ctrl-C or send SIGTERM to stop)")
        yield from stop_event.wait()

if __name__ == "__main__":
    exec_example(EchoBot())
class ListAdhocCommands(Example):
    def prepare_argparse(self):
        super().prepare_argparse()

        def jid(s):
            return aioxmpp.JID.fromstr(s)

        self.argparse.add_argument(
            "peer_jid",
            nargs="?",
            metavar="JID",
            default=None,
            help="Entity to ask for ad-hoc commands. Must be a full jid,"
            " defaults to the domain of the local JID (asking the server)")

    def configure(self):
        super().configure()

        self.adhoc_peer_jid = (self.args.peer_jid
                               or self.g_jid.replace(resource=None,
                                                     localpart=None))

    async def run_simple_example(self):
        adhoc = self.client.summon(aioxmpp.adhoc.AdHocClient)
        for item in await adhoc.get_commands(self.adhoc_peer_jid):
            print("{}: {}".format(item.node, item.name))


if __name__ == "__main__":
    exec_example(ListAdhocCommands())
            try:
                self.remote_jid = aioxmpp.JID.fromstr(
                    self.config.get("vcard", "remote_jid")
                )
            except (configparser.NoSectionError,
                    configparser.NoOptionError):
                self.remote_jid = aioxmpp.JID.fromstr(
                    input("Remote JID> ")
                )

    def make_simple_client(self):
        client = super().make_simple_client()
        self.vcard = client.summon(aioxmpp.vcard.VCardService)
        return client

    async def run_simple_example(self):
        vcard = await self.vcard.get_vcard(
            self.remote_jid
        )

        es = lxml.etree.tostring(vcard.elements, pretty_print=True,
                                 encoding="utf-8")
        print(es.decode("utf-8"))

    async def run_example(self):
        await super().run_example()


if __name__ == "__main__":
    exec_example(VCard())
示例#4
0
            None,
            self.collector.add_presence,
        )

        return client

    @asyncio.coroutine
    def run_simple_example(self):
        print("collecting presences... ")
        self.presences = yield from self.collector.done_future

    @asyncio.coroutine
    def run_example(self):
        yield from super().run_example()

        print("found presences:")
        for i, pres in enumerate(self.presences):
            print("presence {}".format(i))
            print("  peer: {}".format(pres.from_))
            print("  type: {}".format(pres.type_))
            print("  show: {}".format(pres.show))
            print("  status: ")
            for lang, text in pres.status.items():
                print("    (lang={}) {!r}".format(
                    lang,
                    text))


if __name__ == "__main__":
    exec_example(ListPresence())
示例#5
0
                    self.config.get("vcard", "remote_jid")
                )
            except (configparser.NoSectionError,
                    configparser.NoOptionError):
                self.remote_jid = aioxmpp.JID.fromstr(
                    input("Remote JID> ")
                )

    def make_simple_client(self):
        client = super().make_simple_client()
        self.vcard = client.summon(aioxmpp.vcard.VCardService)
        return client

    @asyncio.coroutine
    def run_simple_example(self):
        vcard = yield from self.vcard.get_vcard(
            self.remote_jid
        )


        es = lxml.etree.tostring(vcard.elements, pretty_print=True,
                                 encoding="utf-8")
        print(es.decode("utf-8"))

    @asyncio.coroutine
    def run_example(self):
        yield from super().run_example()

if __name__ == "__main__":
    exec_example(VCard())
示例#6
0
        print("{} *** {} [{}] left room ({})".format(
            datetime.utcnow().isoformat(),
            member.nick,
            member.direct_jid,
            muc_leave_mode,
        ))

    async def run_example(self):
        self.stop_event = self.make_sigint_event()
        await super().run_example()

    async def run_simple_example(self):
        print("waiting to join room...")
        done, pending = await asyncio.wait([
            self.room_future,
            self.stop_event.wait(),
        ],
                                           return_when=asyncio.FIRST_COMPLETED)
        if self.room_future not in done:
            self.room_future.cancel()
            return

        for fut in pending:
            fut.cancel()

        await self.stop_event.wait()


if __name__ == "__main__":
    exec_example(MucLogger())
示例#7
0
                localpart=None,
            )
        )

        if "urn:xmpp:blocking" not in server_info.features:
            print("server does not support block lists!", file=sys.stderr)
            sys.exit(2)

        # now that we are sure that the server supports it, we can send
        # requests.

        if self.args.jids_to_block:
            yield from self.blocking.block_jids(self.args.jids_to_block)
        else:
            print("nothing to block")

        if self.args.jids_to_unblock:
            yield from self.blocking.unblock_jids(self.args.jids_to_unblock)
        else:
            print("nothing to unblock")

        if self.args.show_list:
            # print all the items; again, .items is a list of JIDs
            print("current block list:")
            for item in sorted(self.blocking.blocklist):
                print("\t", item, sep="")


if __name__ == "__main__":
    exec_example(BlockJID())
示例#8
0
            muc_leave_mode,
        ))

    @asyncio.coroutine
    def run_example(self):
        self.stop_event = self.make_sigint_event()
        yield from super().run_example()

    @asyncio.coroutine
    def run_simple_example(self):
        print("waiting to join room...")
        done, pending = yield from asyncio.wait(
            [
                self.room_future,
                self.stop_event.wait(),
            ],
            return_when=asyncio.FIRST_COMPLETED
        )
        if self.room_future not in done:
            self.room_future.cancel()
            return

        for fut in pending:
            fut.cancel()

        yield from self.stop_event.wait()


if __name__ == "__main__":
    exec_example(MucLogger())
示例#9
0
        self.argparse.add_argument(
            "peer_jid",
            nargs="?",
            metavar="JID",
            default=None,
            help="Entity to ask for ad-hoc commands. Must be a full jid,"
            " defaults to the domain of the local JID (asking the server)"
        )

    def configure(self):
        super().configure()

        self.adhoc_peer_jid = (
            self.args.peer_jid or
            self.g_jid.replace(resource=None, localpart=None)
        )

    @asyncio.coroutine
    def run_simple_example(self):
        adhoc = self.client.summon(aioxmpp.adhoc.AdHocClient)
        for item in (yield from adhoc.get_commands(self.adhoc_peer_jid)):
            print("{}: {}".format(
                item.node,
                item.name
            ))


if __name__ == "__main__":
    exec_example(ListAdhocCommands())
示例#10
0
        if (message.from_ != self.client.local_jid.bare()
                and message.from_ is not None):
            return

        if message.xep0280_sent is not None:
            print("SENT: {}".format(
                self._format_message(message.xep0280_sent.stanza)))

        elif message.xep0280_received is not None:
            print("RECV: {}".format(
                self._format_message(message.xep0280_received.stanza)))

    @asyncio.coroutine
    def run_example(self):
        self.stop_event = self.make_sigint_event()
        yield from super().run_example()

    @asyncio.coroutine
    def run_simple_example(self):
        filterchain = self.client.stream.app_inbound_message_filter
        with filterchain.context_register(self._message_filter):
            print("enabling carbons")
            yield from self.carbons.enable()
            print("carbons enabled! sniffing ... (hit Ctrl+C to stop)")

            yield from self.stop_event.wait()


if __name__ == "__main__":
    exec_example(CarbonsSniffer())
示例#11
0
            ))

        cancel_fut = asyncio.ensure_future(self.stop_event.wait())

        await asyncio.wait(
            [
                gather_task,
                cancel_fut,
            ],
            return_when=asyncio.FIRST_COMPLETED,
        )

        for target, fut in zip(self.jids, tasks):
            if not fut.done():
                fut.cancel()
                continue

            if fut.exception():
                print("{} failed: {}".format(target, fut.exception()),
                      file=sys.stderr)
                continue

            print("{}: {}".format(target, self.format_version(fut.result())))

        if not cancel_fut.done():
            cancel_fut.cancel()


if __name__ == "__main__":
    exec_example(SoftwareVersions())
示例#12
0
        print(jid, node, buf.getvalue().decode("utf-8"))

    def make_simple_client(self):
        client = super().make_simple_client()
        self.caps = client.summon(aioxmpp.EntityCapsService)
        self.pep = client.summon(aioxmpp.PEPClient)

        self.claims = []
        for ns in self.pep_namespaces:
            claim = self.pep.claim_pep_node(
                ns,
                notify=True,
            )
            claim.on_item_publish.connect(self._on_item_published)
            self.claims.append(claim)

        return client

    @asyncio.coroutine
    def run_example(self):
        self.stop_event = self.make_sigint_event()
        yield from super().run_example()

    @asyncio.coroutine
    def run_simple_example(self):
        yield from self.stop_event.wait()


if __name__ == "__main__":
    exec_example(ListenPEP())
示例#13
0
        )

        cancel_fut = asyncio.ensure_future(self.stop_event.wait())

        yield from asyncio.wait(
            [
                gather_task,
                cancel_fut,
            ],
            return_when=asyncio.FIRST_COMPLETED,
        )

        for target, fut in zip(self.jids, tasks):
            if not fut.done():
                fut.cancel()
                continue

            if fut.exception():
                print("{} failed: {}".format(target, fut.exception()),
                      file=sys.stderr)
                continue

            print("{}: {}".format(target, self.format_version(fut.result())))

        if not cancel_fut.done():
            cancel_fut.cancel()


if __name__ == "__main__":
    exec_example(SoftwareVersions())
        self.stop_event = self.make_sigint_event()
        await super().run_example()

    def _on_item_published(self, jid, node, item, *, message=None):
        print("PUBLISHED: {}".format(item.id_))

    def _on_item_retracted(self, jid, node, id_, *, message=None):
        print("RETRACTED: {}".format(id_))

    async def run_simple_example(self):
        pubsub = self.client.summon(aioxmpp.PubSubClient)
        pubsub.on_item_published.connect(self._on_item_published)
        pubsub.on_item_retracted.connect(self._on_item_retracted)
        subid = (await pubsub.subscribe(
            self.args.target_entity,
            node=self.args.target_node,
        )).payload.subid
        print("SUBSCRIBED: subid={!r}".format(subid))
        try:
            await self.stop_event.wait()
        finally:
            await pubsub.unsubscribe(
                self.args.target_entity,
                node=self.args.target_node,
                subid=subid,
            )


if __name__ == "__main__":
    exec_example(PubSubWatch())
示例#15
0
        self.humming = True
        replies = [f"* Starting hum: {self.hum_topic}"]
        i = 1
        for option in self.hum_options:
            replies.append(f"  Option {i}: {option}")
            i += 1
        replies.append(
            f"Please hum like this: 'hum n' for option n. To finish, 'hum stop'."
        )
        return replies

    def on_stop(self, rest):
        if not self.humming:
            return [f"Sorry, there isn't a hum running."]
        self.humming = False
        results = defaultdict(int)
        for hum in self.hum_results.values():
            results[hum] += 1
        replies = ["* Finishing hum. The results are:"]
        replies.append(f"  {self.hum_topic}")
        i = 1
        for option in self.hum_options:
            replies.append(f"  Option {i}: {option} -- {results[i]} hummed")
            i += 1
        self.init_hum()
        return replies


if __name__ == "__main__":
    exec_example(MeetingBot())
示例#16
0
    def make_simple_client(self):
        client = super().make_simple_client()
        self.roster = client.summon(aioxmpp.RosterClient)
        self.roster.on_initial_roster_received.connect(
            self._on_initial_roster,
        )
        self.done_event = asyncio.Event()

        return client

    @asyncio.coroutine
    def run_simple_example(self):
        done, pending = yield from asyncio.wait(
            [
                self.sigint_event.wait(),
                self.done_event.wait()
            ],
            return_when=asyncio.FIRST_COMPLETED,
        )
        for fut in pending:
            fut.cancel()

    @asyncio.coroutine
    def run_example(self):
        self.sigint_event = self.make_sigint_event()
        yield from super().run_example()


if __name__ == "__main__":
    exec_example(Roster())
示例#17
0
            type=jid
        )

        self.argparse.add_argument(
            "target_node",
            default=None,
            nargs="?",
        )

    @asyncio.coroutine
    def run_simple_example(self):
        disco = self.client.summon(aioxmpp.DiscoClient)
        try:
            items = yield from disco.query_items(
                self.args.target_entity,
                node=self.args.target_node,
                timeout=10
            )
        except Exception as exc:
            print("could not get info: ")
            print("{}: {}".format(type(exc).__name__, exc))
            raise

        print("items:")
        for item in items.items:
            print("  jid={}  node={!r}  name={!r}".format(item.jid, item.node, item.name))


if __name__ == "__main__":
    exec_example(EntityItems())
示例#18
0
                lookups.append(self._check_for_upload_service(disco, item.jid))

            jids = list(filter(None, (yield from asyncio.gather(*lookups))))

            if not jids:
                print("error: failed to auto-discover upload service",
                      file=sys.stderr)
                return

            self.service_addr = jids[0]

        print("using {}".format(self.service_addr), file=sys.stderr)

        slot = yield from self.client.send(
            aioxmpp.IQ(to=self.service_addr,
                       type_=aioxmpp.IQType.GET,
                       payload=aioxmpp.httpupload.Request(
                           self.file_name,
                           self.file_size,
                           self.file_type,
                       )))

        if not (yield from self.upload(slot.put.url, slot.put.headers)):
            return

        print(slot.get.url)


if __name__ == "__main__":
    exec_example(Upload())
示例#19
0
        self.done_event.set()

    def make_simple_client(self):
        client = super().make_simple_client()
        self.roster = client.summon(aioxmpp.RosterClient)
        self.roster.on_initial_roster_received.connect(
            self._on_initial_roster, )
        self.done_event = asyncio.Event()

        return client

    @asyncio.coroutine
    def run_simple_example(self):
        done, pending = yield from asyncio.wait(
            [self.sigint_event.wait(),
             self.done_event.wait()],
            return_when=asyncio.FIRST_COMPLETED,
        )
        for fut in pending:
            fut.cancel()

    @asyncio.coroutine
    def run_example(self):
        self.sigint_event = self.make_sigint_event()
        yield from super().run_example()


if __name__ == "__main__":
    exec_example(Roster())
示例#20
0
            type=jid,
            help="Recipient JID"
        )

        self.argparse.add_argument(
            "message",
            nargs="?",
            default="Hello World!",
            help="Message to send (default: Hello World!)",
        )

    async def run_simple_example(self):
        # compose a message
        msg = aioxmpp.stanza.Message(
            to=self.args.recipient,
            type_=aioxmpp.MessageType.CHAT,
        )

        # [None] is for "no XML language tag"
        msg.body[None] = self.args.message

        print("sending message ...")
        await self.client.stream.send_and_wait_for_sent(
            msg
        )
        print("message sent!")


if __name__ == "__main__":
    exec_example(SendMessage())
示例#21
0
            default=None,
            nargs="?",
        )

    @asyncio.coroutine
    def run_simple_example(self):
        pubsub = self.client.summon(aioxmpp.PubSubClient)
        try:
            if self.args.target_node is None:
                items = yield from pubsub.get_nodes(self.args.target_entity)
            else:
                items = yield from pubsub.get_items(
                    self.args.target_entity,
                    node=self.args.target_node,
                )
        except Exception as exc:
            print("could not get info: ")
            print("{}: {}".format(type(exc).__name__, exc))
            raise

        print("items:")
        for item in items.payload.items:
            if item.registered_payload is not None:
                print(item.registered_payload)
            else:
                print(lxml.etree.tostring(item.unregistered_payload))


if __name__ == "__main__":
    exec_example(PubSubItems())
示例#22
0
        else:
            self.avatar_file = None
        self.wipe_avatar = self.args.wipe_avatar

    def make_simple_client(self):
        client = super().make_simple_client()
        self.avatar = client.summon(aioxmpp.avatar.AvatarService)
        return client

    @asyncio.coroutine
    def run_simple_example(self):
        if self.avatar_file is not None:
            with open(self.avatar_file, "rb") as f:
                image_data = f.read()

            avatar_set = aioxmpp.avatar.AvatarSet()
            avatar_set.add_avatar_image("image/png", image_bytes=image_data)

            yield from self.avatar.publish_avatar_set(avatar_set)

        elif self.wipe_avatar:
            yield from self.avatar.disable_avatar()

    @asyncio.coroutine
    def run_example(self):
        yield from super().run_example()


if __name__ == "__main__":
    exec_example(Avatar())
示例#23
0
    async def run_example(self):
        self.stop_event = self.make_sigint_event()
        await super().run_example()

    async def run_simple_example(self):
        muc = self.client.summon(aioxmpp.muc.Service)

        config = await muc.get_room_config(self.muc_jid)
        form = aioxmpp.muc.xso.ConfigurationForm.from_xso(config)

        if self.args.membersonly is not None:
            form.membersonly.value = self.args.membersonly

        if self.args.persistent is not None:
            form.persistent.value = self.args.persistent

        if self.args.moderated is not None:
            form.moderatedroom.value = self.args.moderated

        if self.args.description is not None:
            form.roomdesc.value = self.args.description

        if self.args.name is not None:
            form.roomname.value = self.args.name

        await muc.set_room_config(self.muc_jid, form.render_reply())


if __name__ == "__main__":
    exec_example(ServerInfo())
示例#24
0
    def _on_available(self, full_jid, stanza):
        asyncio.ensure_future(self._show_info(full_jid))

    def make_simple_client(self):
        client = super().make_simple_client()
        self.disco = client.summon(aioxmpp.DiscoClient)
        self.caps = client.summon(aioxmpp.EntityCapsService)

        if self.args.system_capsdb:
            self.caps.cache.set_system_db_path(self.args.system_capsdb)
        self.caps.cache.set_user_db_path(self.args.user_capsdb)

        self.presence = client.summon(aioxmpp.PresenceClient)
        self.presence.on_available.connect(
            self._on_available
        )

        return client

    @asyncio.coroutine
    def run_simple_example(self):
        for i in range(5, 0, -1):
            print("going to wait {} more seconds for further "
                  "presence".format(i))
            yield from asyncio.sleep(1)


if __name__ == "__main__":
    exec_example(PresenceInfo())
示例#25
0
        super().prepare_argparse()

        def jid(s):
            return aioxmpp.JID.fromstr(s)

        self.argparse.add_argument("recipient", type=jid, help="Recipient JID")

        self.argparse.add_argument(
            "xml",
            type=etree.fromstring,
            help="XML to send as message",
        )

    @asyncio.coroutine
    def run_simple_example(self):
        # compose a message
        msg = aioxmpp.stanza.Message(
            to=self.args.recipient,
            type_=aioxmpp.MessageType.CHAT,
        )

        msg.raw.append(self.args.xml)

        print("sending message ...")
        yield from self.client.send(msg)
        print("message sent!")


if __name__ == "__main__":
    exec_example(SendMessage())
示例#26
0
        if not msg.body:
            # do not reflect anything without a body
            return

        # we could also use reply = msg.make_reply() instead
        reply = aioxmpp.Message(
            type_=msg.type_,
            to=msg.from_,
        )

        # make_reply() would not set the body though
        reply.body.update(msg.body)

        self.client.enqueue(reply)

    @asyncio.coroutine
    def run_simple_example(self):
        stop_event = self.make_sigint_event()

        self.client.stream.register_message_callback(
            aioxmpp.MessageType.CHAT,
            None,
            self.message_received,
        )
        print("echoing... (press Ctrl-C or send SIGTERM to stop)")
        yield from stop_event.wait()


if __name__ == "__main__":
    exec_example(EchoBot())
示例#27
0
                type_=aioxmpp.IQType.SET,
                payload=blocklist,
            )

            # send it and wait for a response
            await self.client.stream.send_iq_and_wait_for_reply(
                iq
            )
        else:
            print("nothing to block")

        if self.args.show_list:
            # construct the request to retrieve the block list
            iq = aioxmpp.IQ(
                type_=aioxmpp.IQType.GET,
                payload=BlockList(),
            )

            result = await self.client.stream.send_iq_and_wait_for_reply(
                iq,
            )

            # print all the items; again, .items is a list of JIDs
            print("current block list:")
            for item in result.items:
                print(" ", item)


if __name__ == "__main__":
    exec_example(BlockJID())
示例#28
0
        buf = io.BytesIO()
        aioxmpp.xml.write_single_xso(item, buf)
        print(jid, node, buf.getvalue().decode("utf-8"))

    def make_simple_client(self):
        client = super().make_simple_client()
        self.caps = client.summon(aioxmpp.EntityCapsService)
        self.pep = client.summon(aioxmpp.PEPClient)

        self.claims = []
        for ns in self.pep_namespaces:
            claim = self.pep.claim_pep_node(
                ns,
                notify=True,
            )
            claim.on_item_publish.connect(self._on_item_published)
            self.claims.append(claim)

        return client

    async def run_example(self):
        self.stop_event = self.make_sigint_event()
        await super().run_example()

    async def run_simple_example(self):
        await self.stop_event.wait()


if __name__ == "__main__":
    exec_example(ListenPEP())
示例#29
0
        if self.remote_jid is None:
            try:
                self.remote_jid = aioxmpp.JID.fromstr(
                    self.config.get("avatar", "remote_jid"))
            except (configparser.NoSectionError, configparser.NoOptionError):
                self.remote_jid = aioxmpp.JID.fromstr(input("Remote JID> "))

    def make_simple_client(self):
        client = super().make_simple_client()
        self.avatar = client.summon(aioxmpp.avatar.AvatarService)
        return client

    async def run_simple_example(self):
        metadata = await self.avatar.get_avatar_metadata(self.remote_jid)

        for metadatum in metadata:
            if metadatum.can_get_image_bytes_via_xmpp:
                image = await metadatum.get_image_bytes()
                with open(self.output_file, "wb") as avatar_image:
                    avatar_image.write(image)
                return

        print("retrieving avatar failed: no avatar available via xmpp")

    async def run_example(self):
        await super().run_example()


if __name__ == "__main__":
    exec_example(Avatar())
示例#30
0
        muc = self.client.summon(aioxmpp.MUCClient)

        config = yield from muc.get_room_config(
            self.muc_jid
        )
        form = aioxmpp.muc.xso.ConfigurationForm.from_xso(config)

        if self.args.membersonly is not None:
            form.membersonly.value = self.args.membersonly

        if self.args.persistent is not None:
            form.persistent.value = self.args.persistent

        if self.args.moderated is not None:
            form.moderatedroom.value = self.args.moderated

        if self.args.description is not None:
            form.roomdesc.value = self.args.description

        if self.args.name is not None:
            form.roomname.value = self.args.name

        yield from muc.set_room_config(
            self.muc_jid,
            form.render_reply()
        )


if __name__ == "__main__":
    exec_example(ServerInfo())
示例#31
0
            for identity in subidentities:
                print("      [{}] {!r}".format(identity.lang, identity.name))

    def _on_available(self, full_jid, stanza):
        asyncio.ensure_future(self._show_info(full_jid))

    def make_simple_client(self):
        client = super().make_simple_client()
        self.disco = client.summon(aioxmpp.DiscoClient)
        self.caps = client.summon(aioxmpp.EntityCapsService)

        if self.args.system_capsdb:
            self.caps.cache.set_system_db_path(self.args.system_capsdb)
        self.caps.cache.set_user_db_path(self.args.user_capsdb)

        self.presence = client.summon(aioxmpp.PresenceClient)
        self.presence.on_available.connect(self._on_available)

        return client

    @asyncio.coroutine
    def run_simple_example(self):
        for i in range(5, 0, -1):
            print("going to wait {} more seconds for further "
                  "presence".format(i))
            yield from asyncio.sleep(1)


if __name__ == "__main__":
    exec_example(PresenceInfo())
示例#32
0
            if not jids:
                print("error: failed to auto-discover upload service",
                      file=sys.stderr)
                return

            self.service_addr = jids[0]

        print("using {}".format(self.service_addr), file=sys.stderr)

        slot = yield from self.client.send(
            aioxmpp.IQ(
                to=self.service_addr,
                type_=aioxmpp.IQType.GET,
                payload=aioxmpp.httpupload.Request(
                    self.file_name,
                    self.file_size,
                    self.file_type,
                )
            )
        )

        if not (yield from self.upload(slot.put.url, slot.put.headers)):
            return

        print(slot.get.url)


if __name__ == "__main__":
    exec_example(Upload())