Example #1
0
def main():
    j
    api_id = #####
    api_hash = '######################'

# Your Account Sid and Auth Token from twilio.com/console
    account_sid = '###############'
    auth_token = '################'
    clients = Client(account_sid, auth_token)


#telegram_Side
    client = TelegramClient('session_name', api_id, api_hash)
    client.start()
#print(client.get_me().stringify())
#updates = client(ImportChatInviteRequest('FDVzKw8BPHTp2wyhwNqT2Q'))
    siteList=["http://www.indiawaterportal.org/","https://frenli.in/"]
    for i in siteList:
        print(i)
        r = requests.head(i)
        if r.status_code == 200:
            message=i +"  returned  200"
            chat = InputPeerChat(chatID)
            client.send_message(chat, message)
            sms= clients.messages.create(to="#####",from_="##########",body="the  "+i+"   is not responding now  ")
            call = clients.calls.create(url='http://demo.twilio.com/docs/voice.xml',to='############',from_='#############')
            print(call.sid)
        else:
            chat = InputPeerChat(chatID)
            message="oops  " + i + "   not available at the moment"
            client.send_message(chat, message)
Example #2
0
async def handle_message(evt: events.NewMessage.Event) -> None:
    if '*' in allowed_user and not evt.is_private:
        return
    if not (str(evt.from_id) in allowed_user and str(evt.chat_id) in allowed_user) and '*' not in allowed_user:
        log.info(f'user {evt.from_id} or {evt.chat_id} not allowed to use this bot')
        if evt.is_private:
            await evt.delete()
        return
    if str(evt.message.message).startswith('/del') and evt.reply_to_msg_id is not None:
        if bool(int(evt.is_channel)) and bool(int(evt.is_group)):
            peer = InputPeerChat(chat_id=int(evt.chat_id))
        else:
            if bool(int(evt.is_group)):
                peer = InputPeerChat(chat_id=int(evt.chat_id))
            elif bool(int(evt.is_channel)):
                peer = InputPeerChannel(channel_id=int(evt.chat_id), access_hash=0)
            else:
                peer = InputPeerUser(user_id=int(evt.chat_id), access_hash=0)
        c = cast(Message, await client.get_messages(entity=peer, ids=evt.reply_to_msg_id))
        me = await client.get_me()
        reply_msg = cast(Message, await c.get_reply_message())
        log.debug(f'msg_from={c.from_id},evt_from={evt.from_id},c is reply={c.is_reply}'
                  f',reply_msg_from={reply_msg.from_id if reply_msg is not None else 0}')
        if c.from_id == evt.from_id or (c.from_id == me.id and c.is_reply):
            if (reply_msg is not None and reply_msg.from_id == evt.from_id) or reply_msg is None:
                await client.delete_messages(evt.input_chat, [evt.reply_to_msg_id])
        await evt.delete()
    else:
        if not evt.file:
            log.info('not evt.file')
            await evt.delete()
            return
        try:
            ret = get_media_meta(evt.media)
            if ret[0] and ret[1] and ret[2] <= max_file_size:
                middle_x = StringCoder.encode(
                    f"{evt.chat_id}|{evt.id}|{1 if evt.is_group else 0}|{1 if evt.is_channel else 0}")
                log.debug(f"{evt.chat_id}|{evt.id}|{1 if evt.is_group else 0}|{1 if evt.is_channel else 0}")
                # url = public_url / str(pack_id(evt)) / get_file_name(evt)
                url = link_prefix / middle_x / get_file_name(evt)
                await evt.reply(f'[{url}]({url})')
                log.debug(f'Link to {evt.id} in {evt.chat_id}: {url}')
            else:
                if admin_id == evt.from_id and ret[0]:
                    log.debug('admin usage')
                    middle_x = StringCoder.encode(
                        f"{evt.chat_id}|{evt.id}|{1 if evt.is_group else 0}|{1 if evt.is_channel else 0}")
                    log.debug(f"{evt.chat_id}|{evt.id}|{1 if evt.is_group else 0}|{1 if evt.is_channel else 0}")
                    # url = public_url / str(pack_id(evt)) / get_file_name(evt)
                    url = link_prefix / middle_x / get_file_name(evt)
                    await evt.reply(f'[{url}]({url})')
                    log.debug(f'Link to {evt.id} in {evt.chat_id}: {url}')
                else:
                    log.info('non-admin can not serve other than image')
                    await evt.delete()
        except Exception as exp:
            await evt.reply(str(exp))
            pass
Example #3
0
async def gbanmsg(moot):
    """ Küresel banlanan kullanıcı mesaj gelirse """
    try:
        from userbot.modules.sql_helper.gban_sql import is_gbanned
    except:
        return

    chat = await moot.get_chat()
    if (type(chat) == User):
        return 

    admin = chat.admin_rights
    creator = chat.creator

    if not admin and not creator:
        return

    gbanned = is_gbanned(str(moot.sender_id))
    if gbanned == str(moot.sender_id):
        print(moot.chat_id)
        try:
            cet = InputPeerChat(moot.chat_id)
            await moot.client.edit_permissions(cet, moot.sender_id)
        except Exception as e:
            print(e)
            return
        await moot.reply("```Sen kötü birisisin! Daha fazla seni burda tutmuyacağım. Bays!```")
