def __init__(self, host, loop, access_key, encryption): """ :param host: aka serial number :param access_key: :param password: :param host: :param sasl_mech: """ self.serial_number = host self.loop = loop self._encryption = encryption self._request_timeout = 10 self._lock = asyncio.Lock() self.msg_event = None identifier = self.serial_number + "@" + self.xmpp_host self._from = self._rrc_contact_prefix + identifier self._to = self.jid(self._rrc_gateway_prefix + identifier) self._jid = self.jid(self._from) self.xmppclient = aioxmpp.PresenceManagedClient( self._jid, aioxmpp.make_security_layer(self._accesskey_prefix + access_key) ) self.message_dispatcher = self.xmppclient.summon( aioxmpp.dispatcher.SimpleMessageDispatcher )
async def main(local_jid, password): client = aioxmpp.PresenceManagedClient( local_jid, aioxmpp.make_security_layer(password)) def message_received(msg): 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) client.enqueue(reply) message_dispatcher = client.summon( aioxmpp.dispatcher.SimpleMessageDispatcher) message_dispatcher.register_callback( aioxmpp.MessageType.CHAT, None, message_received, ) async with client.connected(): while True: await asyncio.sleep(1)
async def run(self) -> None: resource_id = (uuid.uuid4().hex).upper() resource = 'V2:Fortnite:{0.client.platform.value}::{1}'.format( self, resource_id) self.xmpp_client = aioxmpp.PresenceManagedClient( aioxmpp.JID(self.client.user.id, self.client.service_host, resource), aioxmpp.make_security_layer(self.client.auth.access_token, no_verify=True), override_peer=[(self.client.service_domain, self.client.service_port, XMPPOverWebsocketConnector())], loop=self.client.loop) self.muc_service = self.xmpp_client.summon(aioxmpp.MUCClient) self.setup_callbacks() future = self.client.loop.create_future() self._task = asyncio.ensure_future(self._run(future), loop=self.client.loop) await future self._ping_task = asyncio.ensure_future(self.loop_ping(), loop=self.client.loop) asyncio.ensure_future(self.send_presence_on_start(), loop=self.client.loop) self.client.dispatch_event('xmpp_session_establish')
async def _executor(my_jid, my_passwd, master_jid): masters = [aioxmpp.JID.fromstr(i) for i in master_jid.split(',')] client = aioxmpp.PresenceManagedClient( aioxmpp.JID.fromstr(my_jid), aioxmpp.make_security_layer(my_passwd), ) # auto re-connect every 10s after conn down client.backoff_factor = 1 client.backoff_cap = timedelta(seconds=10) G['client'] = client message_dispatcher = client.summon( aioxmpp.dispatcher.SimpleMessageDispatcher) for m in masters: message_dispatcher.register_callback( aioxmpp.MessageType.CHAT, m, message_received, ) roster_client = client.summon(aioxmpp.RosterClient) while True: try: async with client.connected(): for m in masters: roster_client.approve(m) roster_client.subscribe(m) logger.info('Connected') await asyncio.sleep(time.time()) except asyncio.CancelledError: # asyncio.sleep # KeyboardInterrupt raise except Exception as e: logger.warning(repr(e))
async def run(self): resource_id = (uuid.uuid4().hex).upper() self.xmpp_client = aioxmpp.PresenceManagedClient( aioxmpp.JID( self.client.user.id, self.client.service_host, 'V2:Fortnite:{0.client.platform.value}::{1}'.format(self, resource_id) ), aioxmpp.make_security_layer( self.client.auth.access_token, no_verify=True ), override_peer=[( self.client.service_domain, self.client.service_port, aioxmpp.connector.STARTTLSConnector() )], loop=self.client.loop ) self.muc_service = self.xmpp_client.summon(aioxmpp.MUCClient) self.setup_callbacks() future = self.client.loop.create_future() self._task = asyncio.ensure_future(self._run(future), loop=self.client.loop) await future self._ping_task = asyncio.ensure_future(self.loop_ping(), loop=self.client.loop)
def start(self, user): Log.info('开始登陆', user) self.jid = aioxmpp.JID.fromstr(user['JID']) self.password = user['PWD'] try: # no_verify=True大坑!,注意关闭认证;参考:https://docs.zombofant.net/aioxmpp/devel/api/public/security_layer.html # 可能要自己定义security_layer以达到通信安全 self.client = aioxmpp.PresenceManagedClient( self.jid, aioxmpp.make_security_layer(self.password, no_verify=True), loop=self._loop) self.client.set_presence( aioxmpp.PresenceState(available=True, show=aioxmpp.PresenceShow.FREE_FOR_CHAT), {aioxmpp.structs.LanguageTag.fromstr('en'): '在线'}) self.client.on_failure.connect(self.on_failure) #启动失败时操作 self.client.on_stream_established.connect( self.on_login_success) #在链接服务器时操作 self.client.on_stream_suspended.connect( self.on_internet_disconnect) #服务器链接中断时操作 self.client.on_stream_destroyed.connect( self.on_internet_disconnect) #服务器链接失败时操作 except ConnectionRefusedError: self._sign_login.emit(3) return except Exception: return
def __init__(self, jid: str, password: str, *, config): self.config = config self.client = aioxmpp.PresenceManagedClient( aioxmpp.JID.fromstr(jid), aioxmpp.make_security_layer(password, no_verify=True), ) self.muc = self.client.summon(aioxmpp.MUCClient) self.on_message_handlers = []
async def _async_start(self, auto_register=True): """ Starts the agent from a coroutine. This fires some actions: * if auto_register: register the agent in the server * runs the event loop * connects the agent to the server * runs the registered behaviours Args: auto_register (bool, optional): register the agent in the server (Default value = True) """ await self._hook_plugin_before_connection() if auto_register: await self._async_register() self.client = aioxmpp.PresenceManagedClient( self.jid, aioxmpp.make_security_layer(self.password, no_verify=not self.verify_security), loop=self.loop, logger=logging.getLogger(self.jid.localpart), ) # obtain an instance of the service self.message_dispatcher = self.client.summon(SimpleMessageDispatcher) # Presence service self.presence = PresenceManager(self) await self._async_connect() # register a message callback here self.message_dispatcher.register_callback( aioxmpp.MessageType.CHAT, None, self._message_received, ) await self._hook_plugin_after_connection() # pubsub initialization try: self._node = str(self.jid.bare()) await self.pubsub.create(self.pubsub_server, f"{self._node}") except XMPPCancelError as e: logger.info(f"Node {self._node} already registered") except XMPPAuthError as e: logger.error( f"Artifact {self._node} is not allowed to publish properties.") raise e await self.setup() self._alive.set() asyncio.run_coroutine_threadsafe(self.run(), loop=self.loop)
async def jabber(self, jid, password): await self.bot.wait_until_ready() print('Waiting for pings from Jabber.') client = aioxmpp.PresenceManagedClient( jid, aioxmpp.make_security_layer(password, no_verify=True)) icon_url = self.icon_url bot = self.bot def message_recieved(msg): if not msg.body: # We dont want to do anything with an empty message. return if msg.from_.bare() == aioxmpp.JID.fromstr(self.target).bare(): # Take the message and pass it to an async task so we can post it. return asyncio.Task(post(msg)) return # noinspection PyUnresolvedReferences message_dispatcher = client.summon( aioxmpp.dispatcher.SimpleMessageDispatcher) message_dispatcher.register_callback(aioxmpp.MessageType.CHAT, None, message_recieved) async def post(msg): body = msg.body[list(msg.body.keys())[0]] bot.logger.info('Ping Received.') urls = re.findall( 'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', body) if len(urls) == 0: urlstr = '' else: urlstr = "**PING CONTAINS THE FOLLOWING URLS** \n> " + ' \n> '.join( urls) + "\n\n" time = datetime.datetime.utcnow() embed = discord.Embed( description=f'```\n{body}```\n ' f'{urlstr}' f'***THIS IS PING HAS BEEN AUTOMATICALLY FORWARDED FROM JABBER***', color=discord.Color.red(), timestamp=time) embed.set_author(name=f'{self.target}', icon_url=f'{icon_url}') embed.set_thumbnail(url=f'{icon_url}') embed.set_footer(icon_url=bot.user.avatar_url_as(format='png'), text=f"Service provided by {bot.user.name}") return await self.channel.send(embed=embed) # noinspection PyUnresolvedReferences @aioxmpp.service.iq_handler() async def iq_handle(): pass async with client.connected(): while 'JabberPings' in self.bot.cogs: await asyncio.sleep(1)
async def cancel(jid, password): client = aioxmpp.PresenceManagedClient( jid, aioxmpp.make_security_layer(password) ) async with client.connected() as stream: service = ibr.RegistrationService(stream) await service.cancel_registration()
def __init__(self, jid: str, password: str, nick_name=None): self._jid = jid self._nick_name = nick_name if self._nick_name is None: self._nick_name = jid.split('@')[0] if '@' in jid else 'tcgl_bot' self._client = aioxmpp.PresenceManagedClient( aioxmpp.JID.fromstr(jid), aioxmpp.make_security_layer(password, no_verify=True)) self._muc = self._client.summon(aioxmpp.muc.MUCClient) self._stream = None
async def get_info(jid, password): client = aioxmpp.PresenceManagedClient( jid, aioxmpp.make_security_layer(password) ) async with client.connected() as stream: service = ibr.RegistrationService(stream) reply = await service.get_client_info() print("Username: " + reply.username)
async def amain() -> int: config: Config = environ.to_config(Config) logging.basicConfig(level={ 0: logging.ERROR, 1: logging.WARNING, 2: logging.INFO, }.get(config.lib_log_level, logging.DEBUG), ) logging.getLogger("authbot").setLevel({ 0: logging.ERROR, 1: logging.WARNING, 2: logging.INFO, }.get(config.log_level, logging.DEBUG)) client = aioxmpp.PresenceManagedClient( config.address, aioxmpp.make_security_layer(config.password, ), ) client.summon(aioxmpp.MUCClient) client.summon(aioxmpp.DiscoClient) stop_event = asyncio.Event() loop = asyncio.get_event_loop() loop.add_signal_handler(signal.SIGINT, stop_event.set) loop.add_signal_handler(signal.SIGTERM, stop_event.set) stop_future = asyncio.create_task(stop_event.wait()) async with client.connected() as stream: logger.info("connected as %s", stream.local_jid) bot_task = asyncio.create_task( bot.run_in_room( client, config.room_address, config.room_nickname, )) done, pending = await asyncio.wait( [bot_task, stop_future], return_when=asyncio.FIRST_COMPLETED, ) for fut in pending: fut.cancel() for fut in done: fut.result() for fut in pending: try: await fut except asyncio.CancelledError: pass
async def change_password(jid, old_password, new_password): client = aioxmpp.PresenceManagedClient( jid, aioxmpp.make_security_layer(old_password) ) async with client.connected() as stream: service = ibr.RegistrationService(stream) await service.change_pass(new_password) print("Password changed")
async def _send_message(from_jid, from_passwd, to_jid, message): client = aioxmpp.PresenceManagedClient( aioxmpp.JID.fromstr(from_jid), aioxmpp.make_security_layer(from_passwd), ) msg = aioxmpp.Message( to=aioxmpp.JID.fromstr(to_jid), type_=aioxmpp.MessageType.CHAT, ) msg.body[None] = message async with client.connected(): await client.send(msg)
async def _make_client(self, logger): override_peer = [] if self.__port is not None: override_peer.append((self.__host, self.__port, aioxmpp.connector.STARTTLSConnector())) return aioxmpp.PresenceManagedClient( self._domain, self.__security_layer, override_peer=override_peer, logger=logger, )
async def main(local_jid, password): client = aioxmpp.PresenceManagedClient( local_jid, aioxmpp.make_security_layer(password)) client.stream.register_iq_request_coro( "get", Query, handler, ) async with client.connected(): await asyncio.sleep(30)
def client(client_username, password): jid = aioxmpp.JID.fromstr(client_username) client = aioxmpp.PresenceManagedClient( jid, aioxmpp.make_security_layer( password, no_verify=True ), ) return client
async def _async_start(self, auto_register=True): """ Starts the agent from a coroutine. This fires some actions: * if auto_register: register the agent in the server * runs the event loop * connects the agent to the server * runs the registered behaviours Args: auto_register (bool, optional): register the agent in the server (Default value = True) """ await self._hook_plugin_before_connection() if auto_register: await self._async_register() self.client = aioxmpp.PresenceManagedClient( self.jid, aioxmpp.make_security_layer(self.password, no_verify=not self.verify_security), loop=self.loop, logger=logging.getLogger(self.jid.localpart), ) # obtain an instance of the service self.message_dispatcher = self.client.summon(SimpleMessageDispatcher) # Presence service self.presence = PresenceManager(self) await self._async_connect() # register a message callback here self.message_dispatcher.register_callback( aioxmpp.MessageType.CHAT, None, self._message_received, ) await self._hook_plugin_after_connection() await self.setup() self._alive.set() for behaviour in self.behaviours: if not behaviour.is_running: behaviour.set_agent(self) if issubclass(type(behaviour), FSMBehaviour): for _, state in behaviour.get_states().items(): state.set_agent(self) behaviour.start()
async def main(from_jid, to_jid, password, message): client = aioxmpp.PresenceManagedClient( aioxmpp.JID.fromstr(from_jid), aioxmpp.make_security_layer(password), ) async with client.connected() as stream: msg = aioxmpp.Message( to=aioxmpp.JID.fromstr(to_jid), type_=aioxmpp.MessageType.CHAT, ) msg.body[None] = message await stream.send(msg)
def __init__(self, agent, loop, *args, **kwargs): super().__init__(*args, **kwargs) self.agent = agent self.jid = agent.jid self.event = Event() self.conn_coro = None self.stream = None self.loop = loop asyncio.set_event_loop(self.loop) self.client = aioxmpp.PresenceManagedClient(agent.jid, aioxmpp.make_security_layer(agent.password, no_verify=not agent.verify_security), loop=self.loop, logger=logging.getLogger(agent.jid.localpart))
async def _make_client(self, logger): override_peer = [] if self.__port is not None: override_peer.append((self.__host, self.__port, aioxmpp.connector.STARTTLSConnector())) user = base64.b32encode( self.__username_rng.getrandbits(128).to_bytes( 128 // 8, 'little')).decode("ascii").rstrip("=") user_jid = self._domain.replace(localpart=user) return aioxmpp.PresenceManagedClient( user_jid, self.__security_layer, override_peer=override_peer, logger=logger, )
def __init__(self, jid, password, receive_from): """ Initialize the class by setting JID and password. Adds a dispatcher to receive messages from the defined account. @param jid: the jabber ID of the buffers account @param password: the password of the buffers jabber account @param receiveFrom: the jabber ID of the account that's allowed to send messages to this buffer """ self.running = False self.receive_from = receive_from self.client = aioxmpp.PresenceManagedClient( aioxmpp.JID.fromstr(jid), aioxmpp.make_security_layer(password)) message_dispatcher = self.client.summon( aioxmpp.dispatcher.SimpleMessageDispatcher) message_dispatcher.register_callback(aioxmpp.MessageType.CHAT, aioxmpp.JID.fromstr(receive_from), self.receive) self.loop = asyncio.get_event_loop()
async def watch_for_messages(xmpp_id, password): """ Monitor an XMPP account, and raise any messages received as desktop notifications """ client = aioxmpp.PresenceManagedClient( xmpp_id, aioxmpp.make_security_layer(password) ) # Whenever we receive a message, raise it as a notification client.stream.register_message_callback( aioxmpp.MessageType.CHAT, None, raise_notification, ) async with client.connected(): while True: await asyncio.sleep(5)
async def main(local_jid, password): client = aioxmpp.PresenceManagedClient( local_jid, aioxmpp.make_security_layer(password)) peer_jid = local_jid.bare().replace(localpart=None) async with client.connected() as stream: iq = aioxmpp.IQ( type_="get", payload=Query(), to=peer_jid, ) print("sending query to {}".format(peer_jid)) reply = await stream.send(iq) print("got response! logging off...") print(" name: {!r}".format(reply.name)) print(" version: {!r}".format(reply.version)) print(" os: {!r}".format(reply.os))
async def send(self, chunk): if self.insecure_password: password = self.insecure_password elif keyring is not None: password = keyring.get_password("urlwatch_xmpp", self.sender) if password is None: raise ValueError( "No password available in keyring for {}".format(self.sender) ) jid = aioxmpp.JID.fromstr(self.sender) client = aioxmpp.PresenceManagedClient( jid, aioxmpp.make_security_layer(password) ) recipient_jid = aioxmpp.JID.fromstr(self.recipient) async with client.connected() as stream: msg = aioxmpp.Message(to=recipient_jid, type_=aioxmpp.MessageType.CHAT,) msg.body[None] = chunk await stream.send_and_wait_for_sent(msg)
async def run(self): self.client = aioxmpp.PresenceManagedClient( aioxmpp.JID.fromstr(self.config['xmpp']['jid']), aioxmpp.make_security_layer(self.config['xmpp']['password']), ) async with self.client.connected(): message_dispatcher = self.client.summon( aioxmpp.dispatcher.SimpleMessageDispatcher) message_dispatcher.register_callback( aioxmpp.MessageType.CHAT, None, self.message_received, ) update_feeds_task = asyncio.create_task(self.update_feeds_task()) await self.make_sigint_event().wait() update_feeds_task.cancel() try: await update_feeds_task except asyncio.CancelledError: pass
def __init__(self, host, loop, access_key, encryption): """ :param host: aka serial number :param access_key: :param password: :param host: :param sasl_mech: """ self.serial_number = host self.loop = loop self._encryption = encryption self._lock = asyncio.Lock() identifier = self.serial_number + "@" + self.xmpp_host self._from = self._rrc_contact_prefix + identifier self._to = self.jid(self._rrc_gateway_prefix + identifier) self._jid = self.jid(self._from) self.xmppclient = aioxmpp.PresenceManagedClient( self._jid, aioxmpp.make_security_layer(self._accesskey_prefix + access_key) ) self.message_dispatcher = self.xmppclient.summon( aioxmpp.dispatcher.SimpleMessageDispatcher ) self._st = AsyncExitStack() self.listeners = set() self._xmppstream = None self.message_dispatcher.register_callback( aioxmpp.MessageType.NORMAL, None, self.main_listener, ) self.message_dispatcher.register_callback( aioxmpp.MessageType.CHAT, None, self.main_listener, ) self._seqno = 1
async def _make_client(self, logger): override_peer = [] if self.__port is not None: override_peer.append((self.__host, self.__port, aioxmpp.connector.STARTTLSConnector())) next_account = self.__nused_accounts try: address, security_layer = self.__accounts[next_account] except IndexError: err = ("not enough accounts; needed at least one more account " "after already using {} accounts".format(next_account)) if self.__skip_on_too_few_accounts: raise unittest.SkipTest(err) raise RuntimeError(err) self.__nused_accounts += 1 return aioxmpp.PresenceManagedClient( address, security_layer, override_peer=override_peer, logger=logger, )
def __init__(self, loop, jid, security_layer, default_nickname, state, privileged_entities, components, mirror_config, spokesman_config, avatar_whitelist, prometheus_config): self.logger = logging.getLogger("muclogger") self._loop = loop self._state = state self._intr_event = asyncio.Event(loop=self._loop) self._client = aioxmpp.PresenceManagedClient( jid, security_layer, logger=logging.getLogger("muchopper.client")) self._client.summon(aioxmpp.DiscoServer) self._muc_svc = self._client.summon(aioxmpp.MUCClient) self._disco_svc = self._client.summon(aioxmpp.DiscoClient) if (Component.MIRROR_CLIENT in components and (Component.WATCHER in components or Component.SCANNER in components or Component.INTERACTION in components or Component.INSIDEMAN in components)): raise Exception( "Invalid configuration: mirror-client can not be used together " "with watcher, scanner, interaction or insideman components, " "since mirror-client needs full control over the database.") if Component.INTERACTION in components: self._interaction = self._client.summon(InteractionHandler) self._interaction.state = state self._interaction.suggester = self.suggest_new_address_nonblocking self._interaction.PRIVILEGED_ENTITIES.extend(privileged_entities) if Component.WATCHER in components: self._watcher = self._client.summon(watcher.Watcher) self._watcher.state = state self._watcher.suggester = self.suggest_new_address self._watcher.avatar_whitelist = avatar_whitelist else: self._watcher = None if Component.SCANNER in components: self._scanner = self._client.summon(scanner.Scanner) self._scanner.state = state self._scanner.suggester = self.suggest_new_address if Component.INSIDEMAN in components: self._insideman = self._client.summon(insideman.InsideMan) self._insideman.state = state self._insideman.default_nickname = default_nickname self._insideman.suggester = self.suggest_new_address_nonblocking if Component.SPOKESMAN in components: self._spokesman = self._client.summon(spokesman.Spokesman) self._spokesman.state = state self._spokesman.suggester = self.suggest_new_address self._spokesman.min_keyword_length = spokesman_config.get( "min_keyword_length", self._spokesman.min_keyword_length) self._spokesman.max_query_length = spokesman_config.get( "max_query_length", self._spokesman.max_query_length) self._spokesman.max_page_size = spokesman_config.get( "max_page_size", self._spokesman.max_page_size) self._spokesman.max_keywords = spokesman_config.get( "max_keywords", self._spokesman.max_keywords) if Component.MIRROR_SERVER in components: self._mirror_server = self._client.summon(mirror.MirrorServer) self._mirror_server.publish_target = aioxmpp.JID.fromstr( mirror_config["server"]["pubsub_service"], ) self._mirror_server.state = state if Component.MIRROR_CLIENT in components: self._mirror_client = self._client.summon(mirror.MirrorClient) self._mirror_client.source = aioxmpp.JID.fromstr( mirror_config["client"]["pubsub_service"], ) self._mirror_client.state = state if prometheus_config.get("enable", False): bind_host = prometheus_config["bind_address"] bind_port = prometheus_config["port"] self._prometheus_app = self._setup_prometheus(bind_host, bind_port) if prometheus_config.get("state_metrics", False): import prometheus_client prometheus_client.REGISTRY.register( muchopper.bot.state.StateMetricsCollector(self._state)) else: self._prometheus_app = None version_svc = self._client.summon(aioxmpp.VersionServer) version_svc.name = "search.jabber.network Crawler" version_svc.version = "0.1.0" version_svc.os = "" self._analysis_pool = worker_pool.WorkerPool( 16, self._analyse_address, delay=0.5, max_queue_size=128, logger=self.logger.getChild("analysis"), )