def checkCurChat(chatname, client): print("\n") try: int_chat = int(chatname) except: int_chat = 0 if int_chat != 0: input_channel = client(GetFullChannelRequest(int_chat)) channel_id = input_channel.full_chat.id channel = int_chat print("<<<Fast checking: " + input_channel.chats[0].title + " (" + str(int_chat) + ">>>") else: response = client.invoke(ResolveUsernameRequest(chatname)) channel_id = response.peer.channel_id channel = chatname print("<<<Fast checking: " + response.chats[0].title + " (" + response.chats[0].username + ") >>>") for msg in client.get_messages(channel_id, limit=1): if (msg != '') and not (msg is None): if not hasattr(msg, 'text'): msg.text = None if msg.text is None and hasattr(msg, 'entities'): msg.text = markdown.unparse(msg.message, msg.entities or []) if msg.text is None and msg.message: msg.text = msg.message textCheck(msg.text, False, 1, client) return channel
def __convert(self, ret): if inspect.iscoroutine(ret): async def wrapper(): return self.__convert(await ret) return wrapper() if isinstance(ret, list): for i, thing in enumerate(ret): ret[i] = self.__convert(thing) elif getattr( getattr(getattr(ret, "__self__", ret), "__class__", None), "__module__", "" ).startswith("telethon"): ret = MarkdownBotPassthrough(ret) if hasattr(ret, "text"): logger.debug( "%r(%s) %r(%s)", ret.entities, type(ret.entities), ret.message, type(ret.message), ) ret.text = markdown.unparse( ret.message, [x.__under for x in ret.entities or []] ) return ret
def test_entity_edges(): """ Test that entities at the edges (start and end) don't crash. """ text = 'Hello, world' entities = [MessageEntityBold(0, 5), MessageEntityBold(7, 5)] result = markdown.unparse(text, entities) assert result == '**Hello**, **world**'
def test_malformed_entities(): """ Test that malformed entity offsets from bad clients don't crash and produce the expected results. """ text = '🏆Telegram Official Android Challenge is over🏆.' entities = [ MessageEntityTextUrl(offset=2, length=43, url='https://example.com') ] result = markdown.unparse(text, entities) assert result == "🏆[Telegram Official Android Challenge is over](https://example.com)🏆."
def test_trailing_malformed_entities(): """ Similar to `test_malformed_entities`, but for the edge case where the malformed entity offset is right at the end (note the lack of a trailing dot in the text string). """ text = '🏆Telegram Official Android Challenge is over🏆' entities = [ MessageEntityTextUrl(offset=2, length=43, url='https://example.com') ] result = markdown.unparse(text, entities) assert result == "🏆[Telegram Official Android Challenge is over](https://example.com)🏆"
def test_entities_together(): """ Test that an entity followed immediately by a different one behaves well. """ original = '**⚙️**__Settings__' stripped = '⚙️Settings' text, entities = markdown.parse(original) assert text == stripped assert entities == [MessageEntityBold(0, 2), MessageEntityItalic(2, 8)] text = markdown.unparse(text, entities) assert text == original
def test_offset_at_emoji(): """ Tests that an entity starting at a emoji preserves the emoji. """ text = 'Hi\n👉 See example' entities = [ MessageEntityBold(0, 2), MessageEntityItalic(3, 2), MessageEntityBold(10, 7) ] parsed = '**Hi**\n__👉__ See **example**' assert markdown.parse(parsed) == (text, entities) assert markdown.unparse(text, entities) == parsed
def checkCurchan(channel, client, signals_limit): chantitle = channel.title if not chantitle: chantitle = channel.name if not chantitle: chantitle = str(channel.id) global log if log: log.write("\n\n") log.write("------------------------------\n") log.write("BEGIN CHECKING CHANNEL: "+channel.title+" - " + channel.name +" - " + str(channel.id) + "\n") log.write("------------------------------\n") log.write("\n\n") channame = channel.name if not channame and channel.id != 0: int_chan = int(channel.id) else: int_chan = 0 if int_chan != 0: try: input_channel = client(GetFullChannelRequest(int_chan)) channel_id = input_channel.full_chat.id except Exception as e: print(str(e)) return None else: try: response = client.invoke(ResolveUsernameRequest(channame)) channel_id = response.peer.channel_id except Exception as e: print(str(e)) return None if signals_limit > 0: for msg in client.get_messages(channel_id, limit=signals_limit): if (msg != '') and not (msg is None): if not hasattr(msg, 'text'): msg.text = None if msg.text is None and hasattr(msg, 'entities'): msg.text = markdown.unparse(msg.message, msg.entities or []) if msg.text is None and msg.message: msg.text = msg.message separateCheck(msg.text, chantitle, channel.rating, dateFix(msg.date), client) return client.get_input_entity(channel_id)
async def __get_reply_message(self, *args, **kwargs): ret = await self.__under.get_reply_message(*args, **kwargs) if ret is not None: ret.text = markdown.unparse(ret.message, ret.entities) return ret
async def answer(self, *args, log: str or Tuple[str, str] = None, reply: bool = False, **kwargs) -> Union[custom.Message, List[custom.Message]]: """Custom bound method for the Message object""" message_out = None message = await self.client.get_messages(self.chat_id, ids=self.id) reply_to = self.reply_to_msg_id or self.id if len(args) == 1 and isinstance(args[0], str): is_reply = reply or kwargs.get('reply_to', False) text = args[0] msg, msg_entities = markdown.parse(text) if len(msg) <= MAXLIM: if (not (message and message.out) or is_reply or self.fwd_from or (self.media and not isinstance(self.media, types.MessageMediaWebPage))): kwargs.setdefault('reply_to', reply_to) try: kwargs.setdefault('silent', True) message_out = await self.respond(text, **kwargs) except Exception as e: LOGGER.exception(e) else: if len(msg_entities) > 100: messages = await _resolve_entities(msg, msg_entities) chunks = [markdown.unparse(t, e) for t, e in messages] message_out = [] try: first_msg = await self.edit(chunks[0], **kwargs) except errors.rpcerrorlist.MessageIdInvalidError: first_msg = await self.respond(chunks[0], **kwargs) except Exception as e: LOGGER.exception(e) message_out.append(first_msg) for t in chunks[1:]: try: kwargs.setdefault('silent', True) sent = await self.respond(t, **kwargs) message_out.append(sent) except Exception as e: LOGGER.exception(e) else: try: message_out = await self.edit(text, **kwargs) except errors.rpcerrorlist.MessageIdInvalidError: message_out = await self.respond(text, **kwargs) except Exception as e: LOGGER.exception(e) else: if (message and message.out and not (message.fwd_from or message.media)): try: await self.edit("`Output exceeded the limit.`") except errors.rpcerrorlist.MessageIdInvalidError: await self.respond("`Output exceeded the limit.`") except Exception as e: LOGGER.exception(e) kwargs.setdefault('reply_to', reply_to) output = io.BytesIO(msg.strip().encode()) output.name = "output.txt" try: kwargs.setdefault('silent', True) message_out = await self.respond(file=output, **kwargs) output.close() except Exception as e: output.close() LOGGER.exception(e) else: kwargs.setdefault('reply_to', reply_to) try: kwargs.setdefault('silent', True) message_out = await self.respond(*args, **kwargs) except Exception as e: LOGGER.exception(e) if log: if isinstance(log, tuple): command, extra = log text = f"**USERBOT LOG** #{command}" if extra: text += f"\n{extra}" else: text = f"**USERBOT LOG** `Executed command:` #{log}" if self.client.logger: logger_group = self.client.config['userbot'].getint( 'logger_group_id', False) entity = False try: entity = await self.client.get_input_entity(logger_group) except TypeError: LOGGER.info("Your logger group ID is unsupported") except ValueError: LOGGER.info("Your logger group ID cannot be found") except Exception as e: LOGGER.exception(e) if entity: message, msg_entities = markdown.parse(text) if len(message) <= MAXLIM and len(msg_entities) < 100: messages = [(message, msg_entities)] else: messages = await _resolve_entities(message, msg_entities) for text, entities in messages: try: await self.client( functions.messages.SendMessageRequest( peer=entity, message=text, no_webpage=True, silent=True, entities=entities)) await asyncio.sleep(2) except Exception as e: print("Report this error to the support group.") LOGGER.exception(e) return message_out