Example #4
0
 def send_message(self,
                  peer,
                  message,
                  no_web_page=False,
                  PM=False,
                  access_hash=None):
     msg_id = utils.generate_random_long()
     if not (PM is True):
         self.invoke(
             SendMessageRequest(peer=InputPeerChat(peer),
                                message=message,
                                random_id=msg_id,
                                no_webpage=no_web_page))
     else:
         if access_hash:
             self.invoke(
                 SendMessageRequest(peer=InputPeerUser(peer, access_hash),
                                    message=message,
                                    random_id=msg_id,
                                    no_webpage=no_web_page))
         else:
             print(
                 "Access hash not provided. Could send message to InputPeerUser."
             )
     return msg_id
Example #5
0
 def get_input_peer(entity):
     """Gets the input peer for the given "entity" (user, chat or channel).
        Returns None if it was not found"""
     if isinstance(entity, User):
         return InputPeerUser(entity.id, entity.access_hash)
     if isinstance(entity, Chat):
         return InputPeerChat(entity.id)
     if isinstance(entity, Channel):
         return InputPeerChannel(entity.id, entity.access_hash)
Example #6
0
def populate(quantity: int) -> None:
    client = TelegramClient(api_id=tg.API_ID,
                            api_hash=tg.API_HASH,
                            session="tmp")
    client.connect()
    for i in range(quantity):
        chat_id = client(
            messages.CreateChatRequest([tg.DEAL_BOT_UID, "me"],
                                       tg.BOARD_NAME)).chats[0].id
        chat = db.Chat(invite=client(
            messages.ExportChatInviteRequest(InputPeerChat(chat_id))).link,
                       occupied=False,
                       id=chat_id * -1)
        chat.save()

        client(
            messages.EditChatDefaultBannedRightsRequest(
                InputPeerChat(chat_id), DEFAULT_RIGHTS))
        client(messages.EditChatAdminRequest(chat_id, tg.DEAL_BOT_UID, True))
        client(messages.DeleteChatUserRequest(chat_id, "me"))
Example #7
0
def unpack_id(file_id: int) -> Tuple[TypeInputPeer, int]:
    is_group = file_id & group_bit
    is_channel = file_id & channel_bit
    chat_id = file_id >> chat_id_offset & pack_bit_mask
    msg_id = file_id >> msg_id_offset & pack_bit_mask
    if is_channel:
        peer = InputPeerChannel(channel_id=chat_id, access_hash=0)
    elif is_group:
        peer = InputPeerChat(chat_id=chat_id)
    else:
        peer = InputPeerUser(user_id=chat_id, access_hash=0)
    return peer, msg_id
Example #8
0
def __load_users_from_mtproto(chat_id: int) -> [UserInfo]:
    """
    Loading from the mtproto means that telethon available on system, and we can load list of users from the channel.
    """
    if not TELETHON_ENABLED:
        return []
    users = telethon_client.iter_participants(InputPeerChat(chat_id))
    result = []
    for user in users:
        if user.bot:
            continue
        result.append(UserInfo(user.id, user.username, user.first_name, user.last_name))
    return result
Example #9
0
def start(config):
    # Get information from config file:
    session_name = config["session_name"]
    api_id = config["api_id"]
    api_hash = config["api_hash"]
    trigger_words = config["trigger_words"]
    quit_key_words = config["quit_key_words"]

    # Initialisations:
    input_channels_entities = []
    output_channel_entity = None
    connectivity = ()
    # Acquire entities:
    with TelegramClient(session_name, api_id, api_hash) as client:
        for d in client.iter_dialogs():
            if d.name in config["input_channel_names"]:
                if (config["mode"] in ['1', '2', '3']):
                    input_channels_entities.append(
                        InputChannel(d.entity.id, d.entity.access_hash))
                else:
                    input_channels_entities.append(InputPeerChat(d.entity.id))
            if d.name == config["output_channel_name"]:
                if (config["mode"] in ['1', '4']):
                    output_channel_entity = InputChannel(
                        d.entity.id, d.entity.access_hash)
                elif (config["mode"] in ['2', '5']):
                    output_channel_entity = InputPeerChat(d.entity.id)
                else:
                    output_channel_entity = InputPeerUser(
                        d.entity.id, d.entity.access_hash)

        # Do a check on entities acquired:
        if output_channel_entity is None:
            connectivity = connectivity + (0, )
            print("Requested output channel entity could not be found")
        else:
            connectivity = connectivity + (1, )
        if len(input_channels_entities) == 0:
            connectivity = connectivity + (0, )
            print("Requested input channel entity(s) cannot be found")
        else:
            connectivity = connectivity + (1, )
        if 0 in connectivity:
            print("Shutting down due to entity-check failure...")
            sys.exit(1)
        else:
            print("Entity-check successful!")
            print(
                "Listening on %d channels. Forwarding messages to %s." %
                (len(input_channels_entities), config['output_channel_name']))

        # Create events to listen to:
        # For more recipes, visit https://arabic-telethon.readthedocs.io/en/stable/

        @client.on(events.NewMessage(chats=input_channels_entities))
        async def forwarding_handler(event):
            client = event.client
            # if trigger_words in event.raw_text.lower():
            if any(word in event.raw_text.lower() for word in trigger_words):
                # await event.reply('hi!')    # extra
                await client.forward_messages(output_channel_entity,
                                              event.message)

        @client.on(
            events.NewMessage(chats=output_channel_entity, outgoing=True))
        async def control_handler(event):
            # if quit_key_words in event.raw_text.lower():
            if any(word in event.raw_text.lower() for word in quit_key_words):
                await client.disconnect()

        client.run_until_disconnected()
