Initial commit

This commit is contained in:
mvivlad 2025-02-19 16:15:22 +03:00
commit ffcf283b6f
18 changed files with 1216 additions and 0 deletions

1
.gitignore vendored Normal file
View File

@ -0,0 +1 @@
__pycache__/

25
README.md Normal file
View File

@ -0,0 +1,25 @@
# Odoo base_telegram
Odoo Telegram API
Menu: Settings / Technical / Parameters / Telegram API Connections
## Add new connection
- Open the chat with [@BotFather](https://t.me/BotFather)
- Enter the command **/newbot** to create a bot
- Save received **token** (like: 1234567890:ABcdeFghKLMNopqrs_TUvWxyz)
- Create a group where the created bot should post messages
- Add the bot to the group
- Grant the bot admin access in the group
- Send a test message in the group, ensure that the bot can read it
- Save **Chat ID** from test message
![Telegram API new connection form](chat_bot_config_form.png "Telegram API new connection form")
## Send message to Telegram
``env["base.telegram"].browse(1).send_message('Test')``
## Send message from project.task by template
``
self = env["base.telegram"].browse(1)
obj = env['project.task'].browse(4)
self.with_context(lang=env.user.lang if env.user.lang else 'ru_RU', tz=env.user.tz if env.user.tz else 'Europe/Moscow').send_template('base_telegram.message_new_task', obj)
``

2
__init__.py Normal file
View File

@ -0,0 +1,2 @@
from . import models
from . import wizard

28
__manifest__.py Normal file
View File

@ -0,0 +1,28 @@
# Copyright 2025 Boant <https://boant.ru>
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl).
{
'name': 'Telegram API',
"version": "17.0.0.0.0",
'category': 'Technical',
"author": "Boant",
"license": "LGPL-3",
"development_status": "Production/Stable",
"maintainers": ["mvivlad"],
"website": "https://boant.ru",
'depends': [
'base',
'mail',
'base_automation',
],
'data': [
'security/ir.model.access.csv',
'data/ir_ui_view_templates.xml',
'wizard/create_notify_new_object.xml',
'views/base_telegram_view.xml',
'views/base_telegram_templates.xml',
'views/base_telegram_menu_views.xml',
],
'installable': True,
'application': False,
}

View File

@ -0,0 +1,16 @@
<?xml version="1.0" encoding="utf-8" ?>
<odoo noupdate="1">
<record model="ir.ui.view" id="message_new_task">
<field name='name'>Message template for New Project Task</field>
<field name='type'>qweb</field>
<field name="model_id" ref="project.model_project_task" />
<field name="key">base_telegram.message_new_task</field>
<field name="arch" type="xml"><t t-if="object"><t>Subject:<t t-esc="object.name"/></t>
<a t-attf-href="{{ object.get_base_url() }}/web#id={{ object.id }}&amp;model=project.task&amp;view_type=form">Task #<t t-esc="object.id"/></a>
<t>Created:<t t-esc="object.create_date" t-options="{'widget': 'datetime', 'format': 'dd.MM.yyyy HH:mm:ss'}"/></t>
<t t-if="object.partner_id">Partner:<t t-esc="object.partner_id.name"/>
Mobile:<t t-esc="object.partner_id.mobile"/>
Email:<t t-esc="object.partner_id.email"/></t>
<t t-if="object.description" t-esc="html2plaintext(object.description)"/></t></field>
</record>
</odoo>

389
i18n/ru.po Normal file
View File

