summaryrefslogtreecommitdiff
path: root/indoteknik_custom/models/website_telegram.py
blob: 45927b7300c7850a77567208c31faa2aac4e6d37 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
import requests
import clipboard
from odoo import models, fields, api
from telethon.sessions import StringSession
from telethon.sync import TelegramClient
from telethon import functions, types
from telethon.tl.types import InputChannel, InputPeerChannel
import asyncio
from telethon.tl.functions.messages import SendMessageRequest

class WebsiteTelegram(models.Model):
    _name = 'website.telegram'
    _description = 'Telegram Channel'
    tittle = fields.Char("Channel Title")
    id_data = fields.Char("Channel ID")
    about = fields.Char("Channel Description")
    is_broadcast = fields.Boolean("Is Broadcast", default=True)
    is_megagroup = fields.Boolean("Is Megagroup", default=False)
    # session_string = 'MIIBCgKCAQEAyMEdY1aR+sCR3ZSJrtztKTKqigvO/vBfqACJLZtS7QMgCGXJ6XIRyy7mx66W0/sOFa7/1mAZtEoIokDP3ShoqF4fVNb6XeqgQfaUHd8wJpDWHcR2OFwvplUUI1PLTktZ9uW2WE23b+ixNwJjJGwBDJPQEQFBE+vfmH0JP503wr5INS1poWg/j25sIWeYPHYeOrFp/eXaqhISP6G+q2IeTaWTXpwZj4LzXq5YOpk4bYEQ6mvRq7D1aHWfYmlEGepfaYR8Q0YqvvhYtMte3ITnuSJs171+GDqpdKcSwHnd6FudwGO4pcCOj4WcDuXc2CTHgH8gFTNhp/Y8/SpDOhvn9QIDAQAB'

    def create_channel(self, *args, **kwargs):
        asyncio.run(self._async_create_channel())

    async def _async_create_channel(self):
        async with TelegramClient(StringSession('1BVtsOJABu30MWCBFwYvvaYbFoIWi43r5a7TUZ2IWwrnSlXIwEhJS5k2y4UKjoDeMPKwhgUWn9lMk02zQjM0ZDzq61YyhkRBvZuu3hCxMsrtP92bkuZtL2g3g1VgI8s7rMhOD_WaGrZbuj-TmbTwIEbN5i1J4raDW2kYzmlLRCbT74xxrGjpzWCnVv7CSS9L2juXuut0lLMgli3_JZbqDO1IyBYh4ZFQYbMf7zv6moDR4MQp1qfnFArsikQcfxjlNXKFcSoyA_GjiIFfCuymwQVtdERXOAH03M_lm8fYbjvgxEkJvxR6hdCnYMcKpIujEEo9SmMmK7Vnl29g1TCPO5tlrDNXq3Ng='), 27799517, 'df8ee44b0ed11108245037d47b511201') as client:
            result = await client(functions.channels.CreateChannelRequest(
                title=self.tittle,
                about=self.about,
                broadcast=False,
                megagroup=True,
            ))
            channel = result.updates[3].message.peer_id
            username_to_add = ['@imsep81', '6285764475716', '@stephanchrst']
            for name in username_to_add:
                user_to_add = await client.get_entity(name)
                result = await client(functions.channels.InviteToChannelRequest(
                    channel=channel,
                    users=[user_to_add.id],
                ))
            message = 'https://erp.indoteknik.com/web#id='+self.id_data+'&action=209&model=stock.picking&view_type=form&cids=1&menu_id=101'
            result = await client(SendMessageRequest(channel, message))

    def send_to_telegram(self, message):
        # if self.env.all.registry.db_name == 'odoo016':return

        # message = self.env.all.registry.db_name + " : " + message
        # message = self.test_message

        apiURL = f'https://api.telegram.org/bot{self.bot_name}/sendMessage'
        try:
            requests.post(apiURL, json={'chat_id': self.chatID, 'text': message})
        except Exception as e:
            print(e)

    def test_send(self):
        try:
            self.env.cr.savepoint() #kembalikan database ke save point jika mengalami kesalahan

            self.env['website.telegram'].search([('name', '=', self.name)])[0].send_to_telegram(self.test_message)
        except Exception as e:
            print(e)

    @api.depends('name', 'chatID', 'bot_name')
    def _calc_python_code(self):
        for record in self:
            if not record.name:
                record.python_code = "pleas put a name"
            elif not record.test_message:
                record.test_message = "test"
            else:
                record.python_code = "self.env['website.telegram'].search([('name', '=', '" + record.name + "')])[0].send_to_telegram('" + record.test_message + "')"

    def copy_chat_id(self):
        record = self.browse(self.id)
        clipboard.copy(record.python_code)

    def paste_chat_id(self):
        record = self.browse(self.id)
        chat_id = clipboard.paste()
        record.write({'chatID': chat_id})

    def paste_bot_name(self):
        record = self.browse(self.id)
        bot_name = clipboard.paste()
        record.write({'bot_name': bot_name})

    def get_updates(self):
        apiURL = f'https://api.telegram.org/bot{self.bot_name}/getUpdates'
        try:
            response = requests.get(apiURL)
            updates = response.json()
            return updates  # Ini akan berisi semua pembaruan, termasuk pesan baru
        except Exception as e:
            print(e)
            return None

    def receive_messages(self):
        updates = self.get_updates()
        if updates and 'result' in updates:
            for update in updates['result']:
                if 'text' in update['channel_post']:
                    message_text = update['channel_post']['text']
                    chat_id = update['channel_post']['chat']['id']
                    chat_name = update['channel_post']['chat']['username']
                    print(f"Received message: {message_text} from chat_id: {chat_id}, that is: {chat_name}")