Browse Source

Jun 13: [UPDT] Updated 'odoo_slack_connector'

pull/257/head
AjmalCybro 2 years ago
parent
commit
b6162a43ba
  1. 44
      odoo_slack_connector/README.rst
  2. 1
      odoo_slack_connector/__manifest__.py
  3. 23
      odoo_slack_connector/data/scheduled_action.xml
  4. 7
      odoo_slack_connector/doc/RELEASE_NOTES.md
  5. 2
      odoo_slack_connector/models/__init__.py
  6. 67
      odoo_slack_connector/models/mail_channel.py
  7. 4
      odoo_slack_connector/models/mail_message.py
  8. 65
      odoo_slack_connector/models/res_company.py
  9. 59
      odoo_slack_connector/models/res_users.py

44
odoo_slack_connector/README.rst

@ -1,17 +1,47 @@
.. image:: https://img.shields.io/badge/licence-LGPL--3-blue.svg
:target: http://www.gnu.org/licenses/lgpl-3.0-standalone.html
:alt: License: LGPL-3
Slack Odoo Connector Slack Odoo Connector
==================== =========================
Allows to integrate with slack. Allows to integrate with slack.
Installation
============
- www.odoo.com/documentation/16.0/setup/install.html
- Install our custom addon
Configuration Configuration
============= =============
Need to generate slack API token Need to generate slack API token
Company
-------
* `Cybrosys Techno Solutions <https://cybrosys.com/>`__
License
-------
General Public License, Version 3 (LGPL v3).
(https://www.odoo.com/documentation/user/16.0/legal/licenses/licenses.html)
Credits Credits
======= -------
Developer: Viswanth K v15 @ cybrosys, odoo@cybrosys.com Developer: Viswanth K v15 @ cybrosys, odoo@cybrosys.com
Viswanth K v16 @ cybrosys, odoo@cybrosys.com Viswanth K v16 @ cybrosys, odoo@cybrosys.com
Contacts
-------
* Mail Contact : odoo@cybrosys.com
* Website : https://cybrosys.com
Bug Tracker
-------
Bugs are tracked on GitHub Issues. In case of trouble, please check there if your issue has already been reported.
Maintainer
==========
.. image:: https://cybrosys.com/images/logo.png
:target: https://cybrosys.com
This module is maintained by Cybrosys Technologies.
For support and more information, please visit `Our Website <https://cybrosys.com/>`__
Further information
===================
HTML Description: `<static/description/index.html>`__

1
odoo_slack_connector/__manifest__.py

@ -45,5 +45,4 @@
'installable': True, 'installable': True,
'auto_install': False, 'auto_install': False,
'uninstall_hook': 'slack_uninstall_hook' 'uninstall_hook': 'slack_uninstall_hook'
} }

23
odoo_slack_connector/data/scheduled_action.xml

@ -1,15 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<odoo> <odoo>
<data noupdate="1"> <data noupdate="1">
<record id="ir_cron_scheduler_synchronization_slack_odoo" model="ir.cron"> <!-- scheduled action to fetch the meassages from slack-->
<field name="name">Auto Synchronization of slack and odoo</field> <record id="ir_cron_scheduler_synchronization_slack_odoo" model="ir.cron">
<field name="model_id" ref="model_mail_message"/> <field name="name">Auto Synchronization of slack and odoo</field>
<field name="state">code</field> <field name="model_id" ref="model_mail_message"/>
<field name="code">model.synchronization_slack()</field> <field name="state">code</field>
<field name="user_id" ref="base.user_root"/> <field name="code">model.synchronization_slack()</field>
<field name="interval_number">1</field> <field name="user_id" ref="base.user_root"/>
<field name="interval_type">minutes</field> <field name="interval_number">1</field>
<field name="numbercall">-1</field> <field name="interval_type">minutes</field>
</record> <field name="numbercall">-1</field>
</data> </record>
</data>
</odoo> </odoo>

7
odoo_slack_connector/doc/RELEASE_NOTES.md

@ -3,4 +3,9 @@
#### 27.10.2022 #### 27.10.2022
#### Version 16.0.1.0.0 #### Version 16.0.1.0.0
##### ADD ##### ADD
- Initial commit for Slack - Initial commit for Slack
#### 11.06.2023
#### Version 16.0.1.0.1
##### FIX
- Bug Fix: Fixed the issue where slack members are not loading to odoo

2
odoo_slack_connector/models/__init__.py

@ -24,5 +24,3 @@ from . import mail_message
from . import mail_channel from . import mail_channel
from . import res_partner from . import res_partner
from . import res_users from . import res_users

67
odoo_slack_connector/models/mail_channel.py