@ -0,0 +1,389 @@
# Translation of Odoo Server.
# This file contains the translation of the following modules:
# * base_telegram
#
msgid ""
msgstr ""
"Project-Id-Version: Odoo Server 17.0\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2025-02-19 07:54+0000\n"
"PO-Revision-Date: 2025-02-19 07:54+0000\n"
"Last-Translator: \n"
"Language-Team: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: \n"
"Plural-Forms: \n"
#. module: base_telegram
#: model_terms:ir.ui.view,arch_db:base_telegram.create_from_chat_id_wizard_view
msgid ""
"<b invisible=\"not test_active or not test_no_record\" class=\"text-"
"warning\">No record for this model</b>"
msgstr ""
"<b invisible=\"not test_active or not test_no_record\" class=\"text-"
"warning\">Нет записей для этой Модели</b>"
#. module: base_telegram
#: model_terms:ir.ui.view,arch_db:base_telegram.view_base_telegram_api_form
msgid "@BotFather"
msgstr "@BotFather"
#. module: base_telegram
#: model:ir.model.fields,field_description:base_telegram.field_wizard_create_notify_new_object__action_server_id_domain
msgid "Action Server Id Domain"
msgstr "Домен Серверного действия"
#. module: base_telegram
#: model:ir.model.fields,field_description:base_telegram.field_wizard_create_notify_new_object__action_code
msgid "Action python code"
msgstr "Python код Действия"
#. module: base_telegram
#: model:ir.model.fields,field_description:base_telegram.field_wizard_create_notify_new_object__test_active
msgid "Activate Preview"
msgstr "Проверить текст извещения"
#. module: base_telegram
#: model_terms:ir.ui.view,arch_db:base_telegram.view_base_telegram_api_form
msgid "Add the bot to the group"
msgstr "Добавьте бота в группу"
#. module: base_telegram
#: model:ir.actions.act_window,name:base_telegram.action_base_telegram_api_view
msgid "Base Telegram API"
msgstr "Telegram API"
#. module: base_telegram
#: model:ir.model.fields,field_description:base_telegram.field_base_telegram_api__token
msgid "Bot Token"
msgstr "Token бота"
#. module: base_telegram
#: model:ir.model.fields,field_description:base_telegram.field_wizard_create_notify_new_object__chat_id
msgid "Bot and chat to send messages"
msgstr "Бот и чат для отправки сообщений"
#. module: base_telegram
#: model:ir.model.fields,field_description:base_telegram.field_base_telegram_api__chat_id
#: model_terms:ir.ui.view,arch_db:base_telegram.get_updates
msgid "Chat ID"
msgstr "Chat ID"
#. module: base_telegram
#: model_terms:ir.ui.view,arch_db:base_telegram.view_base_telegram_api_form
msgid "Click the button <b>Get Chat ID</b> on this form"
msgstr "Нажмите кнопку <b>Получить Chat ID</b> на этой форме"
#. module: base_telegram
#: model_terms:ir.ui.view,arch_db:base_telegram.create_from_chat_id_wizard_view
msgid "Close"
msgstr "Закрыть"
#. module: base_telegram
#: model:ir.model.fields,field_description:base_telegram.field_base_telegram_api__code
msgid "Code Name"
msgstr "Код соединения"
#. module: base_telegram
#: model:ir.ui.menu,name:base_telegram.menu_base_telegram_list
msgid "Connections List"
msgstr "Список соединений"
#. module: base_telegram
#: model_terms:ir.ui.view,arch_db:base_telegram.get_updates
msgid "Content"
msgstr "Содержимое"
#. module: base_telegram
#: model:ir.model,name:base_telegram.model_wizard_create_notify_new_object
msgid "Create Automation to send message to Telegram about new object"
msgstr "Создание Автоматизации для отправки сообщения в Telegram о новом объекте (Задача, Лид и пр.)"
#. module: base_telegram
#: model_terms:ir.ui.view,arch_db:base_telegram.view_base_telegram_api_form
msgid "Create Notification"
msgstr "Создать Уведомление"
#. module: base_telegram
#: model_terms:ir.ui.view,arch_db:base_telegram.view_base_telegram_api_form
msgid "Create a group where the created bot should post messages"
msgstr "Создайте группу, в которую должен писать созданный бот"
#. module: base_telegram
#: model_terms:ir.ui.view,arch_db:base_telegram.create_from_chat_id_wizard_view
msgid "Create and Edit"
msgstr "Создать и Изменить"
#. module: base_telegram
#: model:ir.actions.act_window,name:base_telegram.create_from_chat_id_wizard_action
#: model_terms:ir.ui.view,arch_db:base_telegram.create_from_chat_id_wizard_view
msgid "Create new object notification by Telegram bot"
msgstr "Создание Уведомлений о новых объектах ботом Telegram"
#. module: base_telegram
#: model:ir.model.fields,field_description:base_telegram.field_base_telegram_api__create_uid
#: model:ir.model.fields,field_description:base_telegram.field_wizard_create_notify_new_object__create_uid
msgid "Created by"
msgstr "Создал"
#. module: base_telegram
#: model:ir.model.fields,field_description:base_telegram.field_base_telegram_api__create_date
#: model:ir.model.fields,field_description:base_telegram.field_wizard_create_notify_new_object__create_date
msgid "Created on"
msgstr "Создан"
#. module: base_telegram
#: model_terms:ir.ui.view,arch_db:base_telegram.message_new_task
msgid "Created:"
msgstr "Создан:"
#. module: base_telegram
#: model_terms:ir.ui.view,arch_db:base_telegram.view_base_telegram_api_form
msgid "Creating a Telegram Bot:"
msgstr "Создание бота Telegram:"
#. module: base_telegram
#: model:ir.model.fields,field_description:base_telegram.field_base_telegram_api__display_name
#: model:ir.model.fields,field_description:base_telegram.field_wizard_create_notify_new_object__display_name
msgid "Display Name"
msgstr "Отображаемое имя"
#. module: base_telegram
#: model_terms:ir.ui.view,arch_db:base_telegram.message_new_task
msgid "Email:"
msgstr "Email:"
#. module: base_telegram
#: model_terms:ir.ui.view,arch_db:base_telegram.view_base_telegram_api_form
msgid ""
"Enter the <b>Chat ID</b> value from the table of read messages into the "
"<b>Chat ID</b> field"
msgstr ""
"Внесите в поле <b>Chat ID</b> значение из таблицы прочитанных сообщений"
#. module: base_telegram
#: model_terms:ir.ui.view,arch_db:base_telegram.view_base_telegram_api_form
msgid ""
"Enter the command <b>/newbot</b> to create a bot. Follow the instructions "
"provided by @BotFather"
msgstr ""
"Введите команду <b>/newbot</b>, чтобы создать бота. Следуйте инструкциям @BotFather"
#. module: base_telegram
#: model_terms:ir.ui.view,arch_db:base_telegram.get_updates
msgid "Event"
msgstr "Событие"
#. module: base_telegram
#: model_terms:ir.ui.view,arch_db:base_telegram.view_base_telegram_api_form
msgid "Get Chat ID"
msgstr "Получить Chat ID"
#. module: base_telegram
#: model_terms:ir.ui.view,arch_db:base_telegram.view_base_telegram_api_form
msgid "Grant the bot admin access in the group"
msgstr "Предоставьте боту доступ администратора в группу"
#. module: base_telegram
#: model:ir.model.fields,field_description:base_telegram.field_base_telegram_api__id
#: model:ir.model.fields,field_description:base_telegram.field_wizard_create_notify_new_object__id
msgid "ID"
msgstr "ID"
#. module: base_telegram
#: model:ir.model.fields,help:base_telegram.field_wizard_create_notify_new_object__template_xml_id
msgid "ID of the view defined in xml file"
msgstr "xml_id представления"
#. module: base_telegram
#: model:ir.model.fields,field_description:base_telegram.field_base_telegram_api__write_uid
#: model:ir.model.fields,field_description:base_telegram.field_wizard_create_notify_new_object__write_uid
msgid "Last Updated by"
msgstr "Обновил"
#. module: base_telegram
#: model:ir.model.fields,field_description:base_telegram.field_base_telegram_api__write_date
#: model:ir.model.fields,field_description:base_telegram.field_wizard_create_notify_new_object__write_date
msgid "Last Updated on"
msgstr "Обновлено"
#. module: base_telegram
#: model:ir.model.fields,field_description:base_telegram.field_base_telegram_api__messages_html
msgid "Messages for Bot"
msgstr "Сообщения для бота"
#. module: base_telegram
#: model_terms:ir.ui.view,arch_db:base_telegram.message_new_task
msgid "Mobile:"
msgstr "Мобильный:"
#. module: base_telegram
#: model:ir.model.fields,field_description:base_telegram.field_wizard_create_notify_new_object__res_model_id
msgid "Model"
msgstr "Модель"
#. module: base_telegram
#: model:ir.model.fields,field_description:base_telegram.field_base_telegram_api__name
#: model:ir.model.fields,field_description:base_telegram.field_wizard_create_notify_new_object__name
msgid "Name"
msgstr "Наименование"
#. module: base_telegram
#: model:ir.model.fields,field_description:base_telegram.field_wizard_create_notify_new_object__test_no_record
msgid "No Record"
msgstr "Нет записей"
#. module: base_telegram
#: model_terms:ir.ui.view,arch_db:base_telegram.view_base_telegram_api_form
msgid ""
"Once completed, record the received <b>token</b> in the corresponding field.<br/>\n"
"In the chat with @BotFather, look for the text:<br/><code>\n"
"Use this token to access the HTTP API:<br/>\n"
"1234567890:ABcdeFghKLMNopqrs_TUvWxyz\n"
"</code>"
msgstr ""
"По завершении запишите полученный <b>token</b> в одноименное поле.<br/>\n"
"В чате @BotFather ищите текст:<br/><code>\n"
"Use this token to access the HTTP API:<br/>\n"
"1234567890:ABcdeFghKLMNopqrs_TUvWxyz\n"
"</code>"
#. module: base_telegram
#: model_terms:ir.ui.view,arch_db:base_telegram.view_base_telegram_api_form
msgid "Open the chat with"
msgstr "Откройте чат с"
#. module: base_telegram
#: model_terms:ir.ui.view,arch_db:base_telegram.message_new_task
msgid "Partner:"
msgstr "Партнер:"
#. module: base_telegram
#: model:ir.model.fields,help:base_telegram.field_wizard_create_notify_new_object__chat_id
msgid "Select Bot and chat to send messages"
msgstr "Выберите Бота и Чат для отправки сообщений"
#. module: base_telegram
#: model:ir.model.fields,help:base_telegram.field_wizard_create_notify_new_object__res_model_id
msgid "Select Model where new object will be monitored"
msgstr "Выберите Модель для отслеживания новых объектов"
#. module: base_telegram
#: model:ir.model.fields,help:base_telegram.field_wizard_create_notify_new_object__template_id
msgid "Select QWeb Template to compose message"
msgstr "Выберите QWeb шаблон для формирования сообщения"
#. module: base_telegram
#: model_terms:ir.ui.view,arch_db:base_telegram.view_base_telegram_api_form
msgid "Send Test Message"
msgstr "Отправить тестовое сообщение"
#. module: base_telegram
#: model_terms:ir.ui.view,arch_db:base_telegram.view_base_telegram_api_form
msgid "Send a test message in the group, ensure that the bot can read it"
msgstr "Отправить тестовое сообщение в группу, убедитесь в наличии у бота прав читать сообщения"
#. module: base_telegram
#: model:ir.model.fields,field_description:base_telegram.field_wizard_create_notify_new_object__action_server_id
msgid "Server action to send message"
msgstr "Серверное действие для отправки сообщения"
#. module: base_telegram
#: model_terms:ir.ui.view,arch_db:base_telegram.message_new_task
msgid "Subject:"
msgstr "Тема:"
#. module: base_telegram
#: model_terms:ir.ui.view,arch_db:base_telegram.message_new_task
msgid "Task #"
msgstr "Задача #"
#. module: base_telegram
#: model:ir.model,name:base_telegram.model_base_telegram_api
msgid "Telegram API"
msgstr "Telegram API"
#. module: base_telegram
#: model:ir.ui.menu,name:base_telegram.menu_base_telegram
msgid "Telegram API Connections"
msgstr "Соединения Telegram API"
#. module: base_telegram
#: model_terms:ir.actions.act_window,help:base_telegram.action_base_telegram_api_view
msgid "Telegram Chats List"
msgstr "Список чатов Telegram"
#. module: base_telegram
#: model:ir.model.fields,field_description:base_telegram.field_wizard_create_notify_new_object__template_id
msgid "Template"
msgstr "Шаблон"
#. module: base_telegram
#: model:ir.model.fields,field_description:base_telegram.field_wizard_create_notify_new_object__template_id_domain
msgid "Template Id Domain"
msgstr "Домен для поиска Шаблонов"
#. module: base_telegram
#: model:ir.model.fields,field_description:base_telegram.field_wizard_create_notify_new_object__test_lang
msgid "Template Preview Language"
msgstr "Язык предпросмотра"
#. module: base_telegram
#: model:ir.model.fields,field_description:base_telegram.field_wizard_create_notify_new_object__template_arch
msgid "Template arch"
msgstr "Код (arch) шаблона"
#. module: base_telegram
#: model:ir.model.fields,field_description:base_telegram.field_wizard_create_notify_new_object__template_xml_id
msgid "Template xml_id"
msgstr "xml_id шаблона"
#. module: base_telegram
#: model:ir.model.fields,field_description:base_telegram.field_wizard_create_notify_new_object__test_preview
msgid "Test Preview"
msgstr "Предпросмотр активирован"
#. module: base_telegram
#: model:ir.model.fields,field_description:base_telegram.field_wizard_create_notify_new_object__test_record_ref
msgid "Test Record"
msgstr "Тестовая запись"
#. module: base_telegram
#: model_terms:ir.ui.view,arch_db:base_telegram.create_from_chat_id_wizard_view
msgid "Test Record:"
msgstr "Тестовая запись:"
#. module: base_telegram
#. odoo-python
#: code:addons/base_telegram/models/base_telegram.py:0
#, python-format
msgid "Test from Odoo"
msgstr "Тест из Odoo"
#. module: base_telegram
#: model:ir.model.fields,help:base_telegram.field_wizard_create_notify_new_object__template_arch
msgid ""
"This field should be used when accessing view arch. It will use translation.\n"
" Note that it will read `arch_db` or `arch_fs` if in dev-xml mode."
msgstr ""
#. module: base_telegram
#: model_terms:ir.ui.view,arch_db:base_telegram.get_updates
msgid "Time"
msgstr "Время"
#. module: base_telegram
#: model_terms:ir.ui.view,arch_db:base_telegram.get_updates
msgid "new chat member"
msgstr "новый участнник чата"
#. module: base_telegram
#: model_terms:ir.ui.view,arch_db:base_telegram.get_updates
msgid "no messages"
msgstr "нет сообщений"
#. module: base_telegram
#: model_terms:ir.ui.view,arch_db:base_telegram.create_from_chat_id_wizard_view
msgid "or"
msgstr "или"

