Example #1
0
 def __init__(self, jid, password, relations, algorithm, name):
     ClientXMPP.__init__(self, jid, password)
     ''' Add all event handlers, nickname and
 start reciever in alumnchat '''
     self.add_event_handler('session_start', self.session_start)
     self.add_event_handler('message', self.message)
     self.room = 'alumnos'
     self.current_reciever = 'alumchat.xyz'
     self.auto_subscribe = True
     self.relations = relations
     self.algorithm_name = algorithm
     self.algorithm = getAlgorithm(algorithm)
     self.serial = 1
     self.neighbours = getNeighbours(relations, name)
     self.graph = Graph()
     self.name = name
     self.lsps = {}
     # Functions sent as arguments to main menu
     functions = {
         'dc': self.dc_and_exit,
         'list': self.get_contacts,
         'add': self.add_contact,
         'rm': self.delete_account,
         'send_message': self.message_sender,
         'jc': self.join_conversation,
         'find': self.start_algorithm,
         'd': self.direct_message
     }
     self.menuInstance = Thread(target=menu, args=(functions, ))
     self.add_event_handler('register', self.register)
Example #2
0
    def __init__(self, jid, password, shell):
        ClientXMPP.__init__(self, jid, password)

        self.shell = shell
        self.add_event_handler("session_start", self.session_start)
        self.add_event_handler("message", self.message)
        self.add_event_handler("disconnected", self.disconnected)
Example #3
0
 def __init__(self, jid, password, session_config):
     ClientXMPP.__init__(self, jid, password)
     self.jabber_id = jid
     self.add_event_handler("session_start", self.session_start)
     self.add_event_handler("message", self.message)
     self.config_path = session_config
     self.init_session()
Example #4
0
    def __init__(self, jid, password, message_handler, data_dir):

        """
            jid, password : valid account to send and receive messages
            message_handler : a Callable( original_message:Message, decrypted_body )
        """

        ClientXMPP.__init__(self, jid, password)

        self.add_event_handler("session_start", self.session_start)
        self.add_event_handler("message", self.message)

        self.register_plugin('xep_0030') # Service Discovery
        self.register_plugin('xep_0199') # XMPP Ping
        self.register_plugin('xep_0380') # Explicit Message Encryption

        if not os.path.exists(data_dir):
            os.makedirs(data_dir)
        try:
            self.register_plugin(
                'xep_0384',
                {
                    'data_dir': data_dir,
                },
                module=slixmpp_omemo,
            ) # OMEMO
        except (PluginCouldNotLoad,):
            log.exception('And error occured when loading the omemo plugin.')
            sys.exit(1)

        self.message_handler = message_handler
Example #5
0
 def __init__(self, jid, password, nick):
     ClientXMPP.__init__(self, jid, password)
     """ Add all event handlers, nickname and
 start reciever in alumnchat """
     self.add_event_handler("session_start", self.session_start)
     self.add_event_handler("message", self.message)
     self.add_event_handler("socks5_connected", self.stream_opened)
     self.add_event_handler("socks5_data", self.stream_data)
     self.add_event_handler("socks5_closed", self.stream_closed)
     self.room = 'alumnos'
     self.nick = nick
     self.current_reciever = 'alumchat.xyz'
     self.auto_subscribe = True
     # Functions sent as arguments to main menu
     functions = {
         'dc': self.dc_and_exit,
         'list': self.get_contacts,
         'add': self.add_contact,
         'peek': lambda args: print('peekeado hermano'),
         'jr': self.join_room,
         'lr': self.leave_room,
         'cpm': self.change_status,
         'sf': self.send_file,
         'rm': self.delete_account,
         'send_message': self.message_sender,
         'jc': self.join_conversation
     }
     self.menuInstance = Thread(target=menu, args=(functions, ))
Example #6
0
 def __init__(self, jid, password):
     ClientXMPP.__init__(self, jid, password)
     self.register_plugin('xep_0332')    # HTTP over XMPP Transport
     self.add_event_handler(
         'session_start', self.session_start
     )
     self.add_event_handler('http_request', self.http_request_received)
     self.add_event_handler('http_response', self.http_response_received)