Example #10
0
try:
    all_participants = client.get_participants(target_group_scrapper, aggressive=True)
except: 
    print("Unable to fetch participants of", target_group_scrapper)
    exit()

if len(all_participants) == 0:
    print("No user found in", target_group_scrapper + '.', "Please check the group.")
    exit()

try:
    target_group_entity_adder = InputPeerChannel(target_group_adder.id, target_group_adder.access_hash)
    isChannel = True
except:
    target_group_entity_adder = InputPeerChat(target_group_adder.id)
    isChannel = False

n = 0
user_added_count = 0



for i in range(start_index,len(all_participants)):
    user = all_participants[i]
    n += 1
    if n % 50 == 0:
        time.sleep(900)

    try:
        print("Adding {}".format(user.id))
Example #11
0
    def xmpp_update_handler(self, obj):
        """
        Main function: Telegram update handler.
        :param media:
        :return:
        """
        # print("We have received update for <%s>" % self.jid)
        # print(obj)

        # we have received some updates, so we're logined and can get <me> object and start mtd / upd threads #
        if not self.me:
            me = self.get_me()
            self.me = InputPeerUser(me.id, me.access_hash)
            self._media_thread.start()
            self._status_update_thread.start()

        nl = '\n'

        try:

            # message from normal chat #
            if type(obj) in [UpdateShortMessage] and not obj.out:

                fwd_from = self._process_forward_msg(
                    obj) if obj.fwd_from else ''  # process forward messages
                self.gate_send_message(mfrom='u' + str(obj.user_id),
                                       mbody='[MSG {}] {}{}'.format(
                                           obj.id, fwd_from, obj.message))
                usr = self._get_user_information(
                    obj.user_id)  # get peer information
                self.invoke(
                    ReadHistoryRequest(InputPeerUser(usr.id, usr.access_hash),
                                       obj.id))  # delivery report

            # message from normal group #
            if type(obj) in [UpdateShortChatMessage] and not obj.out:
                fwd_from = self._process_forward_msg(
                    obj) if obj.fwd_from else ''  # process forward messages
                usr = self._get_user_information(obj.from_id)
                nickname = display_tg_name(usr)

                # send message
                self.gate_send_message(mfrom='g' + str(obj.chat_id),
                                       mbody='[MSG {}] [User: {}] {}{}'.format(
                                           obj.id, nickname, fwd_from,
                                           obj.message))
                self.invoke(
                    ReadHistoryRequest(InputPeerChat(obj.chat_id), obj.id))

            # message from supergroup or media message #
            if type(obj) in [
                    UpdateNewMessage, UpdateNewChannelMessage,
                    UpdateEditMessage, UpdateEditChannelMessage
            ] and not obj.message.out:

                cid = None
                msg = ''
                fwd_from = ''
                mid = obj.message.id

                # detect message type
                is_user = type(obj.message.to_id) is PeerUser
                is_group = type(obj.message.to_id) is PeerChat
                is_supergroup = type(obj.message.to_id) is PeerChannel

                # detect from id
                if is_user:
                    cid = obj.message.from_id
                    user = self._get_user_information(cid)
                    peer = InputPeerUser(user.id, user.access_hash)
                    prefix = 'u'
                    prefix = 'b' if user.bot else prefix
                elif is_group:
                    cid = obj.message.to_id.chat_id
                    peer = InputPeerChat(cid)
                    prefix = 'g'
                elif is_supergroup:
                    cid = obj.message.to_id.channel_id
                    peer = InputPeerChannel(
                        cid, self.xmpp_gate.tg_dialogs[self.jid]['supergroups']
                        [cid].access_hash) if cid in self.xmpp_gate.tg_dialogs[
                            self.jid]['supergroups'] else None
                    prefix = 's'

                # our message #
                if type(obj.message) == MessageService:
                    obj.message.fwd_from, obj.message.post, obj.message.edit_date, obj.message.media = None, None, None, None
                    msg = self._process_info_msg(obj.message, peer)
                elif type(obj.message) == Message:
                    msg = obj.message.message

                # is forwarded?
                if obj.message.fwd_from:
                    fwd_from = self._process_forward_msg(obj.message)

                # maybe its channel? #
                if obj.message.post:
                    prefix = 'c'

                # get sender information from chat info #
                if not is_user and not obj.message.post:
                    usr = self._get_user_information(obj.message.from_id)
                    nickname = display_tg_name(usr)
                    msg = '[User: {}] {}'.format(nickname, msg)

                # message media #
                if obj.message.media:
                    msg = '{} {}'.format(
                        msg, self._process_media_msg(obj.message.media))

                # edited #
                if obj.message.edit_date:
                    msg = '[Edited] {}'.format(msg)

                # send message #
                self.gate_send_message(prefix + str(cid),
                                       mbody='[MSG {}] {}{}'.format(
                                           mid, fwd_from, msg))

                # delivery report
                if is_supergroup:
                    self.invoke(ReadHistoryChannel(peer, mid))
                else:
                    self.invoke(ReadHistoryRequest(peer, mid))

            # Status Updates #
            if type(obj) is UpdateUserStatus:
                # process status update #
                if type(obj.status) is UserStatusOnline:
                    self._status_updates[str(obj.user_id)] = {
                        'status': None,
                        'message': 'Online'
                    }
                elif type(obj.status) is UserStatusOffline:
                    status = 'away' if datetime.datetime.utcnow(
                    ) - obj.status.was_online < datetime.timedelta(
                        hours=self.xmpp_gate.accounts[
                            self.jid]['status_xa_interval']) else 'xa'
                    self._status_updates[str(obj.user_id)] = {
                        'status':
                        status,
                        'message':
                        localtime(obj.status.was_online).strftime(
                            'Last seen at %H:%M %d/%m/%Y')
                    }
                elif type(obj.status) is UserStatusRecently:
                    self._status_updates[str(obj.user_id)] = {
                        'status': 'dnd',
                        'message': 'Last seen recently'
                    }
                else:
                    pass

        except Exception:
            print('Exception occurs!')
            print(traceback.format_exc())