1
models/__init__.py Normal file
View File

@ -0,0 +1 @@
from . import base_telegram

76
models/base_telegram.py Normal file
View File

@ -0,0 +1,76 @@
from odoo import api, fields, models, _
import requests
import json
from odoo.tools import html2plaintext
import logging
_logger = logging.getLogger(__name__)
class TelegramAPI(models.Model):
_name = "base_telegram.api"
_description = "Telegram API"
code = fields.Char(string='Code Name', index=True)
name = fields.Char(string='Name')
chat_id = fields.Char(string='Chat ID')
token = fields.Char(string='Bot Token')
messages_html = fields.Html(string='Messages for Bot', compute='_compute_messages_html', store=False, readonly=True)
@api.onchange('token')
def _compute_messages_html(self):
for rec in self:
result = rec.get_updates() if rec.token else []
rec.messages_html = self.render_template('base_telegram.get_updates', {'result': result} if result else {})
def get_url(self, command):
return "https://api.telegram.org/bot{token}/{command}".format(token = self.token, command = command)
def send_message(self, message):
cnt = 0
for chat in self:
#url = "https://api.telegram.org/bot{token}/sendMessage".format(token = chat.token)
url = chat.get_url('sendMessage')
info = {
'chat_id': chat.chat_id,
'text': message,
'parse_mode': 'HTML'
}
try:
response = requests.post(url, data=info)
#response.raise_for_status()
cnt += 1
except requests.exceptions.RequestException as e:
_logger.info(f"Error: {e}")
return cnt
def send_template(self, template, obj, data = dict()):
return self.send_message(str(
self.with_context(
lang=self.env.user.lang if self.env.user.lang else 'ru_RU',
tz=self.env.user.tz if self.env.user.tz else 'Europe/Moscow'
).render_template(template, data)
))
def get_updates(self):
url = self.get_url('getUpdates')
try:
response = requests.post(url, data='')
except requests.exceptions.RequestException as e:
_logger.info(f"Error: {e}")
return json.loads(response.content).get('result',[]) if response and response.content else []
def render_template(self, template, obj = False, data = dict()):
if not data:
data = dict()
data['object'] = obj
data['html2plaintext'] = html2plaintext
return self.env['ir.qweb']._render(template, data, lang='ru_RU')
def button_get_messages(self):
self.get_updates()
self._compute_messages_html()
return True
def button_send_test(self):
self.send_message(_('Test from Odoo'))
return True

