Esempio n. 1
1
async def stats_handler(event):
    global guilds_str
    text = event.message.message if hasattr(event.message,
                                            'message') else event.message.text
    chat_id = event.message.to_id if hasattr(
        event.message, 'to_id') else event.message.chat_id
    message_id = event.message.id if hasattr(
        event.message, 'id') else event.message.message_id
    if ((type(chat_id) == PeerChannel and chat_id in [
        PeerChannel(RESULTS_PARSE_CHANNEL_ID), PeerChannel(RESULTS_PARSE_CHANNEL_ID_DEBUG)
    ]) or chat_id == RESULTS_FORWARD_CHAT_ID) and \
            ('Результаты сражений:' in text or '⛺️Гильдия' in text or '⛺Гильдия' in text or "Headquarters" in text or
             "🗺State of map" in text):
        debug = type(chat_id) == PeerChannel and chat_id == PeerChannel(
            RESULTS_PARSE_CHANNEL_ID_DEBUG)
        logging.error("Received data from telegram, sending: {}".format(text))
        if '⛺️Гильдия' in text:
            guilds_str += text + "\n"
            logging.info("Adding text to guilds_str = {}".format(guilds_str))
        else:
            print("put stats in queue")
            castles_stats_queue.put({
                "data": text,
                "message_id": message_id,
                "debug": debug
            })
            castles_stats_queue.put({"data": guilds_str, "debug": debug})
            guilds_str = ""
            return
    elif chat_id == CHAT_WARS_ID and "🏆 очков" in text and "Past battles:" in text:
        logging.info("Received /worldtop")
        castles_stats_queue.put({"data": text, "type": "worldtop"})
Esempio n. 2
0
 def __init__(
         self,
         session_name: str,
         api_id: int, api_hash: str, phone: str,
         chat_id: int = None, channel_id: int = None,
         bot_tk: str = None,
         commands: dict = None,
         passthrough: dict = None
 ):
     self.me = None
     self.session_name = session_name
     self.api_id = api_id
     self.api_hash = api_hash
     self.bot_tk = bot_tk
     self.phone = phone
     self.chat_id = None
     self.channel_id = None
     self.client = None
     self.loop = asyncio.new_event_loop()
     asyncio.set_event_loop(self.loop)
     if chat_id:
         self.chat_id = PeerChannel(chat_id)
     if channel_id:
         self.channel_id = PeerChannel(channel_id)
     self.client = self.get_telegram_client()
     TeleBtn._telewrapper = self
     TeleMsgTemplate.commands = commands
     self.passthrough = passthrough
Esempio n. 3
0
async def report(client: Client, chat: Channel, msg: Message, args, kwargs,
                 event):
    config = Config()

    sw_report = kwargs.get('sw', False)

    if msg.is_reply:
        reply: Message = await msg.get_reply_message()

        result = await reply.forward_to(-1001187874753)

        if sw_report:

            client2: TelegramClient = TelegramClient('reporter',
                                                     api_id=config.api_id,
                                                     api_hash=config.api_hash)
            await client2.connect()
            if not await client2.is_user_authorized():
                await client2.start(config.phone_reporter)

            async with client2:
                await client2.get_dialogs()

                reported = await client2.forward_messages(
                    messages=result.id,
                    from_peer=PeerChannel(channel_id=1187874753),
                    entity=PeerChannel(channel_id=1251251585))

                print(reported)
    else:
        return
Esempio n. 4
0
    def get_dest_channel(self, owner_client, client, channel_id, sources):
        """

        :param sources:
        :param TelegramClient owner_client:
        :param TelegramClient client:
        :param int channel_id:
        :return: Channel
        """
        try:
            channel = client.get_entity(PeerChannel(channel_id))

            if channel.admin_rights is None or not channel.admin_rights.post_messages or not channel.admin_rights.invite_link:
                owner_channel = owner_client.get_entity(
                    PeerChannel(channel_id))
                sender = client.get_me()
                self.set_admin(owner_client, sender, owner_channel)

            return channel
        except (ValueError, ChannelPrivateError):
            owner_channel = owner_client.get_entity(PeerChannel(channel_id))
            inv = owner_client(ExportInviteRequest(owner_channel))
            client(ImportChatInviteRequest(inv.link.split('/')[-1]))
            channel = client.get_entity(PeerChannel(channel_id))

            sender = client.get_me()
            self.set_admin(owner_client, sender, owner_channel)
            return channel
