Pular para o conteúdo
Odoo Menu
  • Entrar
  • Experimente grátis
  • Aplicativos
    Finanças
    • Financeiro
    • Faturamento
    • Despesas
    • Planilhas (BI)
    • Documentos
    • Assinar Documentos
    Vendas
    • CRM
    • Vendas
    • PDV Loja
    • PDV Restaurantes
    • Assinaturas
    • Locação
    Websites
    • Criador de Sites
    • e-Commerce
    • Blog
    • Fórum
    • Chat ao Vivo
    • e-Learning
    Cadeia de mantimentos
    • Inventário
    • Fabricação
    • PLM - Ciclo de Vida do Produto
    • Compras
    • Manutenção
    • Qualidade
    Recursos Humanos
    • Funcionários
    • Recrutamento
    • Folgas
    • Avaliações
    • Indicações
    • Frota
    Marketing
    • Redes Sociais
    • Marketing por E-mail
    • Marketing por SMS
    • Eventos
    • Automação de Marketing
    • Pesquisas
    Serviços
    • Projeto
    • Planilhas de Horas
    • Serviço de Campo
    • Central de Ajuda
    • Planejamento
    • Compromissos
    Produtividade
    • Mensagens
    • Aprovações
    • Internet das Coisas
    • VoIP
    • Conhecimento
    • WhatsApp
    Aplicativos de terceiros Odoo Studio Plataforma Odoo Cloud
  • Setores
    Varejo
    • Loja de livros
    • Loja de roupas
    • Loja de móveis
    • Mercearia
    • Loja de ferramentas
    • Loja de brinquedos
    Comida e hospitalidade
    • Bar e Pub
    • Restaurante
    • Fast Food
    • Hospedagem
    • Distribuidor de bebidas
    • Hotel
    Imóveis
    • Imobiliária
    • Escritório de arquitetura
    • Construção
    • Administração de propriedades
    • Jardinagem
    • Associação de proprietários de imóveis
    Consultoria
    • Escritório de Contabilidade
    • Parceiro Odoo
    • Agência de marketing
    • Escritório de advocacia
    • Aquisição de talentos
    • Auditoria e Certificação
    Fabricação
    • Têxtil
    • Metal
    • Móveis
    • Alimentação
    • Cervejaria
    • Presentes corporativos
    Saúde e Boa forma
    • Clube esportivo
    • Loja de óculos
    • Academia
    • Profissionais de bem-estar
    • Farmácia
    • Salão de cabeleireiro
    Comércio
    • Handyman
    • Hardware e Suporte de TI
    • Sistemas de energia solar
    • Sapataria
    • Serviços de limpeza
    • Serviços de climatização
    Outros
    • Organização sem fins lucrativos
    • Agência Ambiental
    • Aluguel de outdoors
    • Fotografia
    • Aluguel de bicicletas
    • Revendedor de software
    Navegar por todos os setores
  • Comunidade
    Aprenda
    • Tutoriais
    • Documentação
    • Certificações
    • Treinamento
    • Blog
    • Podcast
    Empodere a Educação
    • Programa de educação
    • Scale Up! Jogo de Negócios
    • Visite a Odoo
    Obtenha o Software
    • Baixar
    • Comparar edições
    • Releases
    Colaborar
    • Github
    • Fórum
    • Eventos
    • Traduções
    • Torne-se um parceiro
    • Serviços para parceiros
    • Cadastre seu escritório contábil
    Obtenha os serviços
    • Encontre um parceiro
    • Encontre um Contador
    • Conheça um consultor
    • Serviços de Implementação
    • Referências de Clientes
    • Suporte
    • Upgrades
    Github YouTube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Faça uma demonstração
  • Preços
  • Ajuda

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

  • CRM
  • e-Commerce
  • Financeiro
  • Inventário
  • PoS
  • Projeto
  • MRP
All apps
É necessário estar registrado para interagir com a comunidade.
Todas as publicações Pessoas Emblemas
Marcadores (Ver tudo)
odoo accounting v14 pos v15
Sobre este fórum
É necessário estar registrado para interagir com a comunidade.
Todas as publicações Pessoas Emblemas
Marcadores (Ver tudo)
odoo accounting v14 pos v15
Sobre este fórum
Ajuda

Sending chatter message

Inscrever

Seja notificado quando houver atividade nesta publicação

Esta pergunta foi sinalizada
chatterChatterodoo17Odoo17odoo17EEOdoo 17.0+e (Enterprise Edition)
2 Respostas
871 Visualizações
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
Cancelar
Avatar
OdooIntern
Autor Melhor resposta

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
Cancelar
Avatar
Cybrosys Techno Solutions Pvt.Ltd
Melhor resposta

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
Cancelar
Está gostando da discussão? Não fique apenas lendo, participe!

Crie uma conta hoje mesmo para aproveitar os recursos exclusivos e interagir com nossa incrível comunidade!

Inscreva-se
Publicações relacionadas Respostas Visualizações Atividade
Send notification to specific users Resolvido
odoo17 Odoo17 odoo17EE
Avatar
Avatar
2
set. 25
1047
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
set. 25
1091
Notification and websocket error
notification odoo17 Odoo17 odoo17CE odoo17EE
Avatar
0
set. 25
966
Disable edit/delete messages in chatter
chatter Chatter
Avatar
Avatar
1
mai. 25
2166
Change text of Log Note Button Resolvido
helpdesk chatter Chatter
Avatar
Avatar
1
jul. 25
1265
Comunidade
  • Tutoriais
  • Documentação
  • Fórum
Open Source
  • Baixar
  • Github
  • Runbot
  • Traduções
Serviços
  • Odoo.sh Hosting
  • Suporte
  • Upgrade
  • Desenvolvimentos personalizados
  • Educação
  • Encontre um Contador
  • Encontre um parceiro
  • Torne-se um parceiro
Sobre nós
  • Nossa empresa
  • Ativos da marca
  • Contato
  • Empregos
  • Eventos
  • Podcast
  • Blog
  • Clientes
  • Legal • Privacidade
  • Segurança
الْعَرَبيّة 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 é um conjunto de aplicativos de negócios em código aberto que cobre todas as necessidades de sua empresa: CRM, comércio eletrônico, contabilidade, estoque, ponto de venda, gerenciamento de projetos, etc.

A proposta de valor exclusiva Odoo é ser, ao mesmo tempo, muito fácil de usar e totalmente integrado.

Site feito com

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