Example #12
0
    def message(self, iq):
        """
        Обработчик входящих сообщений из XMPP
        :param iq:
        :return:
        """
        jid = iq['from'].bare

        if iq['to'] == self.config['jid'] and iq[
                'type'] == 'chat':  # Пишут транспорту
            if iq['body'].startswith('!'):
                self.process_command(iq)
            else:
                self.gate_reply_message(
                    iq, 'Only commands accepted. Try !help for more info.')
        else:  # Пишут в Telegram
            if jid in self.tg_connections and self.tg_connections[
                    jid].is_user_authorized():
                if iq['body'].startswith('!'):  # Команда из чата
                    print('command received')
                    if iq['to'].bare.startswith('u'):
                        self.process_chat_user_command(iq)
                    elif iq['to'].bare.startswith(
                            'g') or iq['to'].bare.startswith('s'):
                        self.process_chat_group_command(iq)
                    else:
                        self.gate_reply_message(iq, 'Error.')
                else:  # Обычное сообщение
                    print('sent message')
                    tg_id = int(iq['to'].node[1:])
                    tg_peer = None
                    msg = iq['body']
                    reply_mid = None

                    if msg.startswith('>'):  # Проверка на цитирование
                        msg_lines = msg.split('\n')
                        matched = re.match(r'>[ ]*(?P<mid>[\d]+)[ ]*',
                                           msg_lines[0]).groupdict()

                        if 'mid' in matched:  # Если нашли ID сообщения, то указываем ответ
                            reply_mid = int(matched['mid'])
                            msg = '\n'.join(msg_lines[1:])

                    if iq['to'].bare.startswith('u'):  # Обычный пользователь
                        tg_peer = InputPeerUser(
                            tg_id,
                            self.tg_dialogs[jid]['users'][tg_id].access_hash)
                    elif iq['to'].bare.startswith('g'):  # Обычная группа
                        tg_peer = InputPeerChat(tg_id)
                    elif iq['to'].bare.startswith('s') or iq[
                            'to'].bare.startswith('c'):  # Супергруппа
                        tg_peer = InputPeerChannel(
                            tg_id, self.tg_dialogs[jid]['supergroups']
                            [tg_id].access_hash)

                    if tg_peer:
                        # Отправляем сообщение и получаем новый апдейт
                        result = self.tg_connections[jid].invoke(
                            SendMessageRequest(tg_peer,
                                               msg,
                                               generate_random_long(),
                                               reply_to_msg_id=reply_mid))
                        msg_id = None

                        # Ищем ID отправленного сообщения
                        if type(result) is Updates:  # Супегруппа / канал
                            for upd in result.updates:
                                if type(upd) is UpdateMessageID:
                                    msg_id = upd.id
                        elif type(result
                                  ) is UpdateShortSentMessage:  # ЛС / Группа
                            msg_id = result.id