View File

@ -0,0 +1,3 @@
id,name,model_id:id,group_id:id,perm_read,perm_write,perm_create,perm_unlink
access_base_telegram_api,access_base_telegram_api,model_base_telegram_api,,1,1,1,1
access_wizard_create_notify_new_object,access_wizard_create_notify_new_object,model_wizard_create_notify_new_object,,1,1,1,1
1 id name model_id:id group_id:id perm_read perm_write perm_create perm_unlink
2 access_base_telegram_api access_base_telegram_api model_base_telegram_api 1 1 1 1
3 access_wizard_create_notify_new_object access_wizard_create_notify_new_object model_wizard_create_notify_new_object 1 1 1 1

Binary file not shown.

After

Width:  |  Height:  |  Size: 158 KiB

BIN
static/description/icon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

View File

@ -0,0 +1,374 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Telegram API</title>
<style type="text/css">
/* used to remove borders from tables and images */
.borderless, table.borderless td, table.borderless th {
border: 0 }
table.borderless td, table.borderless th {
/* Override padding for "table.docutils td" with "! important".
The right padding separates the table cells. */
padding: 0 0.5em 0 0 ! important }
.first {
/* Override more specific margin styles with "! important". */
margin-top: 0 ! important }
.last, .with-subtitle {
margin-bottom: 0 ! important }
.hidden {
display: none }
.subscript {
vertical-align: sub;
font-size: smaller }
.superscript {
vertical-align: super;
font-size: smaller }
a.toc-backref {
text-decoration: none ;
color: black }
blockquote.epigraph {
margin: 2em 5em ; }
dl.docutils dd {
margin-bottom: 0.5em }
object[type="image/svg+xml"], object[type="application/x-shockwave-flash"] {
overflow: hidden;
}
/* Uncomment (and remove this text!) to get bold-faced definition list terms
dl.docutils dt {
font-weight: bold }
*/
div.abstract {
margin: 2em 5em }
div.abstract p.topic-title {
font-weight: bold ;
text-align: center }
div.admonition, div.attention, div.caution, div.danger, div.error,
div.hint, div.important, div.note, div.tip, div.warning {
margin: 2em ;
border: medium outset ;
padding: 1em }
div.admonition p.admonition-title, div.hint p.admonition-title,
div.important p.admonition-title, div.note p.admonition-title,
div.tip p.admonition-title {
font-weight: bold ;
font-family: sans-serif }
div.attention p.admonition-title, div.caution p.admonition-title,
div.danger p.admonition-title, div.error p.admonition-title,
div.warning p.admonition-title, .code .error {
color: red ;
font-weight: bold ;
font-family: sans-serif }
/* Uncomment (and remove this text!) to get reduced vertical space in
compound paragraphs.
div.compound .compound-first, div.compound .compound-middle {
margin-bottom: 0.5em }
div.compound .compound-last, div.compound .compound-middle {
margin-top: 0.5em }
*/
div.dedication {
margin: 2em 5em ;
text-align: center ;
font-style: italic }
div.dedication p.topic-title {
font-weight: bold ;
font-style: normal }
div.figure {
margin-left: 2em ;
margin-right: 2em }
div.footer, div.header {
clear: both;
font-size: smaller }
div.line-block {
display: block ;
margin-top: 1em ;
margin-bottom: 1em }
div.line-block div.line-block {
margin-top: 0 ;
margin-bottom: 0 ;
margin-left: 1.5em }
div.sidebar {
margin: 0 0 0.5em 1em ;
border: medium outset ;
padding: 1em ;
background-color: #ffffee ;
width: 40% ;
float: right ;
clear: right }
div.sidebar p.rubric {
font-family: sans-serif ;
font-size: medium }
div.system-messages {
margin: 5em }
div.system-messages h1 {
color: red }
div.system-message {
border: medium outset ;
padding: 1em }
div.system-message p.system-message-title {
color: red ;
font-weight: bold }
div.topic {
margin: 2em }
h1.section-subtitle, h2.section-subtitle, h3.section-subtitle,
h4.section-subtitle, h5.section-subtitle, h6.section-subtitle {
margin-top: 0.4em }
h1.title {
text-align: center }
h2.subtitle {
text-align: center }
hr.docutils {
width: 75% }
img.align-left, .figure.align-left, object.align-left, table.align-left {
clear: left ;
float: left ;
margin-right: 1em }
img.align-right, .figure.align-right, object.align-right, table.align-right {
clear: right ;
float: right ;
margin-left: 1em }
img.align-center, .figure.align-center, object.align-center {
display: block;
margin-left: auto;
margin-right: auto;
}
table.align-center {
margin-left: auto;
margin-right: auto;
}
.align-left {
text-align: left }
.align-center {
clear: both ;
text-align: center }
.align-right {
text-align: right }
/* reset inner alignment in figures */
div.align-right {
text-align: inherit }
/* div.align-center * { */
/* text-align: left } */
.align-top {
vertical-align: top }
.align-middle {
vertical-align: middle }
.align-bottom {
vertical-align: bottom }
ol.simple, ul.simple {
margin-bottom: 1em }
ol.arabic {
list-style: decimal }
ol.loweralpha {
list-style: lower-alpha }
ol.upperalpha {
list-style: upper-alpha }
ol.lowerroman {
list-style: lower-roman }
ol.upperroman {
list-style: upper-roman }
p.attribution {
text-align: right ;
margin-left: 50% }
p.caption {
font-style: italic }
p.credits {
font-style: italic ;
font-size: smaller }
p.label {
white-space: nowrap }
p.rubric {
font-weight: bold ;
font-size: larger ;
color: maroon ;
text-align: center }
p.sidebar-title {
font-family: sans-serif ;
font-weight: bold ;
font-size: larger }
p.sidebar-subtitle {
font-family: sans-serif ;
font-weight: bold }
p.topic-title {
font-weight: bold }
pre.address {
margin-bottom: 0 ;
margin-top: 0 ;
font: inherit }
pre.literal-block, pre.doctest-block, pre.math, pre.code {
margin-left: 2em ;
margin-right: 2em }
pre.code .ln { color: grey; } /* line numbers */
pre.code, code { background-color: #eeeeee }
pre.code .comment, code .comment { color: #5C6576 }
pre.code .keyword, code .keyword { color: #3B0D06; font-weight: bold }
pre.code .literal.string, code .literal.string { color: #0C5404 }
pre.code .name.builtin, code .name.builtin { color: #352B84 }
pre.code .deleted, code .deleted { background-color: #DEB0A1}
pre.code .inserted, code .inserted { background-color: #A3D289}
span.classifier {
font-family: sans-serif ;
font-style: oblique }
span.classifier-delimiter {
font-family: sans-serif ;
font-weight: bold }
span.interpreted {
font-family: sans-serif }
span.option {
white-space: nowrap }
span.pre {
white-space: pre }
span.problematic {
color: red }
span.section-subtitle {
/* font-size relative to parent (h1..h6 element) */
font-size: 80% }
table.citation {
border-left: solid 1px gray;
margin-left: 1px }
table.docinfo {
margin: 2em 4em }
table.docutils {
margin-top: 0.5em ;
margin-bottom: 0.5em }
table.footnote {
border-left: solid 1px black;
margin-left: 1px }
table.docutils td, table.docutils th,
table.docinfo td, table.docinfo th {
padding-left: 0.5em ;
padding-right: 0.5em ;
vertical-align: top }
table.docutils th.field-name, table.docinfo th.docinfo-name {
font-weight: bold ;
text-align: left ;
white-space: nowrap ;
padding-left: 0 }
/* "booktabs" style (no vertical lines) */
table.docutils.booktabs {
border: 0px;
border-top: 2px solid;
border-bottom: 2px solid;
border-collapse: collapse;
}
table.docutils.booktabs * {
border: 0px;
}
table.docutils.booktabs th {
border-bottom: thin solid;
text-align: left;
}
h1 tt.docutils, h2 tt.docutils, h3 tt.docutils,
h4 tt.docutils, h5 tt.docutils, h6 tt.docutils {
font-size: 100% }
ul.auto-toc {
list-style-type: none }
</style>
</head>
<body>
<div class="document">
<h1 class="title">Telegram API</h1>
<h1>Odoo base_telegram</h1>
<p>Odoo Telegram API
Menu: Settings / Technical / Parameters / Telegram API Connections</p>
<h2>Add new connection</h2>
<ul>
<li>Open the chat with <a href="https://t.me/BotFather">@BotFather</a></li>
<li>Enter the command <strong>/newbot</strong> to create a bot</li>
<li>Save received <strong>token</strong> (like: 1234567890:ABcdeFghKLMNopqrs_TUvWxyz)</li>
<li>Create a group where the created bot should post messages</li>
<li>Add the bot to the group</li>
<li>Grant the bot admin access in the group</li>
<li>Send a test message in the group, ensure that the bot can read it</li>
<li>Save <strong>Chat ID</strong> from test message</li>
</ul>
<p><img alt="Telegram API new connection form" src="chat_bot_config_form.png" title="Telegram API new connection form" /></p>
<h2>Send message to Telegram</h2>
<p><code>env["base.telegram"].browse(1).send_message('Test')</code></p>
<h2>Send message from project.task by template</h2>
<p><code>self = env["base.telegram"].browse(1)
obj = env['project.task'].browse(4)
self.with_context(lang=env.user.lang if env.user.lang else 'ru_RU', tz=env.user.tz if env.user.tz else 'Europe/Moscow').send_template('base_telegram.message_new_task', obj)</code></p>
</div>
</body>
</html>

View File

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="utf-8"?>
<odoo>
<data>
<menuitem
id="menu_base_telegram"
name="Telegram API Connections"
parent="base.menu_ir_property"
sequence="50"/>
<menuitem
id="menu_base_telegram_list"
name="Connections List"
parent="menu_base_telegram"
action="action_base_telegram_api_view"
sequence="10"/>
</data>
</odoo>

View File

@ -0,0 +1,33 @@
<?xml version="1.0" encoding="utf-8"?>
<odoo>
<template id="get_updates" name="Show Messages for Telegram Bot">
<table class="table table-sm table-striped">
<tr>
<td>Time</td>
<td>Chat ID</td>
<td>Event</td>
<td>Content</td>
</tr>
<tr t-foreach="result" t-as="rec">
<t t-set="msg" t-value="rec.get('message',{})"/>
<t t-set="chat_member" t-value="rec.get('my_chat_member',{})"/>
<t t-if="msg">
<t t-set="migrate_id" t-value="msg.get('migrate_from_chat_id','') if msg.get('migrate_from_chat_id','') else msg.get('migrate_to_chat_id','')"/>
<td><t t-esc="datetime.datetime.fromtimestamp(msg.get('date')) if msg.get('date') else ''"/></td>
<td><b><t t-esc="msg.get('chat',{}).get('id') if msg.get('text') else migrate_id"/></b></td>
<td><t t-esc="'message' if msg.get('text') else ('member added' if migrate_id else '-')"/></td>
<td><t t-esc="msg.get('text','') if msg.get('text') else (msg.get('chat',{}).get('title') if migrate_id else '')"/></td>
</t>
<t t-elif="chat_member">
<td><t t-esc="datetime.datetime.fromtimestamp(chat_member.get('date')) if chat_member.get('date') else ''"/></td>
<td><b><t t-esc="chat_member.get('chat',{}).get('id')"/></b></td>
<td>new chat member</td>
<td><t t-esc="chat_member.get('new_chat_member',{}).get('user',{}).get('username')"/></td>
</t>
<t t-else="">
<td>no messages</td>
</t>
</tr>
</table>
</template>
</odoo>

View File

@ -0,0 +1,74 @@
<?xml version="1.0" encoding="utf-8"?>
<odoo>
<record id="action_base_telegram_api_view" model="ir.actions.act_window">
<field name="name">Base Telegram API</field>
<field name="type">ir.actions.act_window</field>
<field name="res_model">base_telegram.api</field>
<field name="view_mode">tree,form,kanban</field>
<field name="domain"></field>
<field name="context">{}</field>
<field name="help" type="html">
<p class="o_view_nocontent_smiling_face">
Telegram Chats List
</p>
</field>
</record>
<record id="view_base_telegram_api_tree" model="ir.ui.view">
<field name="name">base_telegram.api.tree</field>
<field name="model">base_telegram.api</field>
<field name="arch" type="xml">
<tree multi_edit="1">
<field name="code" optional="show"/>
<field name="name" optional="show"/>
<field name="token" optional="show"/>
<field name="chat_id" optional="show"/>
</tree>
</field>
</record>
<record id="view_base_telegram_api_form" model="ir.ui.view">
<field name="name">base_telegram.api.form</field>
<field name="model">base_telegram.api</field>
<field name="arch" type="xml">
<form>
<header>
<button name="button_get_messages" string="Get Chat ID" class="btn-primary" type="object" invisible="not token" />
<button name="button_send_test" string="Send Test Message" class="btn-primary" type="object" invisible="not chat_id"/>
<button name="%(create_from_chat_id_wizard_action)d" string="Create Notification" class="btn-primary" type="action" invisible="not chat_id" target="new"/>
</header>
<sheet>
<group>
<group>
<field name="code"/>
<field name="name"/>
<field name="token"/>
<field name="chat_id"/>
</group>
<group col="2">
<div colspan="2">Creating a Telegram Bot:
<ul>
<li>Open the chat with <a href="https://t.me/BotFather">@BotFather</a></li>
<li>Enter the command <b>/newbot</b> to create a bot. Follow the instructions provided by @BotFather</li>
<li>Once completed, record the received <b>token</b> in the corresponding field.<br/>
In the chat with @BotFather, look for the text:<br/><code>
Use this token to access the HTTP API:<br/>
1234567890:ABcdeFghKLMNopqrs_TUvWxyz
</code></li>
<li>Create a group where the created bot should post messages</li>
<li>Add the bot to the group</li>
<li>Grant the bot admin access in the group</li>
<li>Send a test message in the group, ensure that the bot can read it</li>
<li>Click the button <b>Get Chat ID by test message</b> on this form</li>
<li>Enter the <b>Chat ID</b> value from the table of read messages into the <b>Chat ID</b> field</li>
</ul>
</div>
</group>
</group>
<field name="messages_html" columns="2"/>
</sheet>
</form>
</field>
</record>
</odoo>

1
wizard/__init__.py Normal file
View File

@ -0,0 +1 @@
from . import create_notify_new_object

View File

@ -0,0 +1,116 @@
from odoo import fields, models, api
from odoo.exceptions import AccessError, MissingError, UserError, ValidationError
class WizardCreateNotifyNewObject(models.TransientModel):
_name = "wizard.create.notify.new.object"
_description = "Create Automation to send message to Telegram about new object"
@api.model
def _selection_target_model(self):
return [(model.model, model.name) for model in self.env['ir.model'].sudo().search([])]
@api.model
def _selection_languages(self):
return self.env['res.lang'].get_installed()
name = fields.Char(required=True)
chat_id = fields.Many2one('base_telegram.api', string='Bot and chat to send messages', required=True,
help="Select Bot and chat to send messages")
res_model_id = fields.Many2one('ir.model', string='Model', required=True,
help="Select Model where new object will be monitored")
template_id_domain = fields.Char(compute="_compute_template_id_domain")
template_id = fields.Many2one('ir.ui.view', string='Template', domain="template_id_domain",
help="Select QWeb Template to compose message")
template_xml_id = fields.Char(string='Template xml_id', related='template_id.xml_id')
template_arch = fields.Text(string='Template arch', related='template_id.arch')
action_server_id_domain = fields.Char(compute="_compute_action_server_id")
action_server_id = fields.Many2one('ir.actions.server', string='Server action to send message', required=True, domain="action_server_id_domain")
action_code = fields.Text(string='Action python code', compute='_compute_action_code', compute_sudo=True, readonly=True)
test_active = fields.Boolean(string='Activate Preview')
test_record_ref = fields.Reference(
string='Test Record',
compute='_compute_test_record_ref',
compute_sudo=False, readonly=False,
selection='_selection_target_model',
store=True
)
test_lang = fields.Selection(_selection_languages, string='Template Preview Language')
test_no_record = fields.Boolean('No Record', compute='_compute_no_record')
test_preview = fields.Text('Test Preview', compute='_compute_template_preview')
@api.depends('res_model_id')
def _compute_template_id_domain(self):
for rec in self:
domain = [('model', '=', rec.res_model_id.model if rec.res_model_id else False), ('type', '=', 'qweb')]
rec.template_id_domain = domain
@api.depends('res_model_id')
def _compute_action_server_id(self):
for rec in self:
domain = [('model_id', '=', rec.res_model_id.id if rec.res_model_id else False), ('state', '=', 'code')]
rec.action_server_id_domain = domain
@api.depends('action_server_id')
def _compute_action_code(self):
for rec in self:
if rec.action_server_id:
rec.action_code = rec.action_server_id.code
else:
rec.action_code = False
@api.depends('res_model_id')
def _compute_test_record_ref(self):
for rec in self:
if rec.res_model_id:
res = self.env[rec.res_model_id.model].search([], limit=1)
else:
res = False
rec.test_record_ref = f'{str(rec.res_model_id.model)},{res.id}' if res else False
@api.depends('test_record_ref')
def _compute_no_record(self):
for rec in self:
rec.test_no_record = False if rec.test_record_ref else True
@api.depends('test_record_ref','template_id')
def _compute_template_preview(self):
for rec in self:
if rec.chat_id and rec.test_record_ref and rec.test_record_ref.id and rec.template_id:
try:
rec.test_preview = rec.chat_id.with_context(
lang=rec.test_lang
).render_template(rec.template_xml_id, rec.test_record_ref)
except UserError as e:
rec.test_preview = f"Error: {e}"
else:
rec.test_preview = False
def create_by_chat_id(self):
self.ensure_one()
chat_ids = self.env.context.get("active_ids", [])
assert len(chat_ids) == 1
chat_id = chat_ids[0]
rule_obj = self.env["base.automation"]
automation = rule_obj.create(
{
"name": self.name,
"model_id": self.res_model_id.id,
"trigger": 'on_create_or_write',
"trigger_field_ids": self.env['ir.model.fields'].search([('model_id','=',self.res_model_id.id),('name','=','create_date')]),
"action_server_ids": self.action_server_id.ids,
}
)
return {
"context": self.env.context,
"name": "Automation Rule",
"view_type": "form",
"view_mode": "form",
"res_model": "base.automation",
"res_id": automation.id,
"target": "current",
"type": "ir.actions.act_window",
}

View File

@ -0,0 +1,60 @@
<?xml version="1.0" encoding="UTF-8" ?>
<odoo>
<record id="create_from_chat_id_wizard_view" model="ir.ui.view">
<field name="name">Create new object notification by Telegram bot</field>
<field name="model">wizard.create.notify.new.object</field>
<field name="arch" type="xml">
<form string="Create new object notification by Telegram bot">
<header>
<field name="test_no_record" invisible="1"/>
<field name="res_model_id" invisible="1"/>
<field name="action_server_id" invisible="1"/>
<field name="template_id_domain" invisible="1"/>
<field name="action_server_id_domain" invisible="1"/>
</header>
<group>
<field name="name" />
<field name="chat_id" />
<field name="res_model_id" invisible="not chat_id"/>
<field name="template_id" invisible="not res_model_id"/>
<field name="template_xml_id" invisible="not template_id"/>
<field name="template_arch" invisible="not template_id"/>
<field name="action_server_id" invisible="not res_model_id or not template_id"/>
<field name="action_code" invisible="not action_server_id"/>
<field name="test_active" invisible="not template_id"/>
<label for="test_record_ref" string="Test Record: " invisible="not test_active or test_no_record"/>
<field name="test_record_ref" nolabel="1"
options="{'hide_model': True, 'no_create': True, 'no_open': False}"
readonly="False"
invisible="not test_active or test_no_record"/>
<b invisible="not test_active or not test_no_record" class="text-warning">No record for this model</b>
<field name="test_lang" invisible="not test_active or not test_record_ref"/>
<field name="test_preview" invisible="not test_active or not test_record_ref"/>
</group>
<footer>
<button
name="create_by_chat_id"
string="Create and Edit"
type="object"
class="oe_highlight"
invisible="not chat_id or not action_server_id"
/>
or
<button string="Close" class="oe_link" special="cancel" />
</footer>
</form>
</field>
</record>
<record id="create_from_chat_id_wizard_action" model="ir.actions.act_window">
<field name="name">Create new object notification by Telegram bot</field>
<field name="res_model">wizard.create.notify.new.object</field>
<field name="view_mode">form</field>
<field name="target">new</field>
<field name="binding_model_id" eval="False"/>
<field name="view_id" ref="create_from_chat_id_wizard_view"/>
<field name="context">{'default_chat_id':active_id}</field>
</record>
</odoo>