Example #7
0
 def __init__(self, jid, password):
     ClientXMPP.__init__(self, jid, password)
     self.register_plugin('xep_0332')    # HTTP over XMPP Transport
     self.add_event_handler(
         'session_start', self.session_start
     )
     self.add_event_handler('http_request', self.http_request_received)
     self.add_event_handler('http_response', self.http_response_received)
Example #8
0
    def __init__(self, bot_configuration):
        ClientXMPP.__init__(self, bot_configuration.jid,
                            bot_configuration.password)

        self.add_event_handler("session_start", self.on_session_start)
        self.add_event_handler("message", self.on_message)

        self.blabler_bot_jid = bot_configuration.blabler_bot_jid
Example #9
0
 def __init__(self, jid: str, password: str, recipient: str, message: str):
     ClientXMPP.__init__(self, jid,
                         password)  # Создание клиента для подключения
     self.connect(disable_starttls=True
                  )  # Подключение к серверу без шифрования disable_starttls
     self.recipient, self.msg = recipient, message  # Перенаправление аргументов в среду self
     self.add_event_handler("session_start",
                            self.session_start)  # Метод запуска сессии
Example #10
0
 def __init__(self, jid, password, debug_log, mto):
     '''
     Connect to XMPP server, and set up callbacks
     '''
     self.debug_log = debug_log
     self.mto = mto
     ClientXMPP.__init__(self, jid, password)
     self.add_event_handler("session_start", self.session_start)
     self.add_event_handler("message", self.message)
Example #11
0
 def __init__(self, jid: str, password: str, i_answer_obj=False):
     ClientXMPP.__init__(self, jid,
                         password)  # Создание клиента для подключения
     self.connect(disable_starttls=True
                  )  # Подключение к серверу без шифрования disable_starttls
     self.jid, self.i_answer_obj = jid, i_answer_obj  # Переопределяем аргументы в локальные переменные
     self.add_event_handler("session_start",
                            self.session_start)  # Метод запуска сессии
     self.add_event_handler("message",
                            self.message)  # Метод для обработки сообщений
Example #12
0
 def __init__(self, jid, password, debug_log=lambda x: None):
     '''
     Log into XMPP server on localhost with username `jid`, and
     password `password.` If 'debug_log' is passed, pass log
     messages to that callback.
     '''
     self.debug_log = debug_log
     ClientXMPP.__init__(self, jid, password)
     self.add_event_handler("session_start", self.session_start)
     self.add_event_handler("message", self.message)
     self.msg_future = self.new_future()
Example #13
0
 def __init__(self, sender_id, server_key):
     self.sent_count = 0
     self.draining = False
     ClientXMPP.__init__(self, sender_id + '@fcm.googleapis.com',
                         server_key)
     self.default_port = 5235
     self.connected_future = asyncio.Future()
     self.add_event_handler("session_start", self.session_start)
     self.add_event_handler("message", self.message)
     self.register_handler(
         Callback('FCM Message', StanzaPath('message'), self.fcm_message))
Example #14
0
    def __init__(self, cfg: RavenJabberConfig):
        ClientXMPP.__init__(self, cfg.username, cfg.password)
        self.use_message_ids = True
        self.use_ssl = True

        self.rooms = None
        self.nick = cfg.nickname
        self.remote_api = RavenOpenApi()

        # session start disconnect events.
        self.add_event_handler('session_start', self.start_session)
        # register receive handler for both groupchat and normal message events.
        self.add_event_handler('message', self.message)
Example #15
0
    def __init__(self, jid, password, main_bridge):
        ClientXMPP.__init__(self, jid, password)

        self.main_bridge = main_bridge

        self.add_event_handler("session_start", self.session_started)
        self.add_event_handler("message", self.message_received)
        self.add_event_handler("connection_failed", self.connection_failed)
        self.add_event_handler("failed_auth", self.auth_failed)

        self.register_plugin('xep_0030')  # Service Discovery
        self.register_plugin('xep_0045')  # Multi-User Chat
        self.register_plugin('xep_0199')  # XMPP Ping
Example #16
0
    def __init__(self, jid, password, main_bridge):
        ClientXMPP.__init__(self, jid, password)

        self.main_bridge = main_bridge

        self.add_event_handler("session_start", self.session_started)
        self.add_event_handler("message", self.message_received)
        self.add_event_handler("connection_failed", self.connection_failed)
        self.add_event_handler("failed_auth", self.auth_failed)

        self.register_plugin('xep_0030')  # Service Discovery
        self.register_plugin('xep_0045')  # Multi-User Chat
        self.register_plugin('xep_0199')  # XMPP Ping
