from odoo import api, models, exceptions, fields import logging _logger = logging.getLogger(__name__) class WechatEnterpriseSendMessage(models.Model): _name = 'we.send.message' _description = 'Wechat Enterprise Send Message Manage' touser = fields.Many2many('res.users', 'send_message_to_users_ref', 'wechat_contacts_id', 'touser', u'成员列表') msgtype = fields.Selection([('text', u'文字消息'), ('image', u'图片消息'), ('voice', u'语音消息'), ('video', u'视频消息'), ('file', u'文件消息'), ('news', u'图文消息'), ('mpnews', u'微信后台图文消息')], u'消息类型', required=True, default='text') agentid = fields.Many2one('we.app', u'发送消息的企业应用', required=True) content = fields.Char(u'消息内容') media_id = fields.Char(u'媒体文件') title = fields.Char(u'标题') description = fields.Text(u'描述') articles = fields.Char(u'图文消息') url = fields.Char(u'点击后跳转的链接') picurl = fields.Char(u'图文消息的图片链接') thumb_media_id = fields.Char(u'图文消息缩略图') author = fields.Char(u'图文消息的作者') content_source_url = fields.Char(u'图文消息点击“阅读原文”之后的页面链接') news_content = fields.Char(u'图文消息的内容,支持html标签') digest = fields.Char(u'图文消息的描述') show_cover_pic = fields.Selection([('0', u'否'), ('1', u'是')], u'是否显示封面', default='0') safe = fields.Selection([('0', u'否'), ('1', u'是')], u'是否是保密消息', required=True, default='0') def send_message(self): """ 发送消息给关注企业号的用户 :return: """ users = "" i = 0 if self.touser and len(self.touser) > 0: for data in self.touser: i = i + 1 if i == len(self.touser): if data['we_employee_id']: users = users + data['we_employee_id'] else: if data['we_employee_id']: users = users + data['we_employee_id'] + "|" if users == "": users = '@all' partys = "" if self.msgtype == "news": self.send_news_message(users, self.agentid['agentid'], self.title, self.description, self.url, self.picurl) elif self.msgtype == "text": self.send_text_message(users, self.agentid['agentid'], self.content, partys) def send_text_message(self, userid, agentid, content, partyid=None): """ 发送文本消息给关注企业号的用户 :param userid: :param agentid: :param content: :param partyid: :return: """ try: wechat = self.env['we.config'].sudo().get_wechat(agent_id=agentid) if wechat: data = { 'safe': "0", 'msgtype': 'text', 'agentid': agentid, 'touser': userid, 'toparty': partyid, 'content': content } wechat.message.send_text(agent_id=data['agentid'], user_ids=data['touser'], content=data['content'], party_ids=data['toparty'], safe=data['safe']) else: raise exceptions.Warning(u"初始化企业号失败") except Exception as e: logging.error('send_text_message:%s' % e) # 发送图文消息给关注企业号的用户 def send_news_message(self, userid, agentid, title=None, description=None, url=None, picurl=None): """ 发送图文消息给关注企业号的用户 :param userid: :param agentid: :param title: :param description: :param url: :param picurl: :return: """ wechat = self.env['we.config'].sudo().get_wechat(agent_id=agentid) if wechat: articles = [ { 'url': url, 'image': picurl, 'description': description, 'title': title } ] wechat.message.send_articles(agent_id=agentid, user_ids=userid, articles=articles) else: raise exceptions.Warning(u"初始化企业号失败")