Example #13
0
    def xmpp_update_handler(self, obj):
        print('new update for ' + self.jid)
        print(type(obj), obj.__dict__)
        '''
        Боты
        Сделать запоминание ростера в бд
        Сделать лучше хендлинг ошибок
        Доделать все типы информационных сообщений
        Сделать джойны по линкам в чаты/каналы
        Сделать поиск и добавление пользователей
        Сделать листание истории
        Сделать отправку всех непрочтенных сообщений при входе
        '''

        # Здесь будет очень длинный пиздец ^__^

        nl = '\n' if self.user_options['nl_after_info'] else ''

        try:
            if type(
                    obj
            ) is Updates:  # Какой-то общий тип обновления (всегда большое со списками)
                print('Updates')

                # Делаем разбор пользователей/чатов, которые учавствуют в апдейте
                updates_users = {usr.id: usr for usr in obj.users}
                updates_groups = {}
                updates_channels = {}
                updates_supergroups = {}
                updates_type_channels = {}  # Супегруппы и каналы вместе

                for chat in obj.chats:
                    if type(chat) is Chat:  # Обычная группа
                        updates_groups[chat.id] = chat
                    elif type(chat) is Channel:
                        if chat.broadcast:  # Канал
                            updates_channels[chat.id] = chat
                        else:  # Супегруппа
                            updates_supergroups[chat.id] = chat
                        updates_type_channels[chat.id] = chat

                # -------------------------------------------------------------------------------------------

                for update in obj.updates:  # Апдейт содержит список с апдейтами
                    # Новое сообщение или отредактированное в супегруппе или канале
                    # А так же отредактированные и новые сообщения с медиа в ЛС и группах
                    if type(update) in [
                            UpdateNewChannelMessage, UpdateEditChannelMessage,
                            UpdateNewMessage, UpdateEditMessage
                    ]:
                        if update.message.out:  # Игнорируем исходящее сообщение
                            return

                        uid = update.message.from_id  # Будет None, если канал, а так же post=True
                        mid = update.message.id
                        cid = None
                        is_post = update.message.post
                        usr = updates_users[uid] if uid else None
                        nickname = display_tg_name(
                            usr.first_name, usr.last_name) if usr else None

                        from_type = 'c' if is_post else 's'
                        msg = ''
                        alt_msg = None
                        edited = ''
                        fwd_reply = ''
                        orig_msg = None

                        is_user = type(update.message.to_id) is PeerUser
                        is_group = type(update.message.to_id) is PeerChat
                        is_supergroup = type(
                            update.message.to_id) is PeerChannel

                        if is_user:
                            cid = update.message.from_id
                        elif is_group:
                            cid = update.message.to_id.chat_id
                        elif is_supergroup:
                            cid = update.message.to_id.channel_id

                        if type(
                                update.message
                        ) is MessageService:  # Сервисные уведомления в чате
                            print('messageService detected')
                            with open(
                                    '/home/sofia/tgdebug/' + str(mid) + '.txt',
                                    'w') as f:
                                f.write(var_dump(obj))
                            ##################################################################
                            alt_msg = self._process_info_msg(
                                update.message, obj.users)
                        else:  # Обычное сообщение в чате
                            msg = update.message.message

                            if update.message.media:
                                print('media detected')
                                #######################################################
                                msg = '[{}] {}'.format(
                                    update.message.media.__class__.__name__,
                                    '{} {}'.format(
                                        self._process_media_msg(
                                            update.message.media), msg))

                            if update.message.reply_to_msg_id:
                                fwd_reply = '|Reply to MID: {}'.format(
                                    update.message.reply_to_msg_id)
                                reply_mid = update.message.reply_to_msg_id
                                orig_msg = self.get_cached_message(
                                    cid, reply_mid, is_user, is_group,
                                    is_supergroup)

                            if update.message.fwd_from:  # Пересланное сообщение
                                fwd_reply = self._process_forward_msg(
                                    update.message, updates_users,
                                    updates_channels)

                        if update.message.edit_date:  # Если новое - отмечаем прочитанным
                            edited = '|Edited'

                        if alt_msg is None:
                            if is_post or type(
                                    update.message.to_id) is PeerUser:
                                header = '[MID:{}{}{}] '.format(
                                    mid, fwd_reply, edited)
                            else:
                                header = '[User: {}|UID:{}|MID:{}{}{}] {}'\
                                    .format(nickname, uid, mid, fwd_reply, edited, nl)

                            alt_msg = '{}{}'.format(header, msg)

                            self.set_cached_message(  # Кэшируем без цитаты
                                cid,
                                mid,
                                alt_msg,
                                user=is_user,
                                group=is_group,
                                supergroup=is_supergroup)

                            if orig_msg is not None:  # Перестраиваем сообщение уже с цитатой
                                alt_msg = '{}> {}\n{}'.format(
                                    header, orig_msg.replace('\n', '\n> '),
                                    msg)

                        if is_user:
                            self.gate_send_message(mfrom='u' + str(cid),
                                                   mbody=alt_msg)

                            if False:  # Зарезервируем рекурсивные цитаты под опцию
                                self.set_cached_message(cid,
                                                        mid,
                                                        alt_msg,
                                                        user=True)

                            if not update.message.edit_date:
                                self.invoke(
                                    ReadHistoryRequest(  # Отмечаем прочитанным
                                        InputPeerUser(usr.id, usr.access_hash),
                                        mid))
                        elif is_group:
                            self.gate_send_message(
                                mfrom='g' + str(update.message.to_id.chat_id),
                                mbody=alt_msg)

                            if False:  # ...
                                self.set_cached_message(cid,
                                                        mid,
                                                        alt_msg,
                                                        group=True)

                            if not update.message.edit_date:
                                self.invoke(
                                    ReadHistoryRequest(InputPeerChat(cid),
                                                       mid))
                        elif is_supergroup:
                            self.gate_send_message(mfrom=from_type + str(cid),
                                                   mbody=alt_msg)

                            if False:  # ...
                                self.set_cached_message(cid,
                                                        mid,
                                                        alt_msg,
                                                        supergroup=True)

                            if not update.message.edit_date:
                                access_hash = updates_type_channels[
                                    cid].access_hash
                                self.invoke(
                                    ReadHistoryChannel(
                                        InputPeerChannel(cid, access_hash),
                                        mid))
                    elif type(
                            update
                    ) is UpdateDeleteChannelMessages:  # Удаленные сообщения в супергруппе/канале
                        channel_id = update.channel_id
                        channel_type = 's'

                        if self.xmpp_gate.tg_dialogs[self.jid]['supergroups'][
                                channel_id].broadcast:  # А может канал?
                            channel_type = 'c'

                        self.gate_send_message(
                            mfrom=channel_type + str(channel_id),
                            mbody='[Deleted messages IDs: {}]'.format(
                                ', '.join(
                                    [str(mid) for mid in update.messages])))
                    elif type(update) is UpdateDeleteMessages:
                        # Этот ивент обновления присылается при удалении сообщения в личном сообщении или группе.
                        # Только id сообщения. Нет информации об диалоге/пользователе/группе.
                        pass

                if type(obj.updates) is list and type(
                        obj.updates[0]) is UpdateChannelTooLong:
                    print('too long')

            # ***^__^***^__^***^__^***^__^***^__^***^__^***^__^***^__^***^__^***^__^***^__^***^__^***^__^***^__^***

            if type(
                    obj
            ) is UpdateShort:  # Тоже какой-то общий тип обновления (всегда маленькое)
                if type(
                        obj.update
                ) is UpdateUserStatus:  # Обновление статуса пользователя в сети Tg
                    print('UpdateUserStatus')

                    if type(obj.update.status) is UserStatusOnline:
                        self.xmpp_gate.send_presence(
                            pto=self.jid,
                            pfrom='u' + str(obj.update.user_id) + '@' +
                            self.xmpp_gate.config['jid'])
                    elif type(obj.update.status) is UserStatusOffline:
                        self.xmpp_gate.send_presence(
                            pto=self.jid,
                            pfrom='u' + str(obj.update.user_id) + '@' +
                            self.xmpp_gate.config['jid'],
                            ptype='xa',
                            pstatus=obj.update.status.was_online.strftime(
                                'Last seen at %H:%M %d/%m/%Y'))
                    elif type(obj.update.status) is UserStatusRecently:
                        self.xmpp_gate.send_presence(
                            pto=self.jid,
                            pfrom='u' + str(obj.update.user_id) + '@' +
                            self.xmpp_gate.config['jid'],
                            pstatus='Last seen recently')
                    else:
                        print(type(obj.update.status))
                        print(obj.update.status.__dict__)

                elif type(
                        obj.update
                ) is UpdateDeleteChannelMessages:  # Удаленное сообщение в супергруппе
                    if obj.update.pts > self._del_pts:  # Фильтруем дубли обновлений
                        channel_id = obj.update.channel_id
                        channel_type = 's'

                        if self.xmpp_gate.tg_dialogs[
                                self.jid]['supergroups'][channel_id].broadcast:
                            channel_type = 'c'

                        msg = '[Deleted messages IDs: {}]'.format(', '.join(
                            [str(mid) for mid in obj.update.messages]))

                        self.gate_send_message(mfrom=channel_type +
                                               str(channel_id),
                                               mbody=msg)

                    self._del_pts = obj.update.pts

            # ***^__^***^__^***^__^***^__^***^__^***^__^***^__^***^__^***^__^***^__^***^__^***^__^***^__^***^__^***

            # Входящее сообщение в ЛС или группу (без медиа вложений)
            if type(obj) in [UpdateShortMessage, UpdateShortChatMessage
                             ] and not obj.out:
                fwd_reply = ''
                nickname = ''

                if type(obj) is UpdateShortChatMessage:
                    # Так как в апдейте есть только ID пользователя, то запрашиваем с сервера информацию о группе
                    if obj.from_id not in self._groups_users:
                        chat_info = self.invoke(GetFullChatRequest(
                            obj.chat_id))

                        for usr in chat_info.users:
                            self._groups_users[usr.id] = usr

                    nickname = display_tg_name(
                        self._groups_users[obj.from_id].first_name,
                        self._groups_users[obj.from_id].last_name)

                if obj.reply_to_msg_id:
                    fwd_reply = '|Reply to MID: {}'.format(obj.reply_to_msg_id)

                if obj.fwd_from:
                    full_update = self.invoke(
                        GetDifferenceRequest(obj.pts - 1, obj.date, -1, 1))

                    fwd_reply = self._process_forward_msg(
                        full_update.new_messages[0],
                        {usr.id: usr
                         for usr in full_update.users}, {})

                if type(obj) is UpdateShortMessage:
                    self.gate_send_message(mfrom='u' + str(obj.user_id),
                                           mbody='[MID:{}{}] {}'.format(
                                               obj.id, fwd_reply, obj.message))

                    if obj.user_id in self.xmpp_gate.tg_dialogs[
                            self.jid]['users']:
                        usr = self.xmpp_gate.tg_dialogs[self.jid]['users'][
                            obj.user_id]
                        self.invoke(
                            ReadHistoryRequest(  # Отмечаем прочитанным
                                InputPeerUser(usr.id, usr.access_hash),
                                obj.id))
                elif type(obj) is UpdateShortChatMessage:
                    self.gate_send_message(
                        mfrom='g' + str(obj.chat_id),
                        mbody='[User: {}|UID:{}|MID:{}{}] {}'.format(
                            nickname, obj.from_id, obj.id, fwd_reply,
                            obj.message))

                    self.invoke(
                        ReadHistoryRequest(InputPeerChat(obj.chat_id), obj.id))

        except Exception:
            print('Exception occurs!')
            print(traceback.format_exc())

        print(' ')
