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. 1
      odoo_slack_connector/data/scheduled_action.xml
  4. 5
      odoo_slack_connector/doc/RELEASE_NOTES.md
  5. 2
      odoo_slack_connector/models/__init__.py
  6. 63
      odoo_slack_connector/models/mail_channel.py
  7. 4
      odoo_slack_connector/models/mail_message.py
  8. 21
      odoo_slack_connector/models/res_company.py
  9. 45
      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
====================
=========================
Allows to integrate with slack.
Installation
============
- www.odoo.com/documentation/16.0/setup/install.html
- Install our custom addon
Configuration
=============
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
=======
-------
Developer: Viswanth K v15 @ 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,
'auto_install': False,
'uninstall_hook': 'slack_uninstall_hook'
}

1
odoo_slack_connector/data/scheduled_action.xml

@ -1,6 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<odoo>
<data noupdate="1">
<!-- scheduled action to fetch the meassages from slack-->
<record id="ir_cron_scheduler_synchronization_slack_odoo" model="ir.cron">
<field name="name">Auto Synchronization of slack and odoo</field>
<field name="model_id" ref="model_mail_message"/>

5
odoo_slack_connector/doc/RELEASE_NOTES.md

@ -4,3 +4,8 @@
#### Version 16.0.1.0.0
##### ADD
- 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 res_partner
from . import res_users

63
odoo_slack_connector/models/mail_channel.py

@ -19,8 +19,12 @@
# If not, see <http://www.gnu.org/licenses/>.
#
#############################################################################
import requests, json
from odoo import models, fields
import logging
import requests
from requests import RequestException
from odoo import fields, models
class MailChannel(models.Model):
@ -38,29 +42,38 @@ class MailChannel(models.Model):
headers = {
'Authorization': 'Bearer ' + company_record.token
}
for channels in self:
logger = logging.getLogger(__name__)
for channel in self:
if not channel.is_slack:
continue
try:
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 = []
sample_list = []
slack_user_list.clear()
current_channel_user_list = []
current_channel_user_list.clear()
if channels.is_slack:
url = "https://slack.com/api/conversations.members?channel=" + channels.channel
channel_member_resonse = requests.request("GET", url,
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)])
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)
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
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)}")
except Exception as e:
# Handle any other exceptions
logger.error(f"An error occurred: {str(e)}")

4
odoo_slack_connector/models/mail_message.py

@ -19,10 +19,8 @@
# If not, see <http://www.gnu.org/licenses/>.
#
#############################################################################
from datetime import date, time
from odoo import fields, models, api
import requests, re, json
from odoo.http import request
from datetime import datetime
from dateutil import tz
@ -41,7 +39,7 @@ class MailMessage(models.Model):
@api.model
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)
to_zone = tz.gettz('Asia/Kolkata')
channel_date = datetime.today().strftime('%Y-%m-%d %H:%M:%S')

21
odoo_slack_connector/models/res_company.py

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

45
odoo_slack_connector/models/res_users.py

@ -19,42 +19,46 @@
# If not, see <http://www.gnu.org/licenses/>.
#
#############################################################################
import requests
import logging
from odoo import fields, models
import requests, json
class ResPartner(models.Model):
_inherit = 'res.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)
def sync_users(self):
"""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
payload = {}
headers = {
'Authorization': 'Bearer ' + company_record.token
}
users_response = requests.request("GET", url1, headers=headers,
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)
logger = logging.getLogger(__name__)
for rec in users['members']:
if rec['is_email_confirmed'] is True:
if 'email' in rec['profile']:
try:
response = requests.get(url, headers=headers, data=payload)
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']
else:
email = ''
if rec['id'] not in slack_internal_user_list:
vals = {
'name': rec['real_name'],
@ -62,4 +66,11 @@ class ResPartner(models.Model):
'is_slack_internal_users': True,
'login': email,
}
self.create(vals)
vals_list.append(vals)
try:
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