Пример #1
0
                                            """)

try:
    config = configparser.ConfigParser()
    config.read("config.ini")

    channel = config['Telegram']['from_channel']
    phone = utils.parse_phone(config['Telegram']['main_phone'])
    api = read_csv('api.csv')[0]

    client = TelegramClient(f"sessions/{phone}", *api)
    client.start(phone)

    rows = [['ID', 'Name', 'Username', 'Phone']]

    print("Getting participants...")

    for participant in client.iter_participants(channel, aggressive=True):
        print(f"Got {len(rows)}", end='\r')
        rows.append([
            participant.id,
            utils.get_display_name(participant), participant.username,
            participant.phone
        ])

    print("\nWriting output")
    write_csv('users.csv', rows)
    print("Done!")

finally:
    input()
Пример #2
0
        LOGS.info(
            "Support for inline is disabled on your bot. "
            "To enable it, define a bot token and enable inline mode on your bot. "
            "If you think there is a problem other than this, contact us.")
    try:
        bot.loop.run_until_complete(check_botlog_chatid())
    except BaseException:
        LOGS.info(
            "BOTLOG_CHATID environment variable isn't a "
            "valid entity. Check your environment variables/config.env file."
        )
        sys.exit(1)

    if BOTLOG:
        members = []
        for user in bot.iter_participants(BOTLOG_CHATID):
            members.append(user.id)

        helper_id = tgbot.get_me()
        helper_id = helper_id.id

        if helper_id not in members:
            PRINT_LOGS = lambda x: tgbot.send_message(uid, x)
        else:
            PRINT_LOGS = lambda x: tgbot.send_message(BOTLOG_CHATID, x)

# Global Variables
COUNT_MSG = 0
USERS = {}
COUNT_PM = {}
LASTMSG = {}
Пример #3
0
from telethon.sessions import StringSession
from telethon import functions, types
from telethon.sync import TelegramClient
from telethon import functions, types

api_id = os.environ.get("API_ID")
api_hash = os.environ.get("API_HASH")

string_session = os.environ.get("STRING_SESSION")
chan = os.environ.get("GROUP1")
chann = os.environ.get("GROUP2")
client = TelegramClient(StringSession(string_session), api_id, api_hash)
client.start()
usersscraped = list()

for user in client.iter_participants(chan):
    try:
        userinfo = client(functions.users.GetFullUserRequest(id=user.username))
        try:

            result = client(
                functions.contacts.AddContactRequest(
                    id=user.username,
                    first_name=userinfo.user.first_name,
                    last_name=userinfo.user.last_name,
                    phone="+91 ",
                    add_phone_privacy_exception=False))
            try:
                scrap = client(
                    functions.channels.InviteToChannelRequest(
                        channel=chann, users=[user.username]))
Пример #4
0
class TelegramClientWrapper:
    def __init__(self, session, api_id, api_hash):
        self.client = TelegramClient(session, api_id, api_hash)

    def connect(self):
        res = None
        try:
            res = self.client.connect()
        except sqlite3.OperationalError as e:
            try:
                self._manage_sqlite3_errors(e)
            except TwitterstormError as ee:
                logging.critical(ee)
        except Exception as e:
            logging.exception(e)
        return res

    def disconnect(self):
        res = None
        try:
            res = self.client.disconnect()
        except Exception as e:
            logging.critical(e)
        return res

    async def get_messages(self, tg_channel, nb_msgs, **kwargs):
        if tg_channel is None:
            logging.error(
                "On essaie d'obtenir les messages d'un channel qui n'a pas été trouvé"
            )
            return []

        try:
            res = await self.client.get_messages(tg_channel, nb_msgs, **kwargs)
        except Exception as e:
            logging.exception(e)
            return []

        res = [TelegramMessage.from_telethon_object(m) for m in res]
        return res

    async def get_input_entity(self, peer) -> TelegramPersonnalChannel:
        tg_channel = None
        try:
            tg_channel = await self.client.get_input_entity(peer)
        except Exception:
            logging.exception("Channel non trouvé pour l'argument 'peer' = " +
                              str(peer))
            raise KeyboardInterrupt(
                "Si tu tombes là une fois, c'est qu'il est pertinent de laisser la suite du code dans "
                "self._get_1to1_channel. Sinon, non ;)"
            )  # todo_cr à retirer à terme

        return TelegramPersonnalChannel.from_telethon_object(tg_channel)

    async def get_entity(self, entity) -> TelegramChannel:
        unknown_channel_msg = 'L\'identifiant du channel demandé ({}) est inconnu'.format(
            entity)

        try:
            tg_channel = await self.client.get_entity(entity)
        except struct.error:
            logging.exception(unknown_channel_msg)
            tg_channel = None
        except PeerIdInvalidError:
            logging.exception(
                unknown_channel_msg +
                '\nIl est possible que le compte Télégram qu\'utilise le bot' +
                ' ne soit pas parmi les membres du channel principal. Il n\'est donc pas '
                +
                'autorisé à accéder à ses informations. Merci de l\'y ajouter.'
            )
            tg_channel = None
        except Exception:
            logging.exception("Erreur inconnue")
            tg_channel = None

        return TelegramChannel.from_telethon_object(tg_channel)

    def is_user_authorized(self):
        return self.client.is_user_authorized()

    def sign_in(self, *args, **kwargs):
        return self.client.sign_in(*args, **kwargs)

    def send_code_request(self, *args, **kwargs):
        return self.client.send_code_request(*args, **kwargs)

    async def get_dialogs(self, *args, **kwargs) -> TelegramPersonnalChannel:
        res = []
        try:
            res = self.client.get_dialogs(*args, **kwargs)
        except sqlite3.OperationalError as e:
            try:
                self._manage_sqlite3_errors(e)
            except TwitterstormError as ee:
                logging.exception(ee)
        except Exception:
            logging.exception("Erreur inconnue")

        return [TelegramPersonnalChannel.from_telethon_object(c) for c in res]

    async def iter_participants(self, tg_channel, first_time=False, **kwargs):
        if tg_channel is None:
            logging.error(
                "On essaie d'obtenir les participant·e·s d'un channel qui n'a pas été trouvé"
            )
            return iter([])

        try:
            tg_participants = self.client.iter_participants(
                tg_channel, **kwargs)
        except Exception as e:
            logging.exception(e)
            return iter([])

        now = dt.datetime.now(s.TIMEZONE)
        # todo_es : !!!! lors d'une suppression de bdd postgres (ou nouveau campain_id), cette ligne plante au tout premier lancement, pas au 2nd
        default_sug_freq = await s.get_conf_value(
            s.CAMPAIN_ID, 'DEFAULT_SUGGESTIONS_FREQUENCY')

        res = [
            await
            TelegramParticipant.from_telethon_object(p, now, default_sug_freq,
                                                     first_time)
            async for p in tg_participants
        ]
        # todo_chk peut on utiliser yield ici?

        return iter(res)

    def send_message(self, tg_channel, message, **kwargs):
        if tg_channel is None:
            logging.error(
                "On essaie d'envoyer un message vers un channel qui n'a pas été trouvé\nMessage=\n"
                + str(message))
            return None

        try:
            res = self.client.send_message(tg_channel, message, **kwargs)
        except Exception as e:
            logging.exception(e)
            return None

        return res

    @property
    def loop(self):
        return self.client.loop

    @staticmethod
    def _manage_sqlite3_errors(e):
        if isinstance(
                e,
                sqlite3.OperationalError) and "database is locked" in str(e):
            raise TwitterstormError((
                "La connection à Télégram est déjà utilisée. Essayez de supprimer le fichier {}.session\n"
                + "Voici l'erreur d'origine :\n{}").format(
                    s.SESSION_LISTENING_LOOP, e))
        else:
            raise TwitterstormError((
                "Erreur inconnue. Essayez de supprimer le fichier {}.session\n"
                + "Voici l'erreur d'origine :\n{}").format(
                    s.SESSION_LISTENING_LOOP, e))