Esempio n. 5
0
def my_event_handler(update):
    if (update.message.message):
        # channel id
        channel_id = update.message.to_id.channel_id
        # channel name
        channel_name = client.get_entity(
            PeerChannel(update.message.to_id.channel_id)).username
        # channel message Date
        date_message = update.message.date
        # channel message
        message = update.message.message
        # print(channel_name,"-----",channel_id,"------",date_message,"-----",message)
        if (channel_id in channel_lists):
            client.send_message(PeerChannel(1194529271), message)
Esempio n. 6
0
def update_handler(update):
    try:
        message = update.message
        messages = []
        if isinstance(update, UpdateShortMessage):
            sender = client.get_entity(PeerUser(update.user_id))
            messages.append(update.id)
        elif isinstance(update, UpdateNewChannelMessage):
            sender = client.get_entity(
                PeerChannel(update.message.to_id.channel_id))
            # print(update.message.id)
            messages.append(update.message.id)
        elif isinstance(update, UpdateEditChannelMessage):
            pass
        else:
            # print(type(update))
            # print(update)
            return False
    except Exception as e:
        # print(e)
        return

    try:
        client(
            ForwardMessagesRequest(
                from_peer=sender,  # who sent these messages?
                id=messages,  # which are the messages?
                to_peer=InputPeerSelf()  # who are we forwarding them to?
            ))
        print("FORWARD")
        # print(get_text(update))
    except Exception as e:
        print("EXCEPTION")
        print(get_text(update))
        print(e)
Esempio n. 7
0
    def run(self):
        database = Database()
        client = TelegramClient('session_name', local.api_id, local.api_hash)
        client.start()

        add_notification = (
            "INSERT INTO coin_notification (id, message, date) VALUES (%(notification_id)s, %(notification_message)s, %(notification_date)s)"
        )

        cursor = database.query("select max(id) as mx from coin_notification")

        last_db_id = 0
        for mx in cursor:
            last_db_id = mx[0]

        regex = r'[^a-zA-Z0-9.()%/#]+'
        channel = PeerChannel(channel_id=1131948783)

        while True:
            messages = client.get_messages(channel,
                                           min_id=last_db_id,
                                           limit=1000)
            if len(messages) == 0:
                break

            for m in messages:
                m.message = re.sub(regex, ' ', m.message)
                notification = {
                    'notification_id': m.id,
                    'notification_message': m.message.encode('utf8'),
                    'notification_date': m.date
                }
                database.execute(add_notification, notification)

        database.close()
Esempio n. 8
0
async def stats_handler(event):
    text = event.message.message
    if event.message.to_id == PeerChannel(
            RESULTS_PARSE_CHANNEL_ID) and 'Результаты сражений:' in text:
        print("put stats in queue")
        castles_stats_queue.put(text)
        return
Esempio n. 9
0
 async def check_access(event):
     participants = await bot.get_participants(PeerChannel(chat_id))
     participants_id = [user.id for user in participants]
     if event.sender.id in participants_id:
         return True
     else:
         await bot.send_message(event.sender, 'Отказано в доступе.')
Esempio n. 10
0
def get_chat_messages(client, chat):
    if chat.is_channel:
        entity = PeerChannel(chat.id)
    elif chat.is_group:
        entity = PeerChat(chat.id)
    else:
        raise ValueError('Unknown type of group chat!')

    chat_entity = client.get_input_entity(entity)
    history = dict()


    for message in tqdm(client.iter_messages(chat_entity), desc='# messages retrieved', unit=''):
        sender = message.sender
        username = '******'.format(sender.username)

        if message.sender.username is None:
            username = sender.first_name
            if sender.last_name is not None:
                username = '******'.format(username, sender.last_name)

        if not username in history:
            history[username] = {'raw_messages': []}
            
        history[username]['raw_messages'].append(message)
        
    return history
Esempio n. 11
0
 async def get_channel_user_count(self, channel):
     data = await self.client.get_entity(PeerChannel(-channel))
     try:
         users = await self.client.get_participants(data)
         return users.total
     except ChatAdminRequiredError:
         return -1
