Skip to Content
Odoo Menú
  • Registra entrada
  • Prova-ho gratis
  • Aplicacions
    Finances
    • Comptabilitat
    • Facturació
    • Despeses
    • Full de càlcul (IA)
    • Documents
    • Signatura
    Vendes
    • CRM
    • Vendes
    • Punt de venda per a botigues
    • Punt de venda per a restaurants
    • Subscripcions
    • Lloguer
    Imatges de llocs web
    • Creació de llocs web
    • Comerç electrònic
    • Blog
    • Fòrum
    • Xat en directe
    • Aprenentatge en línia
    Cadena de subministrament
    • Inventari
    • Fabricació
    • PLM
    • Compres
    • Manteniment
    • Qualitat
    Recursos humans
    • Empleats
    • Reclutament
    • Absències
    • Avaluacions
    • Recomanacions
    • Flota
    Màrqueting
    • Màrqueting Social
    • Màrqueting per correu electrònic
    • Màrqueting per SMS
    • Esdeveniments
    • Automatització del màrqueting
    • Enquestes
    Serveis
    • Projectes
    • Fulls d'hores
    • Servei de camp
    • Suport
    • Planificació
    • Cites
    Productivitat
    • Converses
    • Validacions
    • IoT
    • VoIP
    • Coneixements
    • WhatsApp
    Aplicacions de tercers Odoo Studio Plataforma d'Odoo al núvol
  • Sectors
    Comerç al detall
    • Llibreria
    • Botiga de roba
    • Botiga de mobles
    • Botiga d'ultramarins
    • Ferreteria
    • Botiga de joguines
    Food & Hospitality
    • Bar i pub
    • Restaurant
    • Menjar ràpid
    • Guest House
    • Distribuïdor de begudes
    • Hotel
    Real Estate
    • Real Estate Agency
    • Estudi d'arquitectura
    • Construcció
    • Gestió immobiliària
    • Jardineria
    • Associació de propietaris de béns immobles
    Consulting
    • Accounting Firm
    • Partner d'Odoo
    • Agència de màrqueting
    • Bufet d'advocats
    • Captació de talent
    • Auditoria i certificació
    Fabricació
    • Textile
    • Metal
    • Furnitures
    • Food
    • Brewery
    • Regals corporatius
    Salut i fitness
    • Club d'esport
    • Òptica
    • Centre de fitness
    • Especialistes en benestar
    • Farmàcia
    • Perruqueria
    Trades
    • Servei de manteniment
    • Hardware i suport informàtic
    • Solar Energy Systems
    • Shoe Maker
    • Serveis de neteja
    • HVAC Services
    Others
    • Nonprofit Organization
    • Agència del medi ambient
    • Lloguer de panells publicitaris
    • Fotografia
    • Lloguer de bicicletes
    • Distribuïdors de programari
    Browse all Industries
  • Comunitat
    Aprèn
    • Tutorials
    • Documentació
    • Certificacions
    • Formació
    • Blog
    • Pòdcast
    Potenciar l'educació
    • Programa educatiu
    • Scale-Up! El joc empresarial
    • Visita Odoo
    Obtindre el programari
    • Descarregar
    • Comparar edicions
    • Novetats de les versions
    Col·laborar
    • GitHub
    • Fòrum
    • Esdeveniments
    • Traduccions
    • Converteix-te en partner
    • Services for Partners
    • Registra la teva empresa comptable
    Obtindre els serveis
    • Troba un partner
    • Troba un comptable
    • Contacta amb un expert
    • Serveis d'implementació
    • Referències del client
    • Suport
    • Actualitzacions
    Github Youtube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Programar una demo
  • Preus
  • Ajuda

Odoo is the world's easiest all-in-one management software.
It includes hundreds of business apps:

  • CRM
  • e-Commerce
  • Comptabilitat
  • Inventari
  • PoS
  • Projectes
  • MRP
All apps
You need to be registered to interact with the community.
All Posts People Badges
Etiquetes (View all)
odoo accounting v14 pos v15
About this forum
You need to be registered to interact with the community.
All Posts People Badges
Etiquetes (View all)
odoo accounting v14 pos v15
About this forum
Ajuda

Sending chatter message

Subscriure's

Get notified when there's activity on this post

This question has been flagged
chatterChatterodoo17Odoo17odoo17EEOdoo 17.0+e (Enterprise Edition)
2 Respostes
882 Vistes
Avatar
OdooIntern

i have this function trigger_test_notif for testing and send_chatter_message for sending the chatter a message but on some browser it is just not converting to absolute link like when i send it from chrome or brave to other browser it works but when i do it from safari,firefox,explorer it just doesnt convert to absolute link just showing the url as string. Also is there any way i can just send message to multiple people but 1-to-many instead of looping through 1-to-1

def trigger_test_notif(self):

self.ensure_one()

partner_ids = None

message = 'TEST MESSGAE'

message_type = 'with_link'

user_ids = None

if user_ids is None and partner_ids is None:

user_ids = [2, 6, 186]

return self.send_chatter_message(user_ids, partner_ids, message, message_type)


def send_chatter_message(self, user_ids, partner_ids, message, message_type):

self.ensure_one()

if partner_ids:

if hasattr(partner_ids, 'ids'):

partners = partner_ids

elif isinstance(partner_ids, (list, tuple, set)):

flat = []

for p in partner_ids:

if isinstance(p, (list, tuple, set)):

flat.extend(p)

else:

flat.append(p)

partners = self.env['res.partner'].browse([int(x) for x in flat if x])

else:

partners = self.env['res.partner'].browse([int(partner_ids)])

else:

if user_ids:

if isinstance(user_ids, (list, tuple, set)):

u_ids = [int(u) for u in user_ids if u]

else:

u_ids = [int(user_ids)]

else:

u_ids = []

users = self.env['res.users'].browse(u_ids)

partners = users.mapped('partner_id')

if not partners:

return False

sender_pid = int(self.env.user.partner_id.id)

recipients = partners.filtered(lambda p: p.id != sender_pid)

if not recipients:

return False

text = (message or "").strip()

model_name = self._name

record_link = '/web#id=%s&model=%s&view_type=form' % (self.id, model_name)

base_url = self.env['ir.config_parameter'].sudo().get_param('web.base.url') or ''

if base_url.endswith('/'):

base_url = base_url.rstrip('/')

full_record_url = base_url + record_link if base_url else record_link

if message_type == 'with_link':

display = text or "This is a chat message"

safe_href = full_record_url

body = '<div>%s</div><div><a href="%s" target="_blank" rel="noopener">Open record</a></div><div>%s</div>' % (display, safe_href, safe_href)

else:

display = text or "This is a chat message"

body = '<div>%s</div>' % (display)

channel_obj = self.env['discuss.channel'].sudo()

for partner in recipients:

channel_ids = channel_obj.search([

('channel_partner_ids', 'in', [partner.id]),

('channel_partner_ids', 'in', [sender_pid])

]).filtered(lambda r: len(r.channel_partner_ids) == 2).ids

if channel_ids:

ch = channel_obj.browse(channel_ids[0])

else:

vals = {

'channel_type': 'chat',

'name': partner.name + ', ' + self.env.user.name,

'channel_partner_ids': [(4, partner.id), (4, sender_pid)],

}

ch = channel_obj.create(vals)

posted = ch.with_context(mail_create_nosubscribe=True).message_post(

body=body,

message_type='comment',

subtype_xmlid='mail.mt_comment',

author_id=sender_pid,

)

try:

msg = self.env['mail.message'].sudo().browse(posted.id)

msg.write({'body': body})

except Exception as e:

_logger.warning("Failed to overwrite mail.message body id=%s: %s", getattr(posted, 'id', None), e)

return True


0
Avatar
Descartar
Avatar
OdooIntern
Autor Best Answer

when i try the code in database the record is created but i am not getting any chatter message(FYI i have notifications enabled). And when i reverse to my code it sends the message


0
Avatar
Descartar
Avatar
Cybrosys Techno Solutions Pvt.Ltd
Best Answer

Hi,


-Safe HTML escaping so links render properly in all browsers.

-One-to-many group messaging so you can post to multiple people in a single channel instead of looping per partner.


Try the following code,


    def trigger_test_notif(self):

        self.ensure_one()

        partner_ids = None

        message = 'TEST MESSAGE'

        message_type = 'with_link'

        user_ids = None


        if user_ids is None and partner_ids is None:

            user_ids = [2, 6, 186]


        return self.send_chatter_message(user_ids, partner_ids, message, message_type)


    # ---------------------------

    # Send message to partners

    # ---------------------------

    def send_chatter_message(self, user_ids, partner_ids, message, message_type):

        self.ensure_one()


        # Resolve partner_ids from input

        if partner_ids:

            if hasattr(partner_ids, 'ids'):

                partners = partner_ids

            elif isinstance(partner_ids, (list, tuple, set)):

                flat = []

                for p in partner_ids:

                    if isinstance(p, (list, tuple, set)):

                        flat.extend(p)

                    else:

                        flat.append(p)

                partners = self.env['res.partner'].browse([int(x) for x in flat if x])

            else:

                partners = self.env['res.partner'].browse([int(partner_ids)])

        else:

            # Resolve users → partners

            if user_ids:

                if isinstance(user_ids, (list, tuple, set)):

                    u_ids = [int(u) for u in user_ids if u]

                else:

                    u_ids = [int(user_ids)]

            else:

                u_ids = []

            users = self.env['res.users'].browse(u_ids)

            partners = users.mapped('partner_id')


        if not partners:

            return False


        sender_pid = int(self.env.user.partner_id.id)

        recipients = partners.filtered(lambda p: p.id != sender_pid)

        if not recipients:

            return False


        # Build message body safely

        text = (message or "").strip()

        model_name = self._name

        record_link = f"/web#id={self.id}&model={model_name}&view_type=form"


        base_url = self.env['ir.config_parameter'].sudo().get_param('web.base.url') or ''

        if base_url.endswith('/'):

            base_url = base_url.rstrip('/')


        full_record_url = base_url + record_link if base_url else record_link


        if message_type == 'with_link':

            display = html_escape(text or "This is a chat message")

            safe_href = html_escape(full_record_url)

            body = f"""

                <p>{display}</p>

                <p><a href="{safe_href}" target="_blank" rel="noopener">Open record</a></p>

            """

        else:

            display = html_escape(text or "This is a chat message")

            body = f"<p>{display}</p>"


        # Create or reuse a group chat channel with recipients

        channel_obj = self.env['discuss.channel'].sudo()

        recipient_ids = recipients.ids + [sender_pid]


        # Try to find an existing channel with exactly this set of partners

        channel = channel_obj.search([

            ('channel_partner_ids', 'in', recipient_ids),

        ], limit=1)


        if not channel:

            vals = {

                'channel_type': 'chat',

                'name': ', '.join(recipients.mapped('name')) + ', ' + self.env.user.name,

                'channel_partner_ids': [(4, pid) for pid in recipient_ids],

            }

            channel = channel_obj.create(vals)


        # Post message once for all

        posted = channel.with_context(mail_create_nosubscribe=True).message_post(

            body=body,

            message_type='comment',

            subtype_xmlid='mail.mt_comment',

            author_id=sender_pid,

        )


        try:

            msg = self.env['mail.message'].sudo().browse(posted.id)

            msg.write({'body': body})  # enforce consistent body formatting

        except Exception as e:

            _logger.warning("Failed to overwrite mail.message body id=%s: %s", getattr(posted, 'id', None), e)


        return True


    Used html_escape so links always render clickable in Safari, Firefox, IE, Chrome.


    Built a group channel once with all recipients, so you don’t loop user by user.


    Kept compatibility with both user_ids and partner_ids inputs.



Hope it helps



0
Avatar
Descartar
Enjoying the discussion? Don't just read, join in!

Create an account today to enjoy exclusive features and engage with our awesome community!

Registrar-se
Related Posts Respostes Vistes Activitat
Send notification to specific users Solved
odoo17 Odoo17 odoo17EE
Avatar
Avatar
2
de set. 25
1063
How to Find Who Created a "To Do" in Chatter of Products in Sales Module?
sales chatter Chatter Odoo17 To-Do Activities
Avatar
Avatar
1
de set. 25
1094
Notification and websocket error
notification odoo17 Odoo17 odoo17CE odoo17EE
Avatar
0
de set. 25
975
Disable edit/delete messages in chatter
chatter Chatter
Avatar
Avatar
1
de maig 25
2175
Change text of Log Note Button Solved
helpdesk chatter Chatter
Avatar
Avatar
1
de jul. 25
1272
Community
  • Tutorials
  • Documentació
  • Fòrum
Codi obert
  • Descarregar
  • GitHub
  • Runbot
  • Traduccions
Serveis
  • Allotjament a Odoo.sh
  • Suport
  • Actualització
  • Desenvolupaments personalitzats
  • Educació
  • Troba un comptable
  • Troba un partner
  • Converteix-te en partner
Sobre nosaltres
  • La nostra empresa
  • Actius de marca
  • Contacta amb nosaltres
  • Llocs de treball
  • Esdeveniments
  • Pòdcast
  • Blog
  • Clients
  • Informació legal • Privacitat
  • Seguretat
الْعَرَبيّة Català 简体中文 繁體中文 (台灣) Čeština Dansk Nederlands English Suomi Français Deutsch हिंदी Bahasa Indonesia Italiano 日本語 한국어 (KR) Lietuvių kalba Język polski Português (BR) română русский язык Slovenský jazyk slovenščina Español (América Latina) Español ภาษาไทย Türkçe українська Tiếng Việt

Odoo és un conjunt d'aplicacions empresarials de codi obert que cobreix totes les necessitats de la teva empresa: CRM, comerç electrònic, comptabilitat, inventari, punt de venda, gestió de projectes, etc.

La proposta única de valor d'Odoo és ser molt fàcil d'utilitzar i estar totalment integrat, ambdues alhora.

Website made with

Odoo Experience on YouTube

1. Use the live chat to ask your questions.
2. The operator answers within a few minutes.

Live support on Youtube
Watch now