@ -19,8 +19,12 @@
# If not, see <http://www.gnu.org/licenses/>. # If not, see <http://www.gnu.org/licenses/>.
# #
############################################################################# #############################################################################
import requests, json import logging
from odoo import models, fields
import requests
from requests import RequestException
from odoo import fields, models
class MailChannel(models.Model): class MailChannel(models.Model):
@ -38,29 +42,38 @@ class MailChannel(models.Model):
headers = { headers = {
'Authorization': 'Bearer ' + company_record.token 'Authorization': 'Bearer ' + company_record.token
} }
for channels in self: logger = logging.getLogger(__name__)
slack_user_list = [] for channel in self:
sample_list = [] if not channel.is_slack:
slack_user_list.clear() continue
current_channel_user_list = [] try:
current_channel_user_list.clear() url = "https://slack.com/api/conversations.members?channel=" + channel.channel
with requests.Session() as session:
response = session.get(url, headers=headers, data=payload)
channel_members = response.json()
slack_user_list = []
for slack_user_id in channel_members['members']:
contact = self.env['res.partner'].search([('slack_user_id', '=', slack_user_id)])
slack_user_list.append(contact.id)
current_channel_user_list = channel.channel_member_ids.mapped('partner_id.id')
sample_list = [
(0, 0, {'partner_id': contact_id})
for contact_id in slack_user_list
if contact_id not in current_channel_user_list
]
channel.channel_member_ids = sample_list
except RequestException as e:
# Handle request exception
logger.error(f"Error occurred during API request: {str(e)}")
except (KeyError, ValueError) as e:
# Handle JSON parsing or key error
logger.error(f"Error occurred while parsing API response: {str(e)}")
if channels.is_slack: except Exception as e:
url = "https://slack.com/api/conversations.members?channel=" + channels.channel # Handle any other exceptions
channel_member_resonse = requests.request("GET", url, logger.error(f"An error occurred: {str(e)}")
headers=headers,
data=payload)
channel_members = channel_member_resonse.__dict__['_content']
dict_channel_members = channel_members.decode("UTF-8")
channel_member = json.loads(dict_channel_members)
for slack_user_id in channel_member['members']:
contact = self.env['res.partner'].search(
[('slack_user_id', '=', slack_user_id)])
slack_user_list.append(contact.id)
for last_seen_partner_ids in channels.channel_member_ids:
current_channel_user_list.append(
last_seen_partner_ids.partner_id.id)
for contact_id in slack_user_list:
if contact_id not in current_channel_user_list:
sample_list.append((0, 0, {'partner_id': contact_id}))
channels.channel_member_ids = sample_list

4
odoo_slack_connector/models/mail_message.py

@ -19,10 +19,8 @@
# If not, see <http://www.gnu.org/licenses/>. # If not, see <http://www.gnu.org/licenses/>.
# #
############################################################################# #############################################################################
from datetime import date, time
from odoo import fields, models, api from odoo import fields, models, api
import requests, re, json import requests, re, json
from odoo.http import request
from datetime import datetime from datetime import datetime
from dateutil import tz from dateutil import tz
@ -41,7 +39,7 @@ class MailMessage(models.Model):
@api.model @api.model
def create(self, vals): def create(self, vals):
"""Over riding the create method to sent message to slack""" """Over-riding the create method to sent message to slack"""
res = super().create(vals) res = super().create(vals)
to_zone = tz.gettz('Asia/Kolkata') to_zone = tz.gettz('Asia/Kolkata')
channel_date = datetime.today().strftime('%Y-%m-%d %H:%M:%S') channel_date = datetime.today().strftime('%Y-%m-%d %H:%M:%S')

65
odoo_slack_connector/models/res_company.py