Example #17
0
    def __init__(self, jid, password, make_authorize_uri, get_load_curve,
                 get_daily):
        ClientXMPP.__init__(self, jid, password)

        self.add_event_handler("session_start", self.session_start)

        self.register_plugin('xep_0004')
        self.register_plugin('xep_0050')
        self.register_plugin('xep_0199', {'keepalive': True, 'frequency': 15})

        self.authorize_uri_handler = AuthorizeUriCommandHandler(
            self, make_authorize_uri)
        self.load_curve_handler = LoadCurveCommandHandler(self, get_load_curve)
        self.daily_handler = DailyCommandHandler(self, get_daily)
Example #18
0
    def __init__(self, jid: str, password: str, nick: str, db: DBManager,
                 dbot: DeltaBot) -> None:
        ClientXMPP.__init__(self, jid, password)
        self.nick = nick
        self.db = db
        self.dbot = dbot
        self.add_event_handler('session_start', self.on_session_start)
        self.add_event_handler('message', self.on_message)
        self.add_event_handler('disconnected', self.on_disconnected)

        self.register_plugin('xep_0045')  # Multi-User Chat
        self.register_plugin('xep_0054')  # vcard-temp
        self.register_plugin('xep_0363')  # HTTP File Upload
        self.register_plugin('xep_0128')  # Service Discovery Extensions
Example #19
0
    def __init__(self, jid, password, cmdparser, connection):
        ClientXMPP.__init__(self, jid, password)
#        cmdparser.registerCommand([("muc", ), ("join", "Joins a given MUC", self.cmdjoinMuc)])

        self.cmdparser = cmdparser
        self.connection = connection
        self.cursor = connection.cursor()
        self.register_plugin('xep_0045')

        self.add_event_handler("session_start", self.session_start)
        self.add_event_handler("message", self.message)
        self.add_event_handler('groupchat_message', self.mucmessage)

        self.cursor.execute("CREATE TABLE IF NOT EXISTS MUC(Id INT, MUC TEXT, Nick TEXT, Pass TEXT)")
Example #20
0
def cancel_config(xmpp: ClientXMPP, room: str) -> None:
    query = ET.Element('{http://jabber.org/protocol/muc#owner}query')
    x = ET.Element('{jabber:x:data}x', type='cancel')
    query.append(x)
    iq = xmpp.make_iq_set(query)
    iq['to'] = room
    iq.send()
Example #21
0
def set_user_affiliation(
    xmpp: ClientXMPP,
    muc_jid: JID,
    affiliation: str,
    callback: Callable[[Iq], None],
    nick: Optional[str] = None,
    jid: Optional[JID] = None,
    reason: Optional[str] = None
) -> None:
    """
    (try to) Set the affiliation of a MUC user
    """
    muc_jid = safeJID(muc_jid)
    query = ET.Element('{http://jabber.org/protocol/muc#admin}query')
    if nick:
        item = ET.Element('{http://jabber.org/protocol/muc#admin}item', {
            'affiliation': affiliation,
            'nick': nick
        })
    else:
        item = ET.Element('{http://jabber.org/protocol/muc#admin}item', {
            'affiliation': affiliation,
            'jid': str(jid)
        })

    if reason:
        reason_item = ET.Element(
            '{http://jabber.org/protocol/muc#admin}reason')
        reason_item.text = reason
        item.append(reason_item)

    query.append(item)
    iq = xmpp.make_iq_set(query)
    iq['to'] = muc_jid
    iq.send(callback=callback)
