简体   繁体   中英

How can I send a system response if a user says something? NodeJS/socketio

I want to make it so if a user says a specific thing, the socket.io responds with something.

ex.
Input: !hi
Output: hello!

If there's a way to do this, I would like to know how, thanks!

I tried making something so if a user just presses the send button, it sends "Please type something", it can only be seen by the user typing the space.

var spaced = ' ';

if (spaced) {
  socket.emit('message', {
        username: 'System',
        text: 'Please Type Something',
        timestamp: moment().valueOf()
    });
}

server.js:

var PORT = process.env.PORT || 3000;
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var moment = require('moment');
var connectedUsers = {};

app.use(express.static(__dirname + '/public'));

io.on('connection', function(socket) {
  
  /*var socketId = socket.id;
  var clientIp = socket.request.connection.remoteAddress;

    console.log('A user is connected. - IP: ' + clientIp + " | ID: " + socketId);*/
  console.log('A user is connected.')

    socket.on('disconnect', function() {
        var userData = connectedUsers[socket.id];
        if (typeof userData !== 'undefined') {
            socket.leave(connectedUsers[socket.id]);
            io.to(userData.room).emit('message', {
                username: 'System',
                text: userData.username + ' has left!',
                timestamp: moment().valueOf()
            });
            delete connectedUsers[socket.id];
        }
    });

    socket.on('joinRoom', function(req, callback) {
        if (req.room.replace(/\s/g, "").length > 0 && req.username.replace(/\s/g, "").length > 0) {
            var nameTaken = false;

            Object.keys(connectedUsers).forEach(function(socketId) {
                var userInfo = connectedUsers[socketId];
                if (userInfo.username.toUpperCase() === req.username.toUpperCase()) {
                    nameTaken = true;
                }
            });

            if (nameTaken) {
                callback({
                    nameAvailable: false,
                    error: 'This username is taken, please choose another one.'
                });
            } else {
                connectedUsers[socket.id] = req;
                socket.join(req.room);
                socket.broadcast.to(req.room).emit('message', {
                    username: 'System',
                    text: req.username + ' has joined!',
                    timestamp: moment().valueOf()
                });
                callback({
                    nameAvailable: true
                });
            }
        } else {
            callback({
                nameAvailable: false,
                error: 'Please complete the forum.'
            });
        }
    });

    socket.on('message', function(message) {
        message.timestamp = moment().valueOf();
        io.to(connectedUsers[socket.id].room).emit('message', message);
    });

    socket.emit('message', {
        username: 'System',
        text: 'Ask someone to join this chat room to start talking.',
        timestamp: moment().valueOf()
    });

});

http.listen(PORT, function() {
    console.log('Server started on port ' + PORT);
});

The body in my index.html:

<body>
    <div class="container">
      <div id="login-area">
        <div class="row">
          <div class="large-7 medium-7 small-12 columns small-centered">
            <form id="login-form">
              <h2>Twintails🎀 Bot Chatroom</h2>
              <p id="error-msg"></p>
              <input
                type="text"
                name="username"
                placeholder="Enter your username"
              />
              <input
                type="text"
                name="room"
                placeholder="Enter a chat room name"
              />
              <input type="submit" value="Join Chat" />
            </form>
          </div>
        </div>
      </div>
      <div class="row" id="message-area">
        <div class="large-8 columns small-centered">
          <h2>Twintails🎀 Bot Chatroom</h2>
          <div class="chat-wrap">
            <div class="top">
              <h5 class="room-title"></h5>
            </div>
            <div id="messages"></div>
            <form id="message-form">
              <div class="input-group">
                <input
                  type="text"
                  placeholder="Type message here"
                  class="input-group-field"
                  name="message"
                />
                <div class="input-group-button">
                  <input type="submit" value="Send" />
                </div>
              </div>
            </form>
          </div>
        </div>
      </div>
      <footer>
        <p>
          Add the
          <a href="https://twintails-bot-dashboard.glitch.me/" target="_blank"
            >Twintails🎀 bot!</a
          >
        </p>
        <p>
          Use the 'Mod' room to talk to mods!
        </p>
      </footer>
    </div>
    <script src="/js/jquery.js"></script>
    <script src="/js/socket.io-1.7.3.min.js"></script>
    <script src="/js/moment.min.js"></script>
    <script src="/js/app.js"></script>
    <script src="/js/foundation.min.js"></script>
    <script type="text/javascript">
      $(document).foundation();
    </script>
  </body>

Why not just use a simple if statement?

if (mySocketData === "!hi") {
    socket.emit('Hello!');
}

New to Socket.IO, not sure if this helps, sorry!

If what you're talking about is when the server receives a specific typed message, you want to send a specific response directly back to the user who typed that message, you can just do something like this:

// this is your existing server-side handler which the `if` statement added to it
socket.on('message', function(message) {
    if (message.text === '!hi') {
        socket.emit('message', {
            username: 'System',
            text: 'hello!',
            timestamp: moment().valueOf()
        });
    } else {
        message.timestamp = moment().valueOf();
        io.to(connectedUsers[socket.id].room).emit('message', message);
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM