Ir al contenido
Odoo Menú
  • Iniciar sesión
  • Pruébalo gratis
  • Aplicaciones
    Finanzas
    • Contabilidad
    • Facturación
    • Gastos
    • Hoja de cálculo (BI)
    • Documentos
    • Firma electrónica
    Ventas
    • CRM
    • Ventas
    • PdV para tiendas
    • PdV para restaurantes
    • Suscripciones
    • Alquiler
    Sitios web
    • Creador de sitios web
    • Comercio electrónico
    • Blog
    • Foro
    • Chat en vivo
    • eLearning
    Cadena de suministro
    • Inventario
    • Manufactura
    • PLM
    • Compras
    • Mantenimiento
    • Calidad
    Recursos humanos
    • Empleados
    • Reclutamiento
    • Vacaciones
    • Evaluaciones
    • Referencias
    • Flotilla
    Marketing
    • Redes sociales
    • Marketing por correo
    • Marketing por SMS
    • Eventos
    • Automatización de marketing
    • Encuestas
    Servicios
    • Proyectos
    • Registro de horas
    • Servicio externo
    • Soporte al cliente
    • Planeación
    • Citas
    Productividad
    • Conversaciones
    • Aprobaciones
    • IoT
    • VoIP
    • Artículos
    • WhatsApp
    Aplicaciones externas Studio de Odoo Plataforma de Odoo en la nube
  • Industrias
    Venta minorista
    • Librería
    • Tienda de ropa
    • Mueblería
    • Tienda de abarrotes
    • Ferretería
    • Juguetería
    Alimentos y hospitalidad
    • Bar y pub
    • Restaurante
    • Comida rápida
    • Casa de huéspedes
    • Distribuidora de bebidas
    • Hotel
    Bienes inmuebles
    • Agencia inmobiliaria
    • Estudio de arquitectura
    • Construcción
    • Gestión de bienes inmuebles
    • Jardinería
    • Asociación de propietarios
    Consultoría
    • Firma contable
    • Partner de Odoo
    • Agencia de marketing
    • Bufete de abogados
    • Adquisición de talentos
    • Auditorías y certificaciones
    Manufactura
    • Textil
    • Metal
    • Muebles
    • Comida
    • Cervecería
    • Regalos corporativos
    Salud y ejercicio
    • Club deportivo
    • Óptica
    • Gimnasio
    • Especialistas en bienestar
    • Farmacia
    • Peluquería
    Trades
    • Personal de mantenimiento
    • Hardware y soporte de TI
    • Sistemas de energía solar
    • Zapateros y fabricantes de calzado
    • Servicios de limpieza
    • Servicios de calefacción, ventilación y aire acondicionado
    Otros
    • Organización sin fines de lucro
    • Agencia para la protección del medio ambiente
    • Alquiler de anuncios publicitarios
    • Fotografía
    • Alquiler de bicicletas
    • Distribuidor de software
    Descubre todas las industrias
  • Odoo Community
    Aprende
    • Tutoriales
    • Documentación
    • Certificaciones
    • Capacitación
    • Blog
    • Podcast
    Fortalece la educación
    • Programa educativo
    • Scale Up! El juego empresarial
    • Visita Odoo
    Obtén el software
    • Descargar
    • Compara ediciones
    • Versiones
    Colabora
    • GitHub
    • Foro
    • Eventos
    • Traducciones
    • Conviértete en partner
    • Servicios para partners
    • Registra tu firma contable
    Obtén servicios
    • Encuentra un partner
    • Encuentra un contador
    • Contacta a un consultor
    • Servicios de implementación
    • Referencias de clientes
    • Soporte
    • Actualizaciones
    GitHub YouTube Twitter LinkedIn Instagram Facebook Spotify
    +1 (650) 691-3277
    Solicita una demostración
  • Precios
  • Ayuda

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

  • CRM
  • e-Commerce
  • Contabilidad
  • Inventario
  • PoS
  • Proyectos
  • MRP
All apps
Debe estar registrado para interactuar con la comunidad.
Todas las publicaciones Personas Insignias
Etiquetas (Ver todo)
odoo accounting v14 pos v15
Acerca de este foro
Debe estar registrado para interactuar con la comunidad.
Todas las publicaciones Personas Insignias
Etiquetas (Ver todo)
odoo accounting v14 pos v15
Acerca de este foro
Ayuda

Sending chatter message

Suscribirse

Reciba una notificación cuando haya actividad en esta publicación

Se marcó esta pregunta
chatterChatterodoo17Odoo17odoo17EEOdoo 17.0+e (Enterprise Edition)
2 Respuestas
932 Vistas
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 Mejor respuesta

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
Mejor respuesta

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
¿Le interesa esta conversación? ¡Participe en ella!

Cree una cuenta para poder utilizar funciones exclusivas e interactuar con la comunidad.

Registrarse
Publicaciones relacionadas Respuestas Vistas Actividad
Send notification to specific users Resuelto
odoo17 Odoo17 odoo17EE
Avatar
Avatar
2
sept 25
1128
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
sept 25
1099
Notification and websocket error
notification odoo17 Odoo17 odoo17CE odoo17EE
Avatar
0
sept 25
1030
Disable edit/delete messages in chatter
chatter Chatter
Avatar
Avatar
1
may 25
2237
Change text of Log Note Button Resuelto
helpdesk chatter Chatter
Avatar
Avatar
1
jul 25
1316
Comunidad
  • Tutoriales
  • Documentación
  • Foro
Código abierto
  • Descargar
  • GitHub
  • Runbot
  • Traducciones
Servicios
  • Alojamiento en Odoo.sh
  • Soporte
  • Actualizaciones del software
  • Desarrollos personalizados
  • Educación
  • Encuentra un contador
  • Encuentra un partner
  • Conviértete en partner
Sobre nosotros
  • Nuestra empresa
  • Activos de marca
  • Contáctanos
  • Empleos
  • Eventos
  • Podcast
  • Blog
  • Clientes
  • Legal • Privacidad
  • Seguridad
الْعَرَبيّة 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 es un conjunto de aplicaciones de código abierto que cubren todas las necesidades de tu empresa: CRM, comercio electrónico, contabilidad, inventario, punto de venta, gestión de proyectos, etc.

La propuesta única de valor de Odoo es ser muy fácil de usar y estar totalmente integrado.

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