Example #14
0
def add_users_to_group(input_file, target_group, add_mode = 0, start_index = 0):
    global client

    mode = 0
    error_count = 0
    user_add_count = 0

    mode_set = False
    isChannel = False

    # validate mode when in auto-add mode
    if add_mode in [1, 2]:
        mode = int(add_mode)
        mode_set = True
    elif add_mode != 0:
        logger.error('Invalid Add Mode')

    # convert target_group to InputPeer
    if isinstance(target_group, Chat):
        target_group_entity = InputPeerChat(target_group.id)
        isChannel = False
    elif isinstance(target_group, Channel):
        target_group_entity = InputPeerChannel(target_group.id, target_group.access_hash)
        isChannel = True
    else:
        logger.error("%s is not a valid InputPeer", target_group.__class__.__name__)
        exit(5)

    while not mode_set:
        try:
            print('Add By:\n1. username\n2. user ID ( requires access hash to be in CSV )\n3. Auto-detect from CSV header')
            mode = int(input('How do you want to add users? '))
            mode_set = True
        except:
            logger.error('ValueError: invalid literal \n')
            continue

        # auto-detect mode from CSV header
        if mode == 3:
            csv_header_fieldnames = csv.DictReader(
                                        open(input_file, encoding='UTF-8'),
                                        delimiter=",",
                                        lineterminator="\n",
                                        skipinitialspace=True
                                    ).fieldnames
            logger.debug(csv_header_fieldnames)
            if len(csv_header_fieldnames) > 1:
                logger.error('CSV file has more than one column. Cannot auto-detect add mode. \n')
                mode_set = False
                continue
            elif csv_header_fieldnames[0] == 'username':
                mode = 1
            elif csv_header_fieldnames[0] == 'user id':
                mode = 2
            else:
                logger.error('Could not detect add mode from CSV file. Try again. \n')
                mode_set = False
                continue

        if mode not in [1, 2]:
            logger.error('Invalid Mode Selected. Try Again. \n')
            mode_set = False

    with open(input_file, encoding='UTF-8') as f:
        # convert csv dict into a list
        # to index it by an integer
        # to be able to resume from arbitrary points
        # https://stackoverflow.com/a/55790863
        users = list(csv.DictReader(f, delimiter=",", lineterminator="\n"))
        for i in range(start_index, len(users)):
            user = users[i]

            logger.debug('### ===== BEGIN USER ===== ###')
            logger.debug(user)

            if mode == 1:
                if user['username'] == "":
                    logger.warning("%s doesn't have a username", user)
                    continue
                user_to_add = client.get_input_entity(user['username'])
                logger.debug("Adding @%s", user['username'])
            elif mode == 2:
                try:
                    user_to_add = client.get_input_entity(int(user['user id']))
                except:
                    logger.error("User ID %s is invalid", user['user id'])
            else:
                sys.exit("Invalid Mode Selected. Please Try Again.")
            logger.debug(user_to_add)

            try:
                if isChannel:
                    updates = client(InviteToChannelRequest(target_group_entity, [user_to_add]))
                    logger.debug(updates.stringify())
                else:
                    updates = client(AddChatUserRequest(target_group_entity.chat_id, user_to_add, fwd_limit=1000000000))
                    logger.debug(updates.stringify())
                user_add_count += 1
                wait_time = random.randrange(60, 300)
                logger.debug("Waiting for %s seconds", wait_time)
                time.sleep(wait_time)
            except (
                    InputUserDeactivatedError,
                    UserNotMutualContactError,
                    UserPrivacyRestrictedError
                   ) as e:
                message = re.search('(?<=user).*', str(e)).group(0)
                logger.error("%s: %s%s", e.__class__.__name__, user_to_add, message)
            except PeerFloodError as e:
                logger.error("%s: %s", e.__class__.__name__, e)
                logger.info("to continue from the last position, run:\n\tpython3 %s %s %s %s %s",
                    sys.argv[0],
                    input_file,
                    target_group.id,
                    mode,
                    start_index + user_add_count
                )
                exit(6)
            except Exception as e:
                logger.exception(e.__class__.__name__)
                error_count += 1
                if error_count > 10:
                    sys.exit('too many errors')
                continue

            logger.debug('### ===== END USER ===== ### \n')