Example #22
0
    def __init__(self, broadcast_msg):
        self.broadcast_msg = broadcast_msg
        self.conn_lock = asyncio.Lock()
        # force locking now
        # it seems that the xmpp server really doesn't like it when you send messages
        # before the setup is complete, so lock everything until we've authed and joined all the rooms.
        [_ for _ in self.conn_lock.acquire()]

        self.c = ClientXMPP(self.jabber_id, self.password)
        self.c.register_plugin('xep_0030')  # Service Discovery
        self.c.register_plugin('xep_0045')  # Multi-User Chat
        self.c.register_plugin('xep_0199')  # XMPP Ping
        self.c.register_plugin('xep_0203')  # XMPP Delayed messages
        self.c.register_plugin('xep_0249')  # XMPP direct MUC invites

        self.c.auto_authorize = True
        self.c.auto_subscribe = True

        self.c.whitespace_keepalive = True
        self.c.whitespace_keepalive_interval = 60

        self.c.add_event_handler('session_bind', self.session_start)
        self.c.add_event_handler('session_bind', self.c._start_keepalive)

        for room, _ in self.rooms:
            self.c.add_event_handler('muc::{}::message'.format(room), self.muc_message)
            self.c.add_event_handler('muc::{}::got_offline'.format(room), functools.partial(self.send_presence, 'parted'))
            self.c.add_event_handler('muc::{}::got_online'.format(room), functools.partial(self.send_presence, 'joined'))

        self.c.connect()
Example #23
0
def destroy_room(
    xmpp: ClientXMPP,
    room: str,
    reason: str = '',
    altroom: str = ''
) -> bool:
    """
    destroy a room
    """
    room = safeJID(room)
    if not room:
        return False
    iq = xmpp.make_iq_set()
    iq['to'] = room
    query = ET.Element('{%s}query' % NS_MUC_OWNER)
    destroy = ET.Element('{%s}destroy' % NS_MUC_OWNER)
    if altroom:
        destroy.attrib['jid'] = altroom
    if reason:
        xreason = ET.Element('{%s}reason' % NS_MUC_OWNER)
        xreason.text = reason
        destroy.append(xreason)
    query.append(destroy)
    iq.append(query)

    def callback(iq: Iq) -> None:
        if not iq or iq['type'] == 'error':
            xmpp.core.information('Unable to destroy room %s' % room, 'Info')
        else:
            xmpp.core.information('Room %s destroyed' % room, 'Info')

    iq.send(callback=callback)
    return True
Example #24
0
def change_subject(xmpp: ClientXMPP, jid: JID, subject: str) -> None:
    """
    Change the room subject
    """
    jid = safeJID(jid)
    msg = xmpp.make_message(jid)
    msg['type'] = 'groupchat'
    msg['subject'] = subject
    msg.send()
Example #25
0
def configure_room(xmpp: ClientXMPP, room: str, form: 'Form') -> None:
    if form is None:
        return
    iq = xmpp.make_iq_set()
    iq['to'] = room
    query = ET.Element('{http://jabber.org/protocol/muc#owner}query')
    form['type'] = 'submit'
    query.append(form.xml)
    iq.append(query)
    iq.send()
Example #26
0
    def __init__(
        self,
        jid,
        password,
        feature=None,
        keepalive=None,
        ca_cert=None,
        server=None,
        use_ipv6=None,
        bot=None,
        ssl_version=None,
    ):
        if feature is None:
            feature = {}
        self._bot = bot
        self.connected = False
        self.server = server
        self.client = ClientXMPP(
            jid, password, plugin_config={"feature_mechanisms": feature}
        )
        self.client.register_plugin("xep_0030")  # Service Discovery
        self.client.register_plugin("xep_0045")  # Multi-User Chat
        self.client.register_plugin("xep_0199")  # XMPP Ping
        self.client.register_plugin("xep_0203")  # XMPP Delayed messages
        self.client.register_plugin("xep_0249")  # XMPP direct MUC invites

        if keepalive is not None:
            self.client.whitespace_keepalive = (
                True  # Just in case Slixmpp's default changes to False in the future
            )
            self.client.whitespace_keepalive_interval = keepalive

        if use_ipv6 is not None:
            self.client.use_ipv6 = use_ipv6

        if ssl_version:
            self.client.ssl_version = ssl_version

        self.client.ca_certs = ca_cert  # Used for TLS certificate validation

        self.client.add_event_handler("session_start", self.session_start)
