U
    h#                     @   sP   d dl Z ddlmZmZmZmZ ddlmZ ddlm	Z	 eG dd deZ
dS )	    N   )EventBuilderEventCommonname_inner_event_into_id_set   )utils)typesc                	       sj   e Zd ZdZddddddddd fddZ fddZedd	d
Z fddZG dd de	Z
  ZS )
NewMessagea  
    Occurs whenever a new text message or a message with media arrives.

    Args:
        incoming (`bool`, optional):
            If set to `True`, only **incoming** messages will be handled.
            Mutually exclusive with ``outgoing`` (can only set one of either).

        outgoing (`bool`, optional):
            If set to `True`, only **outgoing** messages will be handled.
            Mutually exclusive with ``incoming`` (can only set one of either).

        from_users (`entity`, optional):
            Unlike `chats`, this parameter filters the *senders* of the
            message. That is, only messages *sent by these users* will be
            handled. Use `chats` if you want private messages with this/these
            users. `from_users` lets you filter by messages sent by *one or
            more* users across the desired chats (doesn't need a list).

        forwards (`bool`, optional):
            Whether forwarded messages should be handled or not. By default,
            both forwarded and normal messages are included. If it's `True`
            *only* forwards will be handled. If it's `False` only messages
            that are *not* forwards will be handled.

        pattern (`str`, `callable`, `Pattern`, optional):
            If set, only messages matching this pattern will be handled.
            You can specify a regex-like string which will be matched
            against the message, a callable function that returns `True`
            if a message is acceptable, or a compiled regex pattern.

    Example
        .. code-block:: python

            import asyncio
            from telethon import events

            @client.on(events.NewMessage(pattern='(?i)hello.+'))
            async def handler(event):
                # Respond whenever someone says "Hello" and something else
                await event.reply('Hey!')

            @client.on(events.NewMessage(outgoing=True, pattern='!ping'))
            async def handler(event):
                # Say "!pong" whenever you send "!ping", then delete both messages
                m = await event.respond('!pong')
                await asyncio.sleep(5)
                await client.delete_messages(event.chat_id, [event.id, m.id])
    NF)blacklist_chatsfuncincomingoutgoing
from_usersforwardspatternc          	   
      s  |r|rd  }}nN|d k	r*|d kr*| }n6|d k	rB|d krB| }nt dd ||fD r`tdt j|||d || _|| _|| _|| _t|t	rt
|j| _n:|rt|r|| _n&t|drt|jr|j| _ntdt dd | j| j| j| j| j| j| j| jfD | _d S )Nc                 s   s   | ]}|d k	o| V  qd S N .0xr   r   >/tmp/pip-unpacked-wheel-c81u5j2r/telethon/events/newmessage.py	<genexpr>D   s     z&NewMessage.__init__.<locals>.<genexpr>zNDon't create an event handler if you don't want neither incoming nor outgoing!)r   r   matchzInvalid pattern type givenc                 s   s   | ]}|d kV  qd S r   r   r   r   r   r   r   W   s     )all
ValueErrorsuper__init__r   r   r   r   
isinstancestrrecompiler   r   callablehasattr	TypeErrorchatsr   	_no_check)	selfr%   r   r   r   r   r   r   r   	__class__r   r   r   ;   s<    


      zNewMessage.__init__c                    s*   t  |I d H  t|| jI d H | _d S r   )r   _resolver   r   )r'   clientr(   r   r   r*   \   s    zNewMessage._resolvec                 C   s  t |tjtjfr2t |jtjs$d S | |j}nt |tjr| tj|j|j	|j
|j|jt|jt|jrr|n|j|j|j|j|j|j|j|jd}nrt |tjr| tj|j|j	|j
|j|jt|jr|n|jt|j|j|j|j|j|j|j|jd}nd S |S )N)out	mentionedmedia_unreadsilentidpeer_idfrom_idmessagedatefwd_from
via_bot_idreply_toentities
ttl_period)r,   r-   r.   r/   r0   r2   r1   r3   r4   r5   r6   r7   r8   r9   )r   r	   ZUpdateNewMessageZUpdateNewChannelMessager3   MessageEventZUpdateShortMessager,   r-   r.   r/   r0   ZPeerUserZuser_idr4   r5   r6   r7   r8   r9   ZUpdateShortChatMessager2   ZPeerChatZchat_id)clsupdateZothersself_ideventr   r   r   build`   sT    




zNewMessage.buildc                    s   | j r
|S | jr|jjrd S | jr.|jjs.d S | jd k	rRt| jt|jjkrRd S | jd k	rn|jj	| jkrnd S | j
r| 
|jjpd}|sd S ||_t |S )N )r&   r   r3   r,   r   r   boolr5   r   Z	sender_idr   pattern_matchr   filter)r'   r?   r   r(   r   r   rD      s$    

zNewMessage.filterc                       s<   e Zd ZdZ fddZ fddZdd Zdd	 Z  ZS )
zNewMessage.Eventa  
        Represents the event of a new message. This event can be treated
        to all effects as a `Message <telethon.tl.custom.message.Message>`,
        so please **refer to its documentation** to know what you can do
        with this event.

        Members:
            message (`Message <telethon.tl.custom.message.Message>`):
                This is the only difference with the received
                `Message <telethon.tl.custom.message.Message>`, and will
                return the `telethon.tl.custom.message.Message` itself,
                not the text.

                See `Message <telethon.tl.custom.message.Message>` for
                the rest of available members and methods.

            pattern_match (`obj`):
                The resulting object from calling the passed ``pattern`` function.
                Here's an example using a string (defaults to regex match):

                >>> from telethon import TelegramClient, events
                >>> client = TelegramClient(...)
                >>>
                >>> @client.on(events.NewMessage(pattern=r'hi (\w+)!'))
                ... async def handler(event):
                ...     # In this case, the result is a ``Match`` object
                ...     # since the `str` pattern was converted into
                ...     # the ``re.compile(pattern).match`` function.
                ...     print('Welcomed', event.pattern_match.group(1))
                ...
                >>>
        c                    s6   d| j d< t j|j|jt|jd d | _|| _d S )NF_init)Z	chat_peerZmsg_id	broadcast)	__dict__r   r   r1   r0   rB   postrC   r3   )r'   r3   r(   r   r   r      s    

 zNewMessage.Event.__init__c                    s0   t  | | j}||| jd  d| jd< d S )NTrE   )r   _set_clientr3   Z_finish_initZ	_entitiesrG   )r'   r+   mr(   r   r   rI      s    zNewMessage.Event._set_clientc                 C   s$   || j kr| j | S t| j|S d S r   )rG   getattrr3   )r'   itemr   r   r   __getattr__   s    

zNewMessage.Event.__getattr__c                 C   s2   | j d r|| j kr || j |< nt| j|| d S )NrE   )rG   setattrr3   )r'   namevaluer   r   r   __setattr__   s    zNewMessage.Event.__setattr__)	__name__
__module____qualname____doc__r   rI   rM   rQ   __classcell__r   r   r(   r   r;      s
    r;   )N)NN)rR   rS   rT   rU   r   r*   classmethodr@   rD   r   r;   rV   r   r   r(   r   r
      s   1   !-r
   )r    commonr   r   r   r   rA   r   tlr	   r
   r   r   r   r   <module>   s
   