Example #15
0
    for group in groups:
        print(str(i) + '- ' + group.title)
        i += 1

    g_index = input("Enter a Number: ")

target_group = groups[int(g_index) - 1]

isChannel = None

try:
    target_group_entity = InputPeerChannel(target_group.id,
                                           target_group.access_hash)
    isChannel = True
except:
    target_group_entity = InputPeerChat(target_group.id)
    isChannel = False

if not continue_script:
    mode = int(input("Enter 1 to add by username or 2 to add by ID: "))

if (mode not in [1, 2]):
    sys.exit("Invalid Mode Selected. Please Try Again.")

n = 0
user_added_count = 0

for i in range(start_index, len(users)):
    user = users[i]
    n += 1
    if n % 50 == 0:
Example #16
0
]

result = client(
    GetDialogsRequest(offset_date=None,
                      offset_id=0,
                      offset_peer=InputPeerEmpty(),
                      limit=200,
                      hash=0))

client.send_message('me', 'Hello, myself!')

for chat in result.chats:
    if target_id == int(chat.id):
        print('found target_id')
        if type(chat) == Chat:
            target_entity = InputPeerChat(chat.id)
        if type(chat) == Channel:
            target_entity = InputPeerChannel(chat.id, chat.access_hash)

for chat in result.chats:
    if type(chat) == Chat:
        chat_groups.append(chat)
    elif type(chat) == Channel:
        channel_groups.append(chat)

print('\nChats')
for chat in chat_groups:
    print(chat)

