Retrieve a message in a conversation from a user

@param  {String}   userId          User ID
@param  {String}   messageId       Message ID
@param  {Function} callback        Callback function
975750
function(userId, messageId, callback) {
      if (!userId) return callback(new Error(utils.i18n.messages.userId));
      messageId = utils.toUUID(messageId);
      if (!messageId) return callback(new Error(utils.i18n.messages.mid));
      utils.debug('Message getFromUser: ' + userId + ', ' + messageId);

      request.get({
        path: '/users/' + querystring.escape(userId) + '/messages/' + messageId
      }, callback);
    }
92491
public function get(string $userId, string $emailId, array $options = []): ?\Google_Service_Gmail_Message
    {
        try {
            return $this->googleServices->getGoogleServiceGmailForUserId($userId)->users_messages->get($userId, $emailId, $options);
        } catch (\Google_Service_Exception $exception) {
            // message does not exist
            if (404 === $exception->getCode()) {
                return null;
            } else {
                throw $exception;
            }
        }
    }
541696
protected int getUserIdSendError(String username, MessageContext ctx) {
    try {
      return getUser(username).getId();
    } catch (IllegalStateException ex) {
      silent.send(getLocalizedMessage(USER_NOT_FOUND, ctx.user().getLanguageCode(), username), ctx.chatId());
      throw propagate(ex);
    }
  }
275343
public static function delete_message($messageid, $userid, $read = true) {
        global $CFG;

        // Check if private messaging between users is allowed.
        if (empty($CFG->messaging)) {
            throw new moodle_exception('disabled', 'message');
        }

        // Warnings array, it can be empty at the end but is mandatory.
        $warnings = array();

        // Validate params.
        $params = array(
            'messageid' => $messageid,
            'userid' => $userid,
            'read' => $read
        );
        $params = self::validate_parameters(self::delete_message_parameters(), $params);

        // Validate context.
        $context = context_system::instance();
        self::validate_context($context);

        $user = core_user::get_user($params['userid'], '*', MUST_EXIST);
        core_user::require_active_user($user);

        if (\core_message\api::can_delete_message($user->id, $params['messageid'])) {
            $status = \core_message\api::delete_message($user->id, $params['messageid']);
        } else {
            throw new moodle_exception('You do not have permission to delete this message');
        }

        $results = array(
            'status' => $status,
            'warnings' => $warnings
        );
        return $results;
    }
528276
public static function delete_conversations_by_id($userid, array $conversationids) {
        global $CFG;

        // Check if private messaging between users is allowed.
        if (empty($CFG->messaging)) {
            throw new moodle_exception('disabled', 'message');
        }

        // Validate params.
        $params = [
            'userid' => $userid,
            'conversationids' => $conversationids,
        ];
        $params = self::validate_parameters(self::delete_conversations_by_id_parameters(), $params);

        // Validate context.
        $context = context_system::instance();
        self::validate_context($context);

        $user = core_user::get_user($params['userid'], '*', MUST_EXIST);
        core_user::require_active_user($user);

        foreach ($params['conversationids'] as $conversationid) {
            if (\core_message\api::can_delete_conversation($user->id, $conversationid)) {
                \core_message\api::delete_conversation_by_id($user->id, $conversationid);
            } else {
                throw new moodle_exception("You do not have permission to delete the conversation '$conversationid'");
            }
        }

        return [];
    }