Example #27
0
def get_room_form(xmpp: ClientXMPP, room: str, callback: Callable[[Iq], Any]):
    def _cb(result):
        if result["type"] == "error":
            return callback(None)
        xform = result.xml.find(
            '{http://jabber.org/protocol/muc#owner}query/{jabber:x:data}x')
        if xform is None:
            return callback(None)
        form = xmpp.plugin['xep_0004'].build_form(xform)
        return callback(form)

    iq = xmpp.make_iq_get(ito=room)
    query = ET.Element('{http://jabber.org/protocol/muc#owner}query')
    iq.append(query)
    iq.send(callback=_cb)
Example #28
0
def change_show(
    xmpp: ClientXMPP,
    jid: JID,
    own_nick: str,
    show: str,
    status: Optional[str]
) -> None:
    """
    Change our 'Show'
    """
    jid = safeJID(jid)
    pres = xmpp.make_presence(pto='%s/%s' % (jid, own_nick))
    if show:  # if show is None, don't put a <show /> tag. It means "available"
        pres['type'] = show
    if status:
        pres['status'] = status
    pres.send()
Example #29
0
def set_user_role(
    xmpp: ClientXMPP,
    jid: JID,
    nick: str,
    reason: str,
    role: str,
    callback: Callable[[Iq], None]
) -> None:
    """
    (try to) Set the role of a MUC user
    (role = 'none': eject user)
    """
    jid = safeJID(jid)
    iq = xmpp.make_iq_set()
    query = ET.Element('{%s}query' % NS_MUC_ADMIN)
    item = ET.Element('{%s}item' % NS_MUC_ADMIN, {'nick': nick, 'role': role})
    if reason:
        reason_el = ET.Element('{%s}reason' % NS_MUC_ADMIN)
        reason_el.text = reason
        item.append(reason_el)
    query.append(item)
    iq.append(query)
    iq['to'] = jid
    iq.send(callback=callback)
Example #30
0
    def __init__(self, jid, password):
        """Initialize the client."""
        ClientXMPP.__init__(self, jid, password)

        self.add_event_handler("session_start", self.session_start)
        self.add_event_handler("message", self.message)
Example #31
0
    def stream_start(self,
                     mode='client',
                     skip=True,
                     header=None,
                     socket='mock',
                     jid='tester@localhost/resource',
                     password='******',
                     server='localhost',
                     port=5222,
                     sasl_mech=None,
                     plugins=None,
                     plugin_config={}):
        """
        Initialize an XMPP client or component using a dummy XML stream.

        Arguments:
            mode     -- Either 'client' or 'component'. Defaults to 'client'.
            skip     -- Indicates if the first item in the sent queue (the
                        stream header) should be removed. Tests that wish
                        to test initializing the stream should set this to
                        False. Otherwise, the default of True should be used.
            socket   -- Either 'mock' or 'live' to indicate if the socket
                        should be a dummy, mock socket or a live, functioning
                        socket. Defaults to 'mock'.
            jid      -- The JID to use for the connection.
                        Defaults to 'tester@localhost/resource'.
            password -- The password to use for the connection.
                        Defaults to 'test'.
            server   -- The name of the XMPP server. Defaults to 'localhost'.
            port     -- The port to use when connecting to the server.
                        Defaults to 5222.
            plugins  -- List of plugins to register. By default, all plugins
                        are loaded.
        """
        if not plugin_config:
            plugin_config = {}

        if mode == 'client':
            self.xmpp = ClientXMPP(jid,
                                   password,
                                   sasl_mech=sasl_mech,
                                   plugin_config=plugin_config)
        elif mode == 'component':
            self.xmpp = ComponentXMPP(jid,
                                      password,
                                      server,
                                      port,
                                      plugin_config=plugin_config)
        else:
            raise ValueError("Unknown XMPP connection mode.")

        self.xmpp.connection_made(TestTransport(self.xmpp))
        self.xmpp.session_bind_event.set()
        # Remove unique ID prefix to make it easier to test
        self.xmpp._id_prefix = ''
        self.xmpp.default_lang = None
        self.xmpp.peer_default_lang = None

        def new_id():
            self.xmpp._id += 1
            return str(self.xmpp._id)

        self.xmpp._id = 0
        self.xmpp.new_id = new_id

        # Must have the stream header ready for xmpp.process() to work.
        if not header:
            header = self.xmpp.stream_header

        self.xmpp.data_received(header)
        self.wait_for_send_queue()

        if skip:
            self.xmpp.socket.next_sent()
            if mode == 'component':
                self.xmpp.socket.next_sent()

        if plugins is None:
            self.xmpp.register_plugins()
        else:
            for plugin in plugins:
                self.xmpp.register_plugin(plugin)

        # Some plugins require messages to have ID values. Set
        # this to True in tests related to those plugins.
        self.xmpp.use_message_ids = False
        self.xmpp.use_presence_ids = False