@ -19,11 +19,12 @@
# If not, see <http://www.gnu.org/licenses/>. # If not, see <http://www.gnu.org/licenses/>.
# #
############################################################################# #############################################################################
import json
import requests
from odoo import fields, models from odoo import fields, models
import requests, json
class ResCompanyInherited(models.Model): class ResCompany(models.Model):
_inherit = 'res.company' _inherit = 'res.company'
_description = 'Slack Api' _description = 'Slack Api'
@ -53,7 +54,7 @@ class ResCompanyInherited(models.Model):
users_response = users_response.__dict__['_content'] users_response = users_response.__dict__['_content']
dict_users = users_response.decode("UTF-8") dict_users = users_response.decode("UTF-8")
users = json.loads(dict_users) users = json.loads(dict_users)
members = users.get('members', False)
channel_list = [] channel_list = []
channel_response = requests.request("GET", url2, headers=headers, channel_response = requests.request("GET", url2, headers=headers,
data=payload) data=payload)
@ -62,8 +63,6 @@ class ResCompanyInherited(models.Model):
channels = json.loads(dict_channels) channels = json.loads(dict_channels)
search_channel = self.env['mail.channel'].search([]) search_channel = self.env['mail.channel'].search([])
search_channel.sync_members()
self.env['res.users'].search([]).sync_users()
for i in search_channel: for i in search_channel:
channel_list.append(i.channel) channel_list.append(i.channel)
for channel in channels['channels']: for channel in channels['channels']:
@ -74,11 +73,10 @@ class ResCompanyInherited(models.Model):
'channel': channel['id'], 'channel': channel['id'],
'is_slack': True, 'is_slack': True,
}, ]) }, ])
search_channel.sync_members()
self.env['res.users'].search([]).sync_users()
users_list = [] users_list = []
slack_id_list = [] slack_id_list = []
slack_internal_user_list = []
members_list = []
channels_list = [] channels_list = []
record_channel_list = [] record_channel_list = []
record = self.env.user.company_id record = self.env.user.company_id
@ -94,35 +92,36 @@ class ResCompanyInherited(models.Model):
record_user_list = [] record_user_list = []
for rec in record.slack_users_ids: for rec in record.slack_users_ids:
record_user_list.append(rec.user) record_user_list.append(rec.user)
for rec in users['members']: if members is not False:
if 'email' in rec['profile']: for rec in members:
email = rec['profile']['email'] if 'email' in rec['profile']:
else: email = rec['profile']['email']
email = '' else:
if rec['id'] not in record_user_list: email = ''
users_list.append((0, 0, if rec['id'] not in record_user_list:
{'name': rec['real_name'], users_list.append((0, 0,
'user': rec['id'], {'name': rec['real_name'],
'email': email}, 'user': rec['id'],
)) 'email': email},
))
self.slack_users_ids = users_list self.slack_users_ids = users_list
for partner_id in self.env['res.partner'].search([]): for partner_id in self.env['res.partner'].search([]):
slack_id_list.append(partner_id.slack_user_id) slack_id_list.append(partner_id.slack_user_id)
for rec in users['members']: if members is not False:
# if rec['is_email_confirmed'] is True: for rec in members:
if 'email' in rec['profile']: if 'email' in rec['profile']:
email = rec['profile']['email'] email = rec['profile']['email']
else: else:
email = '' email = ''
if rec['id'] not in slack_id_list: if rec['id'] not in slack_id_list:
vals = { vals = {
'name': rec['real_name'], 'name': rec['real_name'],
'slack_user_id': rec['id'], 'slack_user_id': rec['id'],
'is_slack_user': True, 'is_slack_user': True,
'email': email 'email': email
} }
self.env['res.partner'].create(vals) self.env['res.partner'].create(vals)
class SlackUsersLines(models.Model): class SlackUsersLines(models.Model):

59
odoo_slack_connector/models/res_users.py

@ -19,47 +19,58 @@
# If not, see <http://www.gnu.org/licenses/>. # If not, see <http://www.gnu.org/licenses/>.
# #
############################################################################# #############################################################################
import requests
import logging
from odoo import fields, models from odoo import fields, models
import requests, json
class ResPartner(models.Model): class ResPartner(models.Model):
_inherit = 'res.users' _inherit = 'res.users'
_description = 'Slack users' _description = 'Slack users'
slack_user_id = fields.Char(string="Slack User ID") slack_user_id = fields.Char(string="Slack User ID", readonly=True)
is_slack_internal_users = fields.Boolean("Slack User", default=False) is_slack_internal_users = fields.Boolean("Slack User", default=False)
def sync_users(self): def sync_users(self):
"""To load slack users""" """To load slack users"""
slack_internal_user_list = [] slack_internal_user_list = [user_id.slack_user_id for user_id in self]
url1 = "https://slack.com/api/users.list" url = "https://slack.com/api/users.list"
company_record = self.env.user.company_id company_record = self.env.user.company_id
payload = {} payload = {}
headers = { headers = {
'Authorization': 'Bearer ' + company_record.token 'Authorization': 'Bearer ' + company_record.token
} }
users_response = requests.request("GET", url1, headers=headers, logger = logging.getLogger(__name__)
data=payload)
users_response = users_response.__dict__['_content']
dict_users = users_response.decode("UTF-8")
users = json.loads(dict_users)
for user_id in self:
slack_internal_user_list.append(user_id.slack_user_id)
for rec in users['members']: try:
if rec['is_email_confirmed'] is True: response = requests.get(url, headers=headers, data=payload)
if 'email' in rec['profile']: response.raise_for_status()
users = response.json()
except requests.exceptions.RequestException as err:
# Handle request exceptions
logger.error(f"Error during Slack API request: {err}")
return
members = users.get('members', False)
if members is not False:
vals_list = []
for rec in members:
if 'is_email_confirmed' in rec and rec['is_email_confirmed'] is True and 'email' in rec['profile']:
email = rec['profile']['email'] email = rec['profile']['email']
else: if rec['id'] not in slack_internal_user_list:
email = '' vals = {
if rec['id'] not in slack_internal_user_list: 'name': rec['real_name'],
vals = { 'slack_user_id': rec['id'],
'name': rec['real_name'], 'is_slack_internal_users': True,
'slack_user_id': rec['id'], 'login': email,
'is_slack_internal_users': True, }
'login': email, vals_list.append(vals)
} try:
self.create(vals) if vals_list:
self.create(vals_list)
except Exception as e:
# Handle creation exception
logger.error(f"Error creating Slack users: {e}")
return

Loading…
Cancel
Save