Esempio n. 12
0
def add_user_by_id(client, user_id, channel_id=DEFAULT_CHANNEL):
    try:

        # client.invoke(InviteToChannelRequest(get_input_peer(channel), [get_input_peer(user)]))

        # client.invoke(InviteToChannelRequest(
        #     # InputChannel(get_input_peer(user.chats[0]).channel_id, get_input_peer(user.chats[0]).access_hash),
        #     InputChannel(channel.id, channel.access_hash),
        #     [InputUser(get_input_peer(user.users[0]).user_id, get_input_peer(user.users[0]).access_hash)]
        # ))
        # client.invoke(InviteToChannelRequest(InputChannel(channel.id, channel.access_hash), [InputUser(get_input_peer(user.users[0]).user_id, get_input_peer(user.users[0]).access_hash)]))
        # client.invoke(InviteToChannelRequest(client.get_entity(PeerChannel(1188959006)), [user]))
        # client.invoke(InviteToChannelRequest(client.get_input_entity(PeerChannel(channel_id)), [client.get_input_entity(PeerUser(user_id=user.users[0].id))]))

        user_entity = client.get_input_entity(PeerUser(user_id))
        channel_entity = client.get_entity(PeerChannel(channel_id=int(channel_id)))
        client.invoke(InviteToChannelRequest(channel_entity, [user_entity]))

        log.warning("Added User: {} to Channel: {}".format(user_id, channel_id))
        return "User added successfully"
    except Exception as err:
        reason = err.args[1] if len(err.args) > 1 else err.message
        msg = "Add User {} attempt to channel ({}) failed [{}]".format(user_id, channel_id, reason)
        log.error(msg)
        log.error(err)
    return msg