Example #32
0
class XMPPConnection(object):
    def __init__(self,
                 jid,
                 password,
                 feature=None,
                 keepalive=None,
                 ca_cert=None,
                 server=None,
                 use_ipv6=None,
                 bot=None,
                 ssl_version=None):
        if feature is None:
            feature = {}
        self._bot = bot
        self.connected = False
        self.server = server
        self.client = ClientXMPP(jid,
                                 password,
                                 plugin_config={'feature_mechanisms': feature})
        self.client.register_plugin('xep_0030')  # Service Discovery
        self.client.register_plugin('xep_0045')  # Multi-User Chat
        self.client.register_plugin('xep_0199')  # XMPP Ping
        self.client.register_plugin('xep_0203')  # XMPP Delayed messages
        self.client.register_plugin('xep_0249')  # XMPP direct MUC invites

        if keepalive is not None:
            self.client.whitespace_keepalive = True  # Just in case Slixmpp's default changes to False in the future
            self.client.whitespace_keepalive_interval = keepalive

        if use_ipv6 is not None:
            self.client.use_ipv6 = use_ipv6

        if ssl_version:
            self.client.ssl_version = ssl_version

        self.client.ca_certs = ca_cert  # Used for TLS certificate validation

        self.client.add_event_handler("session_start", self.session_start)

    def session_start(self, _):
        self.client.send_presence()
        self.client.get_roster()

    def connect(self):
        if not self.connected:
            if self.server is not None:
                self.client.connect(self.server)
            else:
                self.client.connect()
            self.connected = True
        return self

    def disconnect(self):
        self.client.disconnect(wait=True)
        self.connected = False

    def serve_forever(self):
        self.client.process()

    def add_event_handler(self, name, cb):
        self.client.add_event_handler(name, cb)

    def del_event_handler(self, name, cb):
        self.client.del_event_handler(name, cb)
Example #33
0
class HipchatClient(object):
    def __init__(self, broadcast_msg):
        self.broadcast_msg = broadcast_msg
        self.conn_lock = asyncio.Lock()
        # force locking now
        # it seems that the xmpp server really doesn't like it when you send messages
        # before the setup is complete, so lock everything until we've authed and joined all the rooms.
        [_ for _ in self.conn_lock.acquire()]

        self.c = ClientXMPP(self.jabber_id, self.password)
        self.c.register_plugin('xep_0030')  # Service Discovery
        self.c.register_plugin('xep_0045')  # Multi-User Chat
        self.c.register_plugin('xep_0199')  # XMPP Ping
        self.c.register_plugin('xep_0203')  # XMPP Delayed messages
        self.c.register_plugin('xep_0249')  # XMPP direct MUC invites

        self.c.auto_authorize = True
        self.c.auto_subscribe = True

        self.c.whitespace_keepalive = True
        self.c.whitespace_keepalive_interval = 60

        self.c.add_event_handler('session_bind', self.session_start)
        self.c.add_event_handler('session_bind', self.c._start_keepalive)

        for room, _ in self.rooms:
            self.c.add_event_handler('muc::{}::message'.format(room), self.muc_message)
            self.c.add_event_handler('muc::{}::got_offline'.format(room), functools.partial(self.send_presence, 'parted'))
            self.c.add_event_handler('muc::{}::got_online'.format(room), functools.partial(self.send_presence, 'joined'))

        self.c.connect()

    def session_start(self, event):
        self.c.send_presence()
        self.c.get_roster()

        for room, password in self.rooms:
            self.c.plugin['xep_0045'].joinMUC(room, self.nickname, password=password, wait=True)
        self.conn_lock.release()

    def muc_message(self, msg):
        # yes, this is how you check to see if 'delay' is set on a message.
        # this API is dumb
        if isinstance(msg['delay']['stamp'], datetime.datetime):
            return
        if msg['from'].resource == self.nickname:
            return
        self.broadcast_msg(self.format_msg(msg))

    def format_msg(self, msg):
        return '({0}) {1}'.format(msg['from'].resource, msg['body'])

    def format_presence(self, user, status):
        return '*** {0} has {1}'.format(user, status)

    def send_presence(self, status, msg):
        self.broadcast_msg(self.format_presence(msg['from'].resource, status))

    @asyncio.coroutine
    def send_msg(self, msg):
        with (yield from self.conn_lock):
            for room, _ in self.rooms:
                self.c.send_message(mto=room, mbody=msg, mtype='groupchat')
    def __init__(self, jid, password):
        ClientXMPP.__init__(self, jid, password)

        self.add_event_handler("session_start", self.session_start)
        self.register_plugin('xep_0045')