151544
function onMessage(userId, msg) {
    var dialogId = msg.dialog_id,
        isForCurrentDialog = isMessageForCurrentDialog(userId, dialogId);

    updateCallState({
        dialogId: dialogId,
        userId: userId,
        active: isForCurrentDialog,
        type: msg.extension.notification_type
    });

    if (!msg.body) return true;

    // check if it's a message for current dialog
    if (isMessageForCurrentDialog(userId, dialogId)) {
        dialogsMessages.push(msg);

        if (msg.markable === 1 && userId != currentUser.id) {
            sendReadStatus(userId, msg.id, dialogId);
        }

        // сheck if it's an attachment
        //
        var messageAttachmentFileId = null;

        if (msg.extension.hasOwnProperty("attachments")) {
            if (msg.extension.attachments.length > 0) {
                messageAttachmentFileId = msg.extension.attachments[0].id;
            }
        }

        showMessage(userId, msg, messageAttachmentFileId);
    }

    // Here we process the regular messages
    //
    updateDialogsList(dialogId, msg.body);

    if (userId != currentUser.id) {
        playSoundOnNewMessage();
    }
}
1188207
function receiveMessageWithApiai(messageText, senderID, event) {
    var trequest = apiaiapp.textRequest(messageText, {
        sessionId: senderID
    });
    trequest.on('response', function(response) {
      
        var message = janis.convertFromApiaiResponseToMessage(response);
        var messageData = {
            recipient: {
                id: senderID
            },
            message: message
        }
        callSendAPI(messageData);

        if (response.result.action == "human") {
            // send a janis alert to your slack channel
            // that the user could use assistance
            janis.assistanceRequested(event);
        } else if (response.result.action == "input.unknown" ||
            (response.result.metadata.intentId == null && response.result.fulfillment.speech == "")) {
            //associate an action in api.ai with your fallback intents so you can catch them.
            //in this example, "input.unknown" is the action set in api.ai on the Default Fallback Intent.
          
            //capture conversational ‘dead-ends’ 
            //and send janis an alert to your slack channel
            janis.logUnknownIntent(event);
        }
    });
    trequest.on('error', function(error) {
        console.log(error);
        //capture conversational ‘dead-ends’ 
        //and send janis an alert to your slack channel
        janis.logUnkownIntent(event);
        sendTextMessage(senderID, error.message);
    });
    trequest.end();
}
1262867
function sendMessages(ID, messageArr, interval) {
	var resArr = [], len = messageArr.length;
	var callback = typeof(arguments[2]) === 'function' ?  arguments[2] :  arguments[3];
	if (typeof(interval) !== 'number') interval = 1000;

	function _sendMessages() {
		setTimeout(function() {
			if (messageArr[0]) {
				bot.sendMessage({
					to: ID,
					message: messageArr.shift()
				}, function(err, res) {
					resArr.push(err || res);
					if (resArr.length === len) if (typeof(callback) === 'function') callback(resArr);
				});
				_sendMessages();
			}
		}, interval);
	}
	_sendMessages();
}
1344078
public function getConversationMessageById($conversationId)
    {
        if ($this->conversation->checkUserExist($this->userId, $conversationId)) {
            $channel = $this->getChannelName($conversationId, 'chat_room');

            return $this->conversation->getConversationMessageById($conversationId, $this->userId, $channel);
        }

        abort(404);
    }
876128
public static function delete_conversation($userid, $otheruserid) {
        global $CFG;

        // Check if private messaging between users is allowed.
        if (empty($CFG->messaging)) {
            throw new moodle_exception('disabled', 'message');
        }

        // Warnings array, it can be empty at the end but is mandatory.
        $warnings = array();

        // Validate params.
        $params = array(
            'userid' => $userid,
            'otheruserid' => $otheruserid,
        );
        $params = self::validate_parameters(self::delete_conversation_parameters(), $params);

        // Validate context.
        $context = context_system::instance();
        self::validate_context($context);

        $user = core_user::get_user($params['userid'], '*', MUST_EXIST);
        core_user::require_active_user($user);

        if (!$conversationid = \core_message\api::get_conversation_between_users([$params['userid'], $params['otheruserid']])) {
            return [];
        }

        if (\core_message\api::can_delete_conversation($user->id, $conversationid)) {
            \core_message\api::delete_conversation_by_id($user->id, $conversationid);
            $status = true;
        } else {
            throw new moodle_exception('You do not have permission to delete messages');
        }

        $results = array(
            'status' => $status,
            'warnings' => $warnings
        );

        return $results;
    }
281266
public function getMessage($messageId)
    {
        $this->buildCall('/incoming-messages');
        $this->buildCall('/'.$messageId);

        $rawMessage = $this->getRequest()->json();

        return $this->makeMessage($rawMessage['Response']['Entry']);
    }
902440
function(userId, params, callback) {
      if (!userId) return callback(new Error(utils.i18n.conversations.userId));
      utils.debug('Conversation getAllFromUser: ' + userId);

      var queryParams = '';
      if (typeof params === 'function') callback = params;
      else queryParams = '?' + querystring.stringify(params);

      request.get({
        path: '/users/' + querystring.escape(userId) + '/conversations' + queryParams
      }, callback);
    }
353421
public void updateMessageStatus(@NonNull final String conversationId, @NonNull final List<MessageStatusUpdate> msgStatusList, @Nullable Callback<ComapiResult<Void>> callback) {
        adapter.adapt(updateMessageStatus(conversationId, msgStatusList), callback);
    }
271126
public static function create_contact_request(int $userid, int $requesteduserid) {
        global $CFG, $USER;

        // Check if messaging is enabled.
        if (empty($CFG->messaging)) {
            throw new moodle_exception('disabled', 'message');
        }

        // Validate context.
        $context = context_system::instance();
        self::validate_context($context);

        $params = ['userid' => $userid, 'requesteduserid' => $requesteduserid];
        $params = self::validate_parameters(self::create_contact_request_parameters(), $params);

        $capability = 'moodle/site:manageallmessaging';
        if (($USER->id != $params['userid']) && !has_capability($capability, $context)) {
            throw new required_capability_exception($context, $capability, 'nopermissions', '');
        }

        $result = [
            'warnings' => []
        ];

        if (!\core_message\api::can_create_contact($params['userid'], $params['requesteduserid'])) {
            $result['warnings'][] = [
                'item' => 'user',
                'itemid' => $params['requesteduserid'],
                'warningcode' => 'cannotcreatecontactrequest',
                'message' => 'You are unable to create a contact request for this user'
            ];
        } else {
            if ($requests = \core_message\api::get_contact_requests_between_users($params['userid'], $params['requesteduserid'])) {
                // There should only ever be one but just in case there are multiple then we can return the first.
                $result['request'] = array_shift($requests);
            } else {
                $result['request'] = \core_message\api::create_contact_request($params['userid'], $params['requesteduserid']);
            }
        }

        return $result;
    }
