Skip to Content
Odoo Menu
  • Zaloguj się
  • Wypróbuj za darmo
  • Aplikacje
    Finanse
    • Księgowość
    • Fakturowanie
    • Wydatki
    • Arkusz kalkulacyjny (BI)
    • Dokumenty
    • Podpisy
    Sprzedaż
    • CRM
    • Sprzedaż
    • PoS Sklep
    • PoS Restauracja
    • Subskrypcje
    • Wypożyczalnia
    Strony Internetowe
    • Kreator Stron Internetowych
    • eCommerce
    • Blog
    • Forum
    • Czat na Żywo
    • eLearning
    Łańcuch dostaw
    • Magazyn
    • Produkcja
    • PLM
    • Zakupy
    • Konserwacja
    • Jakość
    Zasoby Ludzkie
    • Pracownicy
    • Rekrutacja
    • Urlopy
    • Ocena pracy
    • Polecenia Pracownicze
    • Flota
    Marketing
    • Marketing Społecznościowy
    • E-mail Marketing
    • SMS Marketing
    • Wydarzenia
    • Automatyzacja Marketingu
    • Ankiety
    Usługi
    • Projekt
    • Ewidencja czasu pracy
    • Usługi Terenowe
    • Helpdesk
    • Planowanie
    • Spotkania
    Produktywność
    • Dyskusje
    • Zatwierdzenia
    • IoT
    • VoIP
    • Baza wiedzy
    • WhatsApp
    Aplikacje trzecich stron Studio Odoo Odoo Cloud Platform
  • Branże
    Sprzedaż detaliczna
    • Księgarnia
    • Sklep odzieżowy
    • Sklep meblowy
    • Sklep spożywczy
    • Sklep z narzędziami
    • Sklep z zabawkami
    Żywienie i hotelarstwo
    • Bar i Pub
    • Restauracja
    • Fast Food
    • Pensjonat
    • Dystrybutor napojów
    • Hotel
    Agencja nieruchomości
    • Agencja nieruchomości
    • Biuro architektoniczne
    • Budowa
    • Zarządzanie nieruchomościami
    • Ogrodnictwo
    • Stowarzyszenie właścicieli nieruchomości
    Doradztwo
    • Biuro księgowe
    • Partner Odoo
    • Agencja marketingowa
    • Kancelaria prawna
    • Agencja rekrutacyjna
    • Audyt i certyfikacja
    Produkcja
    • Tekstylia
    • Metal
    • Meble
    • Jedzenie
    • Browar
    • Prezenty firmowe
    Zdrowie & Fitness
    • Klub sportowy
    • Salon optyczny
    • Centrum fitness
    • Praktycy Wellness
    • Apteka
    • Salon fryzjerski
    Transakcje
    • Złota rączka
    • Wsparcie Sprzętu IT
    • Systemy energii słonecznej
    • Szewc
    • Firma sprzątająca
    • Usługi HVAC
    Inne
    • Organizacja non-profit
    • Agencja Środowiskowa
    • Wynajem billboardów
    • Fotografia
    • Leasing rowerów
    • Sprzedawca oprogramowania
    Przeglądaj wszystkie branże
  • Community
    Ucz się
    • Samouczki
    • Dokumentacja
    • Certyfikacje
    • Szkolenie
    • Blog
    • Podcast
    Pomóż w nauce innym
    • Program Edukacyjny
    • Scale Up! Gra biznesowa
    • Odwiedź Odoo
    Skorzystaj z oprogramowania
    • Pobierz
    • Porównaj edycje
    • Wydania
    Współpracuj
    • Github
    • Forum
    • Wydarzenia
    • Tłumaczenia
    • Zostań partnerem
    • Usługi dla partnerów
    • Zarejestruj swoją firmę rachunkową
    Skorzystaj z usług
    • Znajdź partnera
    • Znajdź księgowego
    • Spotkaj się z doradcą
    • Usługi wdrożenia
    • Opinie klientów
    • Wsparcie
    • Aktualizacje
    Github Youtube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Zaplanuj demo
  • Cennik
  • Pomoc

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

  • CRM
  • e-Commerce
  • Księgowość
  • Zapasy
  • PoS
  • Projekt
  • MRP
All apps
Musisz się zarejestrować, aby móc wchodzić w interakcje z tą społecznością.
Wszystkie posty Osoby Odznaki
Tagi (Zobacz wszystko)
odoo accounting v14 pos v15
O tym forum
Musisz się zarejestrować, aby móc wchodzić w interakcje z tą społecznością.
Wszystkie posty Osoby Odznaki
Tagi (Zobacz wszystko)
odoo accounting v14 pos v15
O tym forum
Pomoc

Sending chatter message

Zaprenumeruj

Otrzymaj powiadomienie o aktywności w tym poście

To pytanie dostało ostrzeżenie
chatterChatterodoo17Odoo17odoo17EEOdoo 17.0+e (Enterprise Edition)
2 Odpowiedzi
996 Widoki
Awatar
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
Awatar
Odrzuć
Awatar
OdooIntern
Autor Najlepsza odpowiedź

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
Awatar
Odrzuć
Awatar
Cybrosys Techno Solutions Pvt.Ltd
Najlepsza odpowiedź

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
Awatar
Odrzuć
Podoba Ci się ta dyskusja? Dołącz do niej!

Stwórz konto dzisiaj, aby cieszyć się ekskluzywnymi funkcjami i wchodzić w interakcje z naszą wspaniałą społecznością!

Zarejestruj się
Powiązane posty Odpowiedzi Widoki Czynność
Send notification to specific users Rozwiązane
odoo17 Odoo17 odoo17EE
Awatar
Awatar
2
wrz 25
1206
How to Find Who Created a "To Do" in Chatter of Products in Sales Module?
sales chatter Chatter Odoo17 To-Do Activities
Awatar
Awatar
1
wrz 25
1113
Notification and websocket error
notification odoo17 Odoo17 odoo17CE odoo17EE
Awatar
0
wrz 25
1091
Disable edit/delete messages in chatter
chatter Chatter
Awatar
Awatar
1
maj 25
2298
Change text of Log Note Button Rozwiązane
helpdesk chatter Chatter
Awatar
Awatar
1
lip 25
1387
Społeczność
  • Samouczki
  • Dokumentacja
  • Forum
Open Source
  • Pobierz
  • Github
  • Runbot
  • Tłumaczenia
Usługi
  • Hosting Odoo.sh
  • Wsparcie
  • Aktualizacja
  • Indywidualne rozwiązania
  • Edukacja
  • Znajdź księgowego
  • Znajdź partnera
  • Zostań partnerem
O nas
  • Nasza firma
  • Zasoby marki
  • Skontaktuj się z nami
  • Oferty pracy
  • Wydarzenia
  • Podcast
  • Blog
  • Klienci
  • Informacje prawne • Prywatność
  • Bezpieczeństwo Odoo
الْعَرَبيّة 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 to pakiet aplikacji biznesowych typu open source, które zaspokoją wszystkie potrzeby Twojej firmy: CRM, eCommerce, księgowość, inwentaryzacja, punkt sprzedaży, zarządzanie projektami itp.

Unikalną wartością Odoo jest to, że jest jednocześnie bardzo łatwe w użyciu i w pełni zintegrowane.

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