Sending Notification Messages
Hooks go in the .module file, the only hooks that can also work in the .theme file are preprocess and alter hooks. 

So if you want the message to be sent when a node is created or updated, use hook_ENTITY_TYPE_presave.

Create a custom module, lets call it "Send Message"

send_message.info.yml

name: 'Send Message'
description: 'Sends the message when a node of Content type Article is created or updated.'
core: 8.x
package: Message
dependencies:
  - message
type: module


send_message.module

&lt;?php

use Drupal\node\NodeInterface;
use Drupal\message\Entity\Message;

/*
 * Implements hook_ENTITY_TYPE_presave()
 */

function send_message_node_presave(NodeInterface $node) {

   if ($node-&gt;getType() == 'article') { // checks if content type is article
      $message = Message::create(['template' =&gt; 'foo_message_type', 'uid' =&gt; $node-&gt;getOwnerId()]);
      $message-&gt;set('field_node_ref', $node);
      $message-&gt;save();
      $notifier = \Drupal::service('message_notify.sender');
      $notifier-&gt;send($message);
   }

}