850362
synchronized boolean deleteMessageForId(String messageId, String userId){
        if(messageId == null || userId == null) return false;

        final String tName = Table.INBOX_MESSAGES.getName();

        try {
            final SQLiteDatabase db = dbHelper.getWritableDatabase();
            db.delete(tName, _ID + " = ? AND " + USER_ID + " = ?", new String[]{messageId,userId});
            return true;
        } catch (final SQLiteException e) {
            getConfigLogger().verbose("Error removing stale records from " + tName, e);
            return false;
        } finally {
            dbHelper.close();
        }
    }
114196
public static function search_messages($userid, $search, $limitfrom = 0, $limitnum = 0) {
        global $DB;

        // Get the user fields we want.
        $ufields = \user_picture::fields('u', array('lastaccess'), 'userfrom_id', 'userfrom_');
        $ufields2 = \user_picture::fields('u2', array('lastaccess'), 'userto_id', 'userto_');
        // Add the uniqueid column to make each row unique and avoid SQL errors.
        $uniqueidsql = $DB->sql_concat('m.id', "'_'", 'm.useridfrom', "'_'", 'mcm.userid');

        $sql = "SELECT $uniqueidsql AS uniqueid, m.id, m.useridfrom, mcm.userid as useridto, m.subject, m.fullmessage,
                       m.fullmessagehtml, m.fullmessageformat, m.smallmessage, m.conversationid, m.timecreated, 0 as isread,
                       $ufields, mub.id as userfrom_blocked, $ufields2, mub2.id as userto_blocked
                  FROM {messages} m
            INNER JOIN {user} u
                    ON u.id = m.useridfrom
            INNER JOIN {message_conversations} mc
                    ON mc.id = m.conversationid
            INNER JOIN {message_conversation_members} mcm
                    ON mcm.conversationid = m.conversationid
            INNER JOIN {user} u2
                    ON u2.id = mcm.userid
             LEFT JOIN {message_users_blocked} mub
                    ON (mub.blockeduserid = u.id AND mub.userid = ?)
             LEFT JOIN {message_users_blocked} mub2
                    ON (mub2.blockeduserid = u2.id AND mub2.userid = ?)
             LEFT JOIN {message_user_actions} mua
                    ON (mua.messageid = m.id AND mua.userid = ? AND mua.action = ?)
                 WHERE (m.useridfrom = ? OR mcm.userid = ?)
                   AND (m.useridfrom != mcm.userid OR mc.type = ?)
                   AND u.deleted = 0
                   AND u2.deleted = 0
                   AND mua.id is NULL
                   AND " . $DB->sql_like('smallmessage', '?', false) . "
              ORDER BY timecreated DESC";

        $params = array($userid, $userid, $userid, self::MESSAGE_ACTION_DELETED, $userid, $userid,
            self::MESSAGE_CONVERSATION_TYPE_SELF, '%' . $search . '%');

        // Convert the messages into searchable contacts with their last message being the message that was searched.
        $conversations = array();
        if ($messages = $DB->get_records_sql($sql, $params, $limitfrom, $limitnum)) {
            foreach ($messages as $message) {
                $prefix = 'userfrom_';
                if ($userid == $message->useridfrom) {
                    $prefix = 'userto_';
                    // If it from the user, then mark it as read, even if it wasn't by the receiver.
                    $message->isread = true;
                }
                $blockedcol = $prefix . 'blocked';
                $message->blocked = $message->$blockedcol ? 1 : 0;

                $message->messageid = $message->id;
                // To avoid duplicate messages, only add the message if it hasn't been added previously.
                if (!array_key_exists($message->messageid, $conversations)) {
                    $conversations[$message->messageid] = helper::create_contact($message, $prefix);
                }
            }
            // Remove the messageid keys (to preserve the expected type).
            $conversations = array_values($conversations);
        }

        return $conversations;
    }
161131
public function send(Conversation $conversation, $body, $userId, $type = 'text')
    {
        $message = $conversation->messages()->create([
            'body' => $body,
            'user_id' => $userId,
            'type' => $type,
        ]);

        $messageWasSent = Chat::sentMessageEvent();
        $message->load('sender');
        $this->raise(new $messageWasSent($message));

        return $message;
    }