odoo14用odoobot给指定用户发消息
1.发送私聊消息最佳写法
def _send_sys_message(self, user, message): """通过OdooBot给指定用户发送消息 :param user: 'res.users' 对象 :param message: str, 消息内容 """ # 获取OdooBot的partner_id odoobot_id = self.env['ir.model.data'].xmlid_to_res_id("base.partner_root") # 获取OdooBot和用户的聊天频道 channel_partners = user.mapped('partner_id').ids channel = self.env['mail.channel'].sudo().search( [('channel_type', '=', 'chat'), ('channel_partner_ids', 'in', channel_partners),('channel_partner_ids', 'in', [odoobot_id])], limit=1) # 不存在则初始化聊天频道 if not channel: user.odoobot_state = 'not_initialized' channel = self.env['mail.channel'].with_user(user).init_odoobot() # 发送消息 channel.sudo().message_post( body=message, author_id=odoobot_id, message_type="comment", subtype_xmlid="mail.mt_comment", )
2.发送群聊消息
@ormcache('odoobot_id') def _get_channel(self,odoobot_id): # find if a channel was opened for this user before channel = self.env['mail.channel'].sudo().search([ ('name', '=', '接口推送'), ('channel_partner_ids', 'in', [self.env.user.partner_id.id]) ], limit=1, ) _logger.info(f'find exist channer:{channel}') if not channel: # create a new channel channel = self.env['mail.channel'].with_context(mail_create_nosubscribe=True).sudo().create({ 'channel_partner_ids': [(4, self.env.user.partner_id.id), (4, odoobot_id)], 'public': 'groups', # 谁能关注组的活动 'channel_type': 'channel', # 渠道,群聊 'group_public_id': self.env.ref('base.group_user').id, # 经授权的群组 'group_ids': [(6, 0, [self.env.ref('api_log.api_log_user_group').id])], # 自动订阅组 'email_send': False, 'name': f'接口推送', 'description': '用于群发接口调用相关的消息,调用日志写入接口日志表时会自动发消息通知群里', 'display_name': f'接口推送', }) _logger.info(f'create an api channel id: {channel}') return channel.id def _send_group_message(self, message): """ 发送群聊渠道消息 """ # 获取OdooBot的partner_id odoobot_id = self.env['ir.model.data'].sudo().xmlid_to_res_id("base.partner_root") # find if a channel was opened for this user before channel_id = self._get_channel(odoobot_id) channel = self.env['mail.channel'].browse(channel_id) # 给群组发消息 channel.sudo().message_post( body=message, author_id=odoobot_id, message_type="comment", subtype="mail.mt_comment", )
发送群聊消息适合在系统中提前配置好群聊和群组成员,比如系统维护之类的消息推送给开发 人员,把所有开发人员拉个群,大家谁看到谁就处理了