print("\nChannel")
for channel in channel_groups:
Example #17
0
    def tg_process_dialogs(self, jid):
        # Инициализируем словари для диалогов
        self.tg_dialogs[jid] = dict()
        self.tg_dialogs[jid]['raw'] = list()
        self.tg_dialogs[jid]['users'] = dict()
        self.tg_dialogs[jid]['groups'] = dict()
        self.tg_dialogs[jid]['supergroups'] = dict()

        # Оффсеты для получения диалогов
        last_peer = InputPeerEmpty()
        last_msg_id = 0
        last_date = None

        while True:  # В цикле по кускам получаем все диалоги
            dlgs = self.tg_connections[jid].invoke(
                GetDialogsRequest(offset_date=last_date,
                                  offset_id=last_msg_id,
                                  offset_peer=last_peer,
                                  limit=100))

            self.tg_dialogs[jid]['raw'].append(dlgs)

            for usr in dlgs.users:
                self.tg_dialogs[jid]['users'][usr.id] = usr
            for cht in dlgs.chats:
                if type(cht) in [Chat, ChatForbidden]:  # Старая группа
                    self.tg_dialogs[jid]['groups'][cht.id] = cht
                elif type(cht) in [Channel, ChannelForbidden]:  # Супергруппа
                    self.tg_dialogs[jid]['supergroups'][cht.id] = cht

            for dlg in dlgs.dialogs:
                if type(dlg.peer) is PeerUser:
                    usr = self.tg_dialogs[jid]['users'][dlg.peer.user_id]
                    vcard = self.plugin['xep_0054'].make_vcard()
                    u_jid = 'u' + str(usr.id) + '@' + self.boundjid.bare

                    if usr.deleted:
                        vcard['FN'] = 'Deleted account'
                        vcard[
                            'DESC'] = 'This user no longer exists in Telegram'
                    else:
                        vcard['FN'] = display_tg_name(usr.first_name,
                                                      usr.last_name)
                        if usr.first_name:
                            vcard['N']['GIVEN'] = usr.first_name
                        if usr.last_name:
                            vcard['N']['FAMILY'] = usr.last_name
                        if usr.username:
                            vcard[
                                'DESC'] = 'Telegram Username: @' + usr.username

                            if usr.bot:
                                vcard['DESC'] += ' [Bot]'

                        vcard['NICKNAME'] = vcard['FN']

                    vcard['JABBERID'] = u_jid
                    self.plugin['xep_0054'].publish_vcard(jid=u_jid,
                                                          vcard=vcard)
                    self.plugin['xep_0172'].publish_nick(nick=vcard['FN'],
                                                         ifrom=u_jid)

                    self.send_presence(pto=jid, pfrom=u_jid, ptype='subscribe')

                    if usr.bot:
                        self.send_presence(pto=jid, pfrom=u_jid, pstatus='Bot')
                    else:
                        if type(usr.status) is UserStatusOnline:
                            self.send_presence(pto=jid, pfrom=u_jid)
                        elif type(usr.status) is UserStatusRecently:
                            self.send_presence(pto=jid,
                                               pfrom=u_jid,
                                               pshow='away',
                                               pstatus='Last seen recently')
                        elif type(usr.status) is UserStatusOffline:
                            self.send_presence(
                                pto=jid,
                                pfrom=u_jid,
                                ptype='xa',
                                pstatus=usr.status.was_online.strftime(
                                    'Last seen at %H:%M %d/%m/%Y'))
                        else:
                            self.send_presence(
                                pto=jid,
                                pfrom=u_jid,
                                ptype='unavailable',
                                pstatus='Last seen a long time ago')

                if type(dlg.peer) in [PeerChat, PeerChannel]:
                    g_type = ''
                    cht = None

                    if type(dlg.peer) is PeerChat:  # Старая группа
                        cht = self.tg_dialogs[jid]['groups'][dlg.peer.chat_id]
                        c_jid = 'g' + str(cht.id) + '@' + self.boundjid.bare
                        g_type = 'G'
                    elif type(dlg.peer) is PeerChannel:  # Супергруппа
                        cht = self.tg_dialogs[jid]['supergroups'][
                            dlg.peer.channel_id]

                        if cht.broadcast:
                            g_type = 'C'
                            c_jid = 'c' + str(
                                cht.id) + '@' + self.boundjid.bare
                        else:
                            g_type = 'SG'
                            c_jid = 's' + str(
                                cht.id) + '@' + self.boundjid.bare

                    vcard = self.plugin['xep_0054'].make_vcard()
                    vcard['FN'] = '[{}] {}'.format(g_type, cht.title)
                    vcard['NICKNAME'] = vcard['FN']
                    vcard['JABBERID'] = c_jid
                    self.plugin['xep_0054'].publish_vcard(jid=c_jid,
                                                          vcard=vcard)
                    self.plugin['xep_0172'].publish_nick(nick=vcard['FN'],
                                                         ifrom=c_jid)

                    self.send_presence(pto=jid, pfrom=c_jid, ptype='subscribe')
                    self.send_presence(pto=jid, pfrom=c_jid)

            if len(dlgs.dialogs
                   ) == 0:  # Если все диалоги получены - прерываем цикл
                break
            else:  # Иначе строим оффсеты
                last_msg_id = dlgs.dialogs[
                    -1].top_message  # Нужен последний id сообщения. Наркоманы.
                last_peer = dlgs.dialogs[-1].peer

                last_date = next(
                    msg for msg in dlgs.messages  # Ищем дату среди сообщений
                    if type(msg.to_id) is type(last_peer)
                    and msg.id == last_msg_id).date

                if type(last_peer) is PeerUser:  # Пользователь
                    access_hash = self.tg_dialogs[jid]['users'][
                        last_peer.user_id].access_hash
                    last_peer = InputPeerUser(last_peer.user_id, access_hash)
                elif type(last_peer) in [Chat, ChatForbidden]:  # Группа
                    last_peer = InputPeerChat(last_peer.chat_id)
                elif type(last_peer) in [Channel,
                                         ChannelForbidden]:  # Супергруппа
                    access_hash = self.tg_dialogs[jid]['supergroups'][
                        last_peer.channel_id].access_hash
                    last_peer = InputPeerChannel(last_peer.channel_id,
                                                 access_hash)