Search code examples
pythonodooodoo-12sendmessage

Odoo - How can i send a custom message to followers


I want to send a cuustom message to followers when record is created My class :

class StockAlert(models.Model):
    _name = "stock.alert"
    _inherit = ['mail.thread', 'mail.activity.mixin']

    responsable_id = fields.Many2one('res.users' ,store=True)

    @api.multi
    def write(self, vals):
      result = super(StockAlert, self).write(vals)
      for record in self:
          followers= []
          if record.responsable_id.partner_id.id not in record.message_follower_ids.ids:
              followers.append(record.responsable_id.partner_id.id)
          record.message_subscribe(followers)
      return result

    @api.model
    def create(self, vals):
      result = super(StockAlert, self).create(vals)
      for record in result:
          followers= []
          if record.responsable_id.partner_id.id not in record.message_follower_ids.ids:
              followers.append(record.responsable_id.partner_id.id)
          record.message_subscribe(followers)
      return result

Called the chatter on my view :

<div class="oe_chatter">
            <field name="message_follower_ids" widget="mail_followers"/>
             <field name="activity_ids" widget="mail_activity"/>
            <field name="message_ids" widget="mail_thread"/>          
          </div>

Any help please !


Solution

  • I'm not fully sure the follower subscription is correct this way, but posting a message should be very easy. Right after the subscription do:

    record.message_post(body)  # body should be a string
    

    Look right into the defintion of message_post to get more possible parameters like subject or partner_ids.

    partner_ids could be interesting for you, because this parameter can be used to autosubscribe on message_post. For example in create:

    @api.model
    def create(self, vals):
        result = super().create(vals)
        for record in result:
            partner_ids = record.responsable_id.partner_id.ids
            body = 'hello world'
            record.with_context(mail_post_autofollow=1).message_post(
                body, partner_ids=partner_ids)
        return result