Esempio n. 13
0
async def main():

    # Create the client and connect
    client = TelegramClient(USERNAME, API_ID, API_HASH)
    await client.start()
    print("Client Created")

    # Ensure you're authorized
    if not await client.is_user_authorized():
        await client.send_code_request(PHONE)
        try:
            await client.sign_in(PHONE, input('Enter the code: '))
        except errors.SessionPasswordNeededError:
            await client.sign_in(password=input('Password: '******'getting forwards for channel {username}\n')

        with open(os.path.join(MSG_INPUT_DIR, username), 'rb') as f:
            messages = pickle.load(f)

        forward_list = list()

        for message in messages:

            try:

                channel_id = message['fwd_from']['from_id']['channel_id']
                forward_channel = await client.get_entity(
                    PeerChannel(channel_id))
                forward_username = forward_channel.username

                print(username, forward_username)

                if forward_channel is not None:

                    forward_list.append(forward_username)

            except:

                pass

        print(f'forwards from {username}: {dict( Counter( forward_list ))}')

        user_connection_dict = dict(Counter(forward_list))

        with open(os.path.join(OUTPUT_CONNECTION_DIR, f'{username}.pkl'),
                  'wb') as f:
            pickle.dump(user_connection_dict, f)

        connection_dict[username] = user_connection_dict
Esempio n. 14
0
 def peer(self) -> Union[TypePeer, TypeInputPeer]:
     if self.peer_type == "user":
         return PeerUser(user_id=self.tgid)
     elif self.peer_type == "chat":
         return PeerChat(chat_id=self.tgid)
     elif self.peer_type == "channel":
         return PeerChannel(channel_id=self.tgid)
Esempio n. 15
0
async def normal_handler(event):
    post = WordPressPost()
    msg = event.message.to_dict()
    fwd_channel_name = (await client.get_entity(
        PeerChannel(msg['fwd_from']['channel_id']))).username
    title, content = tit_le(msg)
    post.title = '@' + fwd_channel_name + ': ' + title
    post.content = content
    post.id = wp.call(posts.NewPost(post))
    post.post_status = 'publish'
    # add image
    # set to the path to your file
    try:
        filename = (await event.message.download_media())
        data = {
            'name': 'picture.jpg',
            'type': 'image/jpeg',  # mimetype
        }
        with open(filename, 'rb') as img:
            data['bits'] = xmlrpc_client.Binary(img.read())
        response = wp.call(media.UploadFile(data))
        attachment_id = response['id']
        post.thumbnail = attachment_id
        # delete pictures
        remove(filename)
    except:
        print("with out pictures")

    wp.call(posts.EditPost(post.id, post))
Esempio n. 16
0
 def update_handler(update):
     print(type(update))
     print(update)
     print("------------------")
     if isinstance(update, UpdateNewChannelMessage):
         # message_from = client.get_entity(PeerChannel(update.message.to_id))
         # print("From: "+str(update.message.to_id))
         try:
             for peer_from in peers_from:
                 if update.message.to_id.channel_id != peer_from.channel_id:
                     continue
                 if "http" in str(update.message.message) or "https" in str(
                         update.message.message):
                     continue
                 peer_to = client.get_input_entity(
                     PeerChannel(CHANNEL_TO.id))
                 print("Message comming from channel id: " +
                       str(update.message.to_id.channel_id))
                 print("To: " + str(peer_from.channel_id))
                 print("From: " + str(peer_to.channel_id))
                 print("########\nMessage:")
                 print(str(update.message.message))
                 print("########\nMessage id:")
                 print(str(update.message.id))
                 print("########:")
                 client(
                     ForwardMessagesRequest(
                         from_peer=
                         peer_from,  # who sent these messages or what channel sent in?
                         id=[update.message.id],  # which are the messages?
                         to_peer=
                         peer_to  # who or what channel are we forwarding them to?
                     ))
         except Exception as ex:
             print("Error: " + str(ex))
    def get_entity_rows_by_id(self, entity_id, exact=True):
        if exact:
            key = "{}:entities:{}".format(self.sess_prefix, entity_id)
            s = self.redis_connection.get(key)
            if not s:
                return None
            try:
                s = self._unpack(s)
                return entity_id, s["hash"]
            except Exception as ex:
                __log__.exception(ex.args)
                return None
        else:
            ids = (
                utils.get_peer_id(PeerUser(entity_id)),
                utils.get_peer_id(PeerChat(entity_id)),
                utils.get_peer_id(PeerChannel(entity_id))
            )

            try:
                for key in self._get_entities():
                    entity = self._unpack(self.redis_connection.get(key))
                    if "id" in entity and entity["id"] in ids:
                        return entity["id"], entity["hash"]
            except Exception as ex:
                __log__.exception(ex.args)
Esempio n. 18
0
    def get_channel(self, client, channel_id):
        """

        :param TelegramClient client:
        :param int channel_id:
        :return:
        """
        return client.get_entity(PeerChannel(channel_id))
Esempio n. 19
0
def callbackUpdate(update):
    channel_name = client.get_entity(PeerChannel(update.message.to_id.channel_id)).username
    if (update.message.message ==''):
        if (channel_name == 'bigpumpsignal'): #name of the telegram channel
            str_date='output'
            client.download_media(update.message,str_date)
            print("Image downloaded!")
            client.disconnect()
Esempio n. 20
0
 async def _poll_pinned_msg(self):
     client = self._client
     logger = get_logger()
     channel_entity = await client.get_entity(PeerChannel(self._CHANNEL_ID))
     channel_info = await client(GetFullChannelRequest(channel_entity))
     pinned_msg_id = channel_info.full_chat.pinned_msg_id
     logger.debug("channel info", pinned_msg_id=pinned_msg_id)
     return pinned_msg_id
async def main(phone):
    await client.start()
    print("Client Created")
    # Check whether the authentication has been done or not?
    if await client.is_user_authorized() == False:
        await client.send_code_request(phone)
        try:
            await client.sign_in(phone, input('Enter the code: '))
        except SessionPasswordNeededError:
            await client.sign_in(password=input('Password: '******'confirmedChannelsList.txt', 'r')
    for channel in channelLis:
        if channel.isdigit():
            entity = PeerChannel(int(channel))
        else:
            entity = channel

        my_channel = await client.get_entity(entity)
        print(str(channel))
        offset_id = 0
        limit = 1
        all_messages = []
        total_messages = 0
        total_count_limit = 0
        while True:
            print("Current Offset ID is:", offset_id, "; Total Messages:",
                  total_messages)
            history = await client(
                functions.messages.SearchRequest(
                    peer=my_channel,
                    q='کرونا',
                    filter=types.InputMessagesFilterEmpty(),
                    # limited date because Covid-19 is a new problem
                    min_date=datetime(2019, 7, 1),
                    max_date=datetime(2020, 3, 30),
                    offset_id=offset_id,
                    add_offset=0,
                    limit=limit,
                    max_id=0,
                    min_id=0,
                    hash=0,
                ))
            if not history.messages:
                break
            messages = history.messages
            for message in messages:
                all_messages.append(message.to_dict())
            offset_id = messages[len(messages) - 1].id
            total_messages = len(all_messages)
            if total_count_limit != 0 and total_messages >= total_count_limit:
                break

        with open('FakesMessage.json', 'a') as outfile:
            json.dump(all_messages, outfile, cls=DateTimeEncoder)
Esempio n. 22
0
async def stats_handler(event):
    global guilds_str
    text = event.message.message
    if event.message.to_id in [PeerChannel(RESULTS_PARSE_CHANNEL_ID), PeerChannel(RESULTS_PARSE_CHANNEL_ID_DEBUG)] and \
            ('Результаты сражений:' in text or '⛺️Гильдия' in text or '⛺Гильдия' in text or "Headquarters" in text or
             "🗺State of map" in text):
        debug = event.message.to_id == PeerChannel(
            RESULTS_PARSE_CHANNEL_ID_DEBUG)
        logging.error("Received data from telegram, sending: {}".format(text))
        if '⛺️Гильдия' in text:
            guilds_str += text + "\n"
            logging.info("Adding text to guilds_str = {}".format(guilds_str))
        else:
            print("put stats in queue")
            castles_stats_queue.put({"data": text, "debug": debug})
            castles_stats_queue.put({"data": guilds_str, "debug": debug})
            guilds_str = ""
            return
async def _add_forward_header(source: 'AbstractUser', content: TextMessageEventContent,
                              fwd_from: MessageFwdHeader) -> None:
    if not content.formatted_body or content.format != Format.HTML:
        content.format = Format.HTML
        content.formatted_body = escape(content.body)
    fwd_from_html, fwd_from_text = None, None
    if fwd_from.from_id:
        user = u.User.get_by_tgid(TelegramID(fwd_from.from_id))
        if user:
            fwd_from_text = user.displayname or user.mxid
            fwd_from_html = (f"<a href='https://matrix.to/#/{user.mxid}'>"
                             f"{escape(fwd_from_text)}</a>")

        if not fwd_from_text:
            puppet = pu.Puppet.get(TelegramID(fwd_from.from_id), create=False)
            if puppet and puppet.displayname:
                fwd_from_text = puppet.displayname or puppet.mxid
                fwd_from_html = (f"<a href='https://matrix.to/#/{puppet.mxid}'>"
                                 f"{escape(fwd_from_text)}</a>")

        if not fwd_from_text:
            try:
                user = await source.client.get_entity(PeerUser(fwd_from.from_id))
                if user:
                    fwd_from_text = pu.Puppet.get_displayname(user, False)
                    fwd_from_html = f"<b>{escape(fwd_from_text)}</b>"
            except ValueError:
                fwd_from_text = fwd_from_html = "unknown user"
    elif fwd_from.channel_id:
        portal = po.Portal.get_by_tgid(TelegramID(fwd_from.channel_id))
        if portal:
            fwd_from_text = portal.title
            if portal.alias:
                fwd_from_html = (f"<a href='https://matrix.to/#/{portal.alias}'>"
                                 f"{escape(fwd_from_text)}</a>")
            else:
                fwd_from_html = f"channel <b>{escape(fwd_from_text)}</b>"
        else:
            try:
                channel = await source.client.get_entity(PeerChannel(fwd_from.channel_id))
                if channel:
                    fwd_from_text = f"channel {channel.title}"
                    fwd_from_html = f"channel <b>{escape(channel.title)}</b>"
            except ValueError:
                fwd_from_text = fwd_from_html = "unknown channel"
    elif fwd_from.from_name:
        fwd_from_text = fwd_from.from_name
        fwd_from_html = f"<b>{escape(fwd_from.from_name)}</b>"
    else:
        fwd_from_text = "unknown source"
        fwd_from_html = f"unknown source"

    content.body = "\n".join([f"> {line}" for line in content.body.split("\n")])
    content.body = f"Forwarded from {fwd_from_text}:\n{content.body}"
    content.formatted_body = (
        f"Forwarded message from {fwd_from_html}<br/>"
        f"<tg-forward><blockquote>{content.formatted_body}</blockquote></tg-forward>")
Esempio n. 24
0
 def get_entity_rows_by_id(self, id, exact=True):
     with switch_db(Entity, self.database) as _Entity:
         if exact:
             return _Entity.objects(id=id)
         else:
             ids = (utils.get_peer_id(PeerUser(id)),
                    utils.get_peer_id(PeerChat(id)),
                    utils.get_peer_id(PeerChannel(id)))
             return _Entity.objects(id__in=ids)
Esempio n. 25
0
async def get_entity(chat_id, client):
    try:
        entity = await client.get_entity(PeerUser(chat_id))
    except:
        try:
            entity = await client.get_entity(PeerChannel(chat_id))
        except:
            entity = await client.get_entity(PeerChat(chat_id))
    return entity
Esempio n. 26
0
    def get_entity_rows_by_id(self, key, exact=True):
        if exact:
            row = models.Entity.objects.filter(id=key).first()
        else:
            ids = (utils.get_peer_id(PeerUser(key)),
                   utils.get_peer_id(PeerChat(key)),
                   utils.get_peer_id(PeerChannel(key)))
            row = models.Entity.objects.filter(id__in=ids).first()

        return (row.id, row.hash) if row else None
 def get_entity_rows_by_id(self, id, exact=True):
     if exact:
         query = "SELECT * FROM c WHERE c.id = {}".format(id)
     else:
         query = "SELECT * FROM c WHERE c.id in ({}, {}, {})".format(
             utils.get_peer_id(PeerUser(id)), 
             utils.get_peer_id(PeerChat(id)),
             utils.get_peer_id(PeerChannel(id))
             )
     return self.get_entity_from_container(query)
Esempio n. 28
0
    def get_dest_channel_old(self, owner_client, client, channel_id, sources):
        """

        :param sources:
        :param TelegramClient owner_client:
        :param TelegramClient client:
        :param int channel_id:
        :return: Channel
        """
        try:
            channel = client.get_entity(PeerChannel(channel_id))
            print("get_dest_channel 1 channel:", channel)
            exit(1)
            client(ExportInviteRequest(channel))
            # try:
            #     client(EditAboutRequest(channel, self.get_about(sources)))
            # except Exception as e:
            #     print("error:", e)
            #     pass
            # todo:: check the owner is in the channel members
            # todo:: check members count
            # todo:: set list of sources to the about
            return channel
        except (ValueError, ChannelPrivateError) as e:
            owner_channel = owner_client.get_entity(PeerChannel(channel_id))
            inv = owner_client(ExportInviteRequest(owner_channel))
            client(ImportChatInviteRequest(inv.link.split('/')[-1]))
            channel = client.get_entity(PeerChannel(channel_id))
            print("e:", e)
            print("get_dest_channel 2 channel:", channel)
            exit(1)
            sender = client.get_me()
            self.set_admin(owner_client, sender, owner_channel)
            return channel
        except ChatAdminRequiredError:
            owner_channel = owner_client.get_entity(PeerChannel(channel_id))
            sender = client.get_me()
            self.set_admin(owner_client, sender, owner_channel)
            channel = client.get_entity(PeerChannel(channel_id))

            print("get_dest_channel 3 channel:", channel)
            exit(1)
            return channel
Esempio n. 29
0
async def main(phone, user_input_channel):
    '''Asynchronosly ump messages in a channel as json file

    :param phone: phone number as string
    :param user_input_channel: channel to pull data from, either given as id or name
    '''
    await client.start()
    print("Client Created")
    # Ensure you're authorized
    if await client.is_user_authorized() == False:
        await client.send_code_request(phone)
        try:
            await client.sign_in(phone, input('Enter the code: '))
        except SessionPasswordNeededError:
            await client.sign_in(password=input('Password: '******'channel_messages.json', 'w') as outfile:
        json.dump(all_messages, outfile, cls=DateTimeEncoder)
Esempio n. 30
0
    async def _build_message(self, msg, keywords, raw_text: str) -> str:
        link = ''
        if isinstance(msg.peer_id, PeerChannel):
            channel = await self._client.get_entity(
                PeerChannel(msg.peer_id.channel_id))
            link = 'https://t.me/{0}/{1}'.format(channel.username, msg.id)

        text = "keywords: " + "\n".join(
            [self.decorate_tags(keywords), raw_text, link])

        return text