import requests # import clipboard from odoo import models, fields, api from telethon.sessions import StringSession from telethon.sync import TelegramClient from odoo.exceptions import UserError from telethon import functions, types from telethon.tl.types import InputPeerChannel import asyncio from telethon.tl.functions.messages import SendMessageRequest # from telethon.tl.types import InputMediaPoll, Poll, PollAnswer, PeerChannel import datetime from telethon.tl.types import MessageMediaPoll # from telethon.tl.functions.messages import SendMediaRequest # from telethon.tl.types import TextWithEntities class WebsiteTelegram(models.Model): _name = 'website.telegram' _description = 'Telegram Channel' tittle = fields.Char("Channel Title") invite_link = fields.Char("Channel invite link") username = fields.Char("Channel Name") user_id = fields.Many2many('res.partner', string='User Member', store=True) 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) is_accept = 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, message): asyncio.run(self._async_create_channel(message)) async def _async_create_channel(self, message): 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 channel_link = await client(functions.messages.ExportChatInviteRequest( peer=InputPeerChannel(channel_id=channel.channel_id, access_hash=result.chats[0].access_hash), )) self.invite_link = channel_link.link # Iterasi untuk setiap username for name in self.user_id: if name.telegram_id: user_to_add = await client.get_entity(name.telegram_id) result_add_user = await client(functions.channels.InviteToChannelRequest( channel=channel, users=[user_to_add.id], )) else: raise UserError('ID Telegram '+ name.name + ' salah atau belum diisi') # message = 'https://erp.indoteknik.com/web#id=' + self.id_data + '&action=209&model=sale.order&view_type=form&cids=1&menu_id=101' message_template = 'https://erp.indoteknik.com/web#id=' + self.id_data + '&action=357&model=sale.order&view_type=form&cids=1&menu_id=212' message2 = self.tittle + ' di print oleh ' + self.env.user.name result_massage = await client(SendMessageRequest(channel, message_template)) result_massage2 = await client(SendMessageRequest(channel, message)) # Send the poll to the channel using PeerChannel with the channel's ID # result_polling = await client(SendMediaRequest( # peer=InputPeerChannel(channel_id=channel.channel_id, access_hash=result.chats[0].access_hash), # media=InputMediaPoll(poll=Poll( # question=TextWithEntities(text="ASK RETURN?", entities=[]), # answers=[ # PollAnswer(text=TextWithEntities(text="Accept", entities=[]), option=b'\x01'), # PollAnswer(text=TextWithEntities(text="Reject", entities=[]), option=b'\x02'), # ], # id=2 # )), # message='Ask Return Polling' # )) def receive_messages(self): return asyncio.run(self._async_receive_messages()) async def _async_receive_messages(self): async with TelegramClient(StringSession( '1BVtsOJABu30MWCBFwYvvaYbFoIWi43r5a7TUZ2IWwrnSlXIwEhJS5k2y4UKjoDeMPKwhgUWn9lMk02zQjM0ZDzq61YyhkRBvZuu3hCxMsrtP92bkuZtL2g3g1VgI8s7rMhOD_WaGrZbuj-TmbTwIEbN5i1J4raDW2kYzmlLRCbT74xxrGjpzWCnVv7CSS9L2juXuut0lLMgli3_JZbqDO1IyBYh4ZFQYbMf7zv6moDR4MQp1qfnFArsikQcfxjlNXKFcSoyA_GjiIFfCuymwQVtdERXOAH03M_lm8fYbjvgxEkJvxR6hdCnYMcKpIujEEo9SmMmK7Vnl29g1TCPO5tlrDNXq3Ng='), 27799517, 'df8ee44b0ed11108245037d47b511201') as client: channel = await client.get_entity(self.invite_link) result = await client(functions.messages.GetHistoryRequest( peer=channel, offset_id=42, offset_date=datetime.datetime(2024, 12, 31), add_offset=0, limit=100, max_id=0, min_id=0, hash=channel.access_hash )) accept_found = False for message in result.messages: if not isinstance(message.media, MessageMediaPoll): continue if message.media.results.total_voters > 0: if message.media.results.results[0].voters > message.media.results.results[1].voters: accept_found = True break return accept_found def send_to_telegram(self, message): # apiURL = f'https://api.telegram.org/bot{self.bot_name}/sendMessage' try: # requests.post(apiURL, json={'chat_id': self.chatID, 'text': message}) asyncio.run(self._async_send_to_telegram(message)) except Exception as e: print(e) async def _async_send_to_telegram(self, message): async with TelegramClient(StringSession( '1BVtsOJABu30MWCBFwYvvaYbFoIWi43r5a7TUZ2IWwrnSlXIwEhJS5k2y4UKjoDeMPKwhgUWn9lMk02zQjM0ZDzq61YyhkRBvZuu3hCxMsrtP92bkuZtL2g3g1VgI8s7rMhOD_WaGrZbuj-TmbTwIEbN5i1J4raDW2kYzmlLRCbT74xxrGjpzWCnVv7CSS9L2juXuut0lLMgli3_JZbqDO1IyBYh4ZFQYbMf7zv6moDR4MQp1qfnFArsikQcfxjlNXKFcSoyA_GjiIFfCuymwQVtdERXOAH03M_lm8fYbjvgxEkJvxR6hdCnYMcKpIujEEo9SmMmK7Vnl29g1TCPO5tlrDNXq3Ng='), 27799517, 'df8ee44b0ed11108245037d47b511201') as client: channel = await client.get_entity(self.invite_link) # Iterasi untuk setiap username for username in self.user_id: if username: try: user_to_add = await client.get_entity(username.telegram_id) result_add_user = await client(functions.channels.InviteToChannelRequest( channel=channel, users=[user_to_add.id], )) except Exception as e: print(f"Error adding user {username}: {e}") result_message = await client(SendMessageRequest(channel, message)) def test_send(self): try: self.env.cr.savepoint() self.env['website.telegram'].search([('tittle', '=', self.tittle)])[0].send_to_telegram('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 # 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}")