Example #35
0
    def __init__(self, jid, password, nick, rooms, MUC_name, Ignored):
        ClientXMPP.__init__(self, jid, password)
        self.nickname = nick
        self.room_names = rooms
        self.MUC = MUC_name

        self.model = {}
        self.char2idx = {}
        self.idx2char = {}
        self.Ignored = Ignored
        for room_name in self.room_names:
            vocab_filepath = checkpoint_dir + '/vocab_' + room_name + '.npy'
            if os.path.isfile(vocab_filepath):
                vocab = np.load(
                    vocab_filepath)  # The unique characters in the file
            else:
                print("Could not find vocab file at: " + vocab_filepath)
                exit()
            vocab_size = len(vocab)  # Length of the vocabulary in chars
            # Creating a mapping from unique characters to indices
            self.char2idx[room_name] = {u: i for i, u in enumerate(vocab)}
            self.idx2char[room_name] = np.array(vocab)

            self.model[room_name] = build_model(vocab_size,
                                                embedding_dim,
                                                batch_size=1)
            checkpoint_file = checkpoint_dir + "/weights_" + room_name + ".h5"
            if os.path.isfile(checkpoint_file):
                self.model[room_name].load_weights(checkpoint_file)
            else:
                print("Could not find checkpoint file: " + checkpoint_file)
                exit()
            self.model[room_name].build(tf.TensorShape([1, None]))
            text = ""
            logfile = regex.compile(
                regex.escape(room_name) + r'@' + regex.escape(MUC) +
                r'-\d\d\d\d-\d\d-\d\d\.log')
            for file in sorted(os.listdir(logs_dir), reverse=True):
                match = logfile.search(file)
                if match != None and match.span()[0] == 0:
                    print("Parsing " + file + " for inference initialisation")
                    text = open(logs_dir + '/' + file).read() + text
                    if len(text) >= Initialisation_Length:
                        break
            init_text = ""
            segment_counter = 2
            while len(init_text) - init_text.find(
                    '\n') < Initialisation_Length:
                start_idx = max(
                    0,
                    len(text) - segment_counter * Initialisation_Length)
                init_text = text[start_idx:]
                segment_counter += 1
            init_text = init_text[text.find('\n') + 1:]
            init_text = Filter_Logs(init_text)
            init_text = init_text[len(init_text) - Initialisation_Length:]
            init_text = init_text[init_text.find('\n') + 1:]
            if len(init_text) > 0:
                Feed_Model(
                    self.model[room_name], init_text,
                    self.char2idx[room_name])  #Give the model some state
        if Test:
            first_room = self.room_names[0]
            Test_Bot(self.model[first_room], self.idx2char[first_room],
                     self.char2idx[first_room])
        self.register_plugin('xep_0045')
        self.add_event_handler("session_start", self.session_start)
        self.add_event_handler("message", self.message)
        self.add_event_handler("groupchat_message", self.muc_message)
        self.add_event_handler("session_end", self.crash)
        self.add_event_handler("socket_error", self.crash)
        self.add_event_handler("disconnected", self.crash)
        self.add_event_handler("stream_error", self.crash)
        self.add_event_handler("killed", self.crash)
        self.add_event_handler("connection_failed", self.crash)
        self.add_event_handler("close", self.crash)
Example #36
0
 def __init__(self, jid, password, recipient, msg):
     ClientXMPP.__init__(self, jid, password)
     self.recipient = recipient
     self.msg = msg
     self.add_event_handler("session_start", self.session_start)