예제 #1
0
def client_job(id_to_send, msg_to_send, gr):
    """does a client.start and send the messages to the needed ppl"""
    client = TelegramClient(tlt_conf.sess, tlt_conf.api_id, tlt_conf.api_hash)
    client.start()
    deelay = 0
    with client:
        client.get_participants(gr[0])
        for i in range(0, len(iD_to_send)):
            try:
                client.send_message(int(id_to_send[i]),
                                    str(msg_to_send[i].encode('cp1251')))
                time.sleep(deelay)
            except ValueError:
                file = open('log.txt', 'a')  # a = append
                file.write("User" + " " + str(id_to_send[i]) + " " +
                           "is deleted" + " " + str(datetime.datetime.now()) +
                           "\n")
                file.close()
                pass
            except PeerFloodError:
                file = open('log.txt', 'a')  # a = append
                file.write(
                    "U r having some sending problems (maybe u r currently banned for spam)"
                    + " " + str(datetime.datetime.now()) + "\n")
                file.close()
                pass
def get_participants_hash(api_id: int, api_hash: str, channel_id: int):
    client = TelegramClient('session_name', api_id, api_hash)
    try:
        client.start()
        return str(client.get_participants(channel_id))
    finally:
        client.disconnect()
예제 #3
0
def main():
    api_id = os.environ.get('API_ID')
    api_hash = os.environ.get('API_HASH')

    client = TelegramClient('kolya', api_id, api_hash)
    client.start()

    print('Start find clients')
    participants = client.get_participants('u_job')
    ids = list(map(lambda x: x.id, participants))
    print('I findes {} clients'.format(len(ids)))

    text = 'Добрый день.\n\nНаша команда разработала замечательного бота для '\
           'поиска работы: @RS_Work_bot\n\nВы можете создавать в нём свои ' \
           'вакансии, или искать работу.\n\nМы учли все недостатки' \
           ' существующих ботов в телеграм, и создали очень удобного' \
           ' и просто бота.'

    print('I start the newsletter')

    count = len(ids)
    counter = 0

    def _send(ids):
        for send_id in ids[60:]:
            nonlocal counter
            counter += 1
            print('I send to client msg')
            user = client.get_entity(PeerUser(send_id))
            sec = 5
            try:
                client.send_message(user, text)
            except FloodWaitError as error:
                sec = int(str(error).split(' ')[3])
                print('FLOOD, please sleep {}'.format(sec))
            except PeerFloodError as error:
                print(str(error))
                sleep(5)

            nonlocal count
            count -= 1
            print('Отправлено: {}'.format(counter))
            print('Осталось отправить: {}'.format(count))

            print('I sleep 5 seconds')
            sleep(sec)
            print('continue')

        return print('I finished the newsletter')

    return _send(ids)
예제 #4
0
class TelethonWorker:
    def __init__(self, api, hash_, number, password, proxy, getCodeFunc):
        self.api_id = api
        self.api_hash = hash_
        self.proxy = proxy
        proxy_ip = self.proxy.split(':')[0]
        port = self.proxy.split(':')[1]
        self.getCode = getCodeFunc
        self.number = number
        self.session = number
        self.password = password
        self.app = TelegramClient(self.session,
                                  self.api_id,
                                  self.api_hash,
                                  proxy=(socks.SOCKS5, str(proxy_ip),
                                         int(port)))
        self.app.run_until_disconnected()
        self.app.start(phone=self.number,
                       password=self.password,
                       code_callback=self.getCode)
        # self.app.start()

    def getListMembers(self):
        users = []
        for dialog in self.app.get_dialogs():
            if (dialog.is_group
                    and type(dialog.draft.entity).__name__ == "Channel"):
                time.sleep(10)
                chatUser = self.app.get_participants(dialog, aggressive=True)
                for user in chatUser:
                    if (not (user.bot or user.is_self or user.deleted)):
                        users.append(user)
        return self.saveListUsers(users)

    def saveListUsers(self, arr):
        f = open('users.txt', 'w')
        for i in arr:
            username = "******" + i.username if i.username is not None else "-"
            f.write(str(i.id) + "\t" + username + '\n')
        f.close()
        return len(arr)
예제 #5
0
def user_status(api_id, api_hash, group_name):
    """
    This function can be used to get users who was active in last 24 hours
    :param api_id: Your API ID
    :param api_hash: Your API hash
    :param group_name:  group/channel name
    :return: pandas DataFrame
    """
    client = TelegramClient('session_name', api_id, api_hash).start()

    participants = client.get_participants(group_name)

    time_limit = (datetime.utcnow() -
                  timedelta(days=1)).strftime('%Y-%m-%d %H:%M:%S')

    user_name = []
    user_status = []

    if len(participants):
        for x in participants:
            try:
                if str(x.status).startswith('UserStatusRecen'):
                    user_name.append(x.first_name)
                    user_status.append('recently')
                elif str(x.status).startswith('UserStatusOnline'):
                    user_name.append(x.first_name)
                    user_status.append('online')
                elif x.status.was_online.strftime(
                        '%Y-%m-%d %H:%M:%S') >= time_limit:
                    user_name.append(x.first_name)
                    user_status.append(
                        x.status.was_online.strftime('%Y-%m-%d %H:%M:%S'))
                else:
                    pass
            except:
                pass

    df = pd.DataFrame({'User': user_name, 'status': user_status})
    print('Number of active users in last 24 hours is {}.'.format(df.shape[0]))
    print(df.head(5))
예제 #6
0
def main():
    global client
    global user_dialogs
    client = TelegramClient(PHONE.strip('+'),
                            TG_API_ID,
                            TG_API_HASH,
                            proxy=None,
                            update_workers=4,
                            spawn_read_thread=False)

    client.start()

    if not client.is_user_authorized():
        client.send_code_request(PHONE)
        client.sign_in(PHONE, input("Enter code: "))

    user_dialogs = client.get_dialogs()

    group = search_entities("Bmsklad")
    for participant in client.get_participants(group):
        print(
            f"{participant.username}, {participant.first_name} {participant.last_name}"
        )
def main():
    # Get ENV variables from the '.env' file
    load_dotenv()
    api_id = os.getenv('API_ID')
    api_hash = os.getenv('API_HASH')
    phone = os.getenv('PHONE')
    fileName = input("Enter the File Name: ")
    fileName = fileName + '.csv'

    client = TelegramClient(phone, api_id, api_hash)

    client.connect()
    if not client.is_user_authorized():
        client.send_code_request(phone)
        client.sign_in(phone, input('Enter the OTP: '))

    groups_list = []
    group = {}

    # Get's a List of Dictionaries with Group name with Group ID
    for d in client.get_dialogs():
        try:
            if d.is_group and not d.is_channel and d.name != '':
                group = {
                    "id": d.entity.id,
                    "title" : d.entity.title
                }
                groups_list.append(group)
        except:
            continue

    # Create a CSV file
    with open(fileName, mode="w",encoding='UTF-8') as f:
            writer = csv.writer(f,delimiter=",",lineterminator="\n")
            writer.writerow(['username', 'first_name', 'last_name', 'phone','group', 'user_id', 'group_id'])

    # Extract Users from the Group
    for group_name in groups_list:
        # Iterates over List of Dictionaries to extract Users
        # Output CSV file has:- username, first_name, last_name, phone, group, user_id, group_id

        target_group = group_name
        all_participants = []
        all_participants = client.get_participants(target_group["title"])

        print('Fetching Members from {}\nWriting to the file'.format(target_group["title"]))

        with open(fileName, mode="a", encoding='UTF-8') as f:
            writer = csv.writer(f, delimiter=",", lineterminator="\n")
            for user in all_participants:
                if user.username:
                    username = user.username
                else:
                    username = ""
                if user.first_name:
                    first_name = user.first_name
                else:
                    first_name = ""
                if user.last_name:
                    last_name = user.last_name
                else:
                    last_name = ""
                if user.phone:
                    phone = user.phone
                else:
                    phone = ""
                if user.id:
                    user_id = user.id
                else:
                    user_id = ""
                if target_group["title"]:
                    group = target_group["title"]
                else:
                    group = ""
                if target_group["id"]:
                    group_id = target_group["id"]
                else:
                    group_id = ""
                writer.writerow([username, first_name, last_name, phone, group, user_id, group_id])      

    print('All Group Members are scraped successfully.')
예제 #8
0
from telethon import TelegramClient
from telethon.tl.functions.channels import JoinChannelRequest
from telethon.tl.functions.channels import GetFullChannelRequest
#from telethon.tl.functions.channels import get_participants

api_id = 3409046
api_hash = '48ae9fbdf79edda291e1fa5796fc4665'
client = TelegramClient('anon', api_id, api_hash)
entity = client.get_entity("t.me/micanaljc")  #omit @
channel = "@micanaljc"

# get all the users and print them
for u in client.get_participants(channel):
    print(u.id, u.first_name, u.last_name, u.username)

    #with TelegramClient('sessionname', api_id, api_hash) as client:
    #r = client(functions.channels.JoinChannelRequest(channel='@pruebastienda'))
    #print(r)
예제 #9
0
api_id = your API ID
api_hash = 'Your API Hash'
phone_number = 'Registered mobile number with country code'
channel_username = '******'  # Channel name can be found in channel link (https://t.me/CHANNEL_NAME)
# ---------------------------------------------------------------------------------------------


client = TelegramClient('session_name', api_id, api_hash).start()

# You will be asked to enter your mobile number- Enter mobile number with country code
# Enter OTP (For OTP check Telegram inbox)
# ======================================================================================================================
#                                               Getting user details
# ======================================================================================================================
participants = client.get_participants(channel_username)

# This code can be used to extracted upto 10k user's details
# Let's get first name, last name and username
# ---------------------------------------------------------------------------------------------

firstname =[]
lastname = []
username = []
if len(participants):
    for x in participants:
        firstname.append(x.first_name)
        lastname.append(x.last_name)
        username.append(x.username)

# ---------------------------------------------------------------------------------------------
예제 #10
0
            if d.is_channel}
channel_name = 'SuperGrupoPortalRubemGonzalez' 

# choose the one that I want list users from
channel = channels[channel_name]
dialogs = client.get_dialogs()

# get all the users and print them
#for u in client.get_participants(dialogs[3].entity,limit=0):
#    print(u.id, u.first_name, u.last_name, u.username, u.access_hash)

#for u in client.get_participants(channel):
#    print(u.id, u.first_name, u.last_name, u.username, u.access_hash)


#for i in channels:
#    print(i)

#for u in dialogs:
#    print(u)

for u in dialogs:
    print(u.name)

print(dialogs[3])

for u in client.get_participants(dialogs[3].entity,aggressive=True):
    print(u.username, u.first_name, u.last_name, u.username, u.id, u.access_hash)

print(client.get_participants(dialogs[3].entity,limit=0).total)
예제 #11
0
number_of_Groups = int(input('How much groups you want to Add '))

for i in range(number_of_Groups):
		i=0		 
		for group in groups:
			print(str(i) + '- ' + group.title)
			i+=1
		Target_group = result[int(input('Chose number of gropup '))]
		try:
			for key in queryKey:
				offset = 0
				limit = 10000
				limit=None
				makeList(client_1(GetParticipantsRequest(Target_group, ChannelParticipantsSearch(key), offset, limit=10000 ,hash=0)))
			makelist(client_1.get_participants(Target_group.title, aggressive = True))	#Передаем список следующему методу	#Передаем список следующему методу
		except Exception as e:
			print(type(e))
			print(e)
			continue
		    

	

		




    
print('Users lenght - ',len(Users))
예제 #12
0
from telethon import TelegramClient, sync

api_id = '<your API>'
api_hash = '<your API>'
# 149.154.167.50:443

client = TelegramClient('<appname>', api_id, api_hash).start()

# get all the channels that I can access
groups = {d.entity.title: d.entity for d in client.get_dialogs() if d.is_group}

group_array = ['<your groups>', '']

# d.entity est une instance de chat
# print(groups)
# choose the one that I want list users from
for name in group_array:
    group = groups[name]
    print('\n\n\n###### GROUPE : ' + name)
    print('- group name : ' + str(group.id))
    # get all the users and print them
    for u in client.get_participants(group):
        print(u.id, u.first_name, u.last_name, u.username)
예제 #13
0
                    continue

            print('[+] Выберите группу, чтобы спиздить участников :')
            i = 0
            for g in groups:
                print('[' + str(i) + ']' + ' - ' + g.title)
                i += 1

            print('')
            g_index = input("[+] Введите номер : ")
            target_group = groups[int(g_index)]

            print('[+] Выборка участников...')
            time.sleep(1)
            all_participants = []
            all_participants = client.get_participants(target_group,
                                                       aggressive=True)

            print('[+] Сохранение в файл...')
            time.sleep(1)
            with open("members.csv", "w", encoding='UTF-8') as f:
                writer = csv.writer(f, delimiter=",", lineterminator="\n")
                writer.writerow([
                    'username', 'user id', 'access hash', 'name', 'group',
                    'group id'
                ])
                for user in all_participants:
                    if user.username:
                        username = user.username
                    else:
                        username = ""
                    if user.first_name:
    client = TelegramClient(api_id,
                            api_id,
                            api_hash,
                            proxy=(proxy_host, proxy_port, proxy_secret),
                            connection=connection.tcpmtproxy.
                            ConnectionTcpMTProxyRandomizedIntermediate)
else:
    client = TelegramClient(api_id, api_id, api_hash)
client.start()

usernames_import = []
for chat in export_chats:
    usernames_export = []

    log.info(f"✔ [EXPORT] Parse all users from chat @{chat} ...")
    users = client.get_participants(chat)

    log.info(f"✔ [EXPORT] Users parsed: {len(users)}")
    log.debug(f"✔ [EXPORT] Users: \n{users}")

    usernames_export = filter_users(users=users,
                                    exclude_bots=exclude_bots,
                                    exclude_deleted=exclude_deleted,
                                    exclude_offline=exclude_offline_days,
                                    users_blacklist=usernames_blacklist)

    # Exclude chat admins
    if exclude_admins:
        usernames_admins = []

        for user in client.iter_participants(chat,
예제 #15
0
파일: informer.py 프로젝트: Leavel/cs_jia
class TGInformer:
    def __init__(
        self,
        account_id=None,
        db_prod_ip=None,
        db_prod_port=None,
        db_prod_name=None,
        db_prod_user=None,
        db_prod_password=None,
        db_local_ip=None,
        db_local_port=None,
        db_local_name=None,
        db_local_user=None,
        db_local_password=None,
        tg_notifications_channel_id=None,
        google_credentials_path=None,
        google_sheet_name=None,
    ):

        # ------------------
        # Instance variables
        # ------------------
        self.keyword_list = []
        self.channel_list = []
        self.channel_meta = {}
        self.bot_task = None
        self.KEYWORD_REFRESH_WAIT = 15 * 60
        self.MIN_CHANNEL_JOIN_WAIT = 30
        self.MAX_CHANNEL_JOIN_WAIT = 120
        self.bot_uptime = 0

        # --------------
        # Display banner
        # --------------
        print("""
            ____      ____                              
           /  _/___  / __/___  _________ ___  ___  _____
           / // __ \/ /_/ __ \/ ___/ __ `__ \/ _ \/ ___/
         _/ // / / / __/ /_/ / /  / / / / / /  __/ /    
        /___/_/ /_/_/  \____/_/  /_/ /_/ /_/\___/_/     

        by @paulpierre 11-26-2019
        """)

        # ------------------------------------------------
        # Check if we're in app engine and set environment
        # ------------------------------------------------

        self.MYSQL_CONNECTOR_STRING = 'mysql+pymysql://{}:{}@{}:{}/{}'.format(
            db_prod_user, db_prod_password, db_prod_ip, db_prod_port,
            db_prod_name)
        '''if os.getenv('GAE_INSTANCE'):
            self.SERVER_MODE = 'prod'  # prod vs local
            self.MYSQL_CONNECTOR_STRING = 'mysql+pymysql://{}:{}@{}:{}/{}'.format(db_prod_user, db_prod_password, db_prod_ip, db_prod_port, db_prod_name)
        else:
            self.SERVER_MODE = 'local'
            self.MYSQL_CONNECTOR_STRING = 'mysql+pymysql://{}:{}@{}:{}/{}'.format(db_local_user, db_local_password, db_local_ip, db_local_port, db_local_name)

        logging.info('SERVER_MODE: {} GAE_ENV: {}'.format(self.SERVER_MODE, str(os.getenv('GAE_INSTANCE'))))'''

        # -----------------------------------------
        # Set the channel we want to send alerts to
        # -----------------------------------------
        self.monitor_channel = tg_notifications_channel_id

        if not account_id:
            logging.error('Must specify account_id for bot instance')
            return

        # -----------------------
        # Initialize Google Sheet  谷歌表进行初始化
        # -----------------------
        '''scope = [
            'https://docs.google.com/spreadsheets/d/1cPLE0raSMEflvDBwENu36J1pmyd8hVKdAT6eGd9eAGQ/edit#gid=0',
            ]  # 'https://drive.google.com/drive/my-drive'
        creds = ServiceAccountCredentials.from_json_keyfile_name(google_credentials_path, scope)
        self.gsheet = gspread.authorize(creds)
        self.sheet = self.gsheet.open(google_sheet_name).sheet1'''

        # -------------------
        # Initialize database  初始化数据库
        # -------------------
        self.engine = db.create_engine(self.MYSQL_CONNECTOR_STRING,
                                       pool_size=50,
                                       max_overflow=100)  # , echo=True
        self.Session = sessionmaker(bind=self.engine)
        self.session = self.Session()

        # --------------------
        # Load account from DB  加载数据库里面的账户
        # --------------------
        self.tg_user = None
        try:
            self.account = self.session.query(Account).filter_by(
                account_id=account_id).first()
            print(self.account)
        except ProgrammingError as e:
            logging.error('Database is not set up, setting it up')
            build_database.initialize_db()
            self.account = self.session.query(Account).filter_by(
                account_id=account_id).first()

        if not self.account:
            logging.error(
                'Invalid account_id {} for bot instance'.format(account_id))
            sys.exit(0)

        # ----------------------
        # Telegram service login
        # ----------------------
        logging.info('Logging in with account # {}'.format(
            self.account.account_phone))
        session_file = 'session/' + self.account.account_phone.replace('+', '')
        self.client = TelegramClient(session_file, self.account.account_api_id,
                                     self.account.account_api_hash)

        # -----------------------
        # Authorize from terminal
        # -----------------------
        # TODO: automate authcode with the Burner API
        self.client.connect()
        if not self.client.is_user_authorized():
            logging.info('Client is currently not logged in, please sign in!')
            self.client.send_code_request(self.account.account_phone)
            self.tg_user = self.client.sign_in(self.account.account_phone,
                                               input('Enter code: '))

    # =============
    # Get all users
    # =============
    def get_channel_all_users(self, channel_id):
        # TODO: this function is not complete
        channel = self.client.get_entity(PeerChat(channel_id))
        users = self.client.get_participants(channel)
        print('total users: {}'.format(users.total))
        for user in users:
            if user.username is not None and not user.is_self:
                print(utils.get_display_name(user), user.username, user.id,
                      user.bot, user.verified, user.restricted,
                      user.first_name, user.last_name, user.phone,
                      user.is_self)

    # =====================
    # Get # of participants
    # =====================
    async def get_channel_user_count(self, channel):
        data = await self.client.get_entity(PeerChannel(-channel))
        users = await self.client.get_participants(data)
        return users.total

    # =======================
    # Get channel by group ID
    # =======================
    def get_channel_info_by_group_id(self, id):
        channel = self.client.get_entity(PeerChat(id))

        return {
            'channel_id': channel.id,
            'channel_title': channel.title,
            'is_broadcast': False,
            'is_mega_group': False,
            'channel_access_hash': None,
        }

    # ==========================
    # Get channel by channel URL
    # ==========================
    async def get_channel_info_by_url(self, url):
        logging.info('{}: Getting channel info with url: {}'.format(
            sys._getframe().f_code.co_name, url))
        channel_hash = utils.parse_username(url)[0]

        # -----------------------------------------
        # Test if we can get entity by channel hash
        # -----------------------------------------
        try:
            channel = await self.client.get_entity(channel_hash)
        except ValueError:
            logging.info('{}: Not a valid telegram URL: {}'.format(
                sys._getframe().f_code.co_name, url))
            return False
        except FloodWaitError as e:
            logging.info('{}: Got a flood wait error for: {}'.format(
                sys._getframe().f_code.co_name, url))
            await asyncio.sleep(e.seconds * 2)

        return {
            'channel_id': channel.id,
            'channel_title': channel.title,
            'is_broadcast': channel.broadcast,
            'is_mega_group': channel.megagroup,
            'channel_access_hash': channel.access_hash,
        }

    # ===================
    # Get user info by ID
    # ===================
    async def get_user_by_id(self, user_id=None):
        u = await self.client.get_input_entity(PeerUser(user_id=user_id))
        user = await self.client(GetFullUserRequest(u))

        logging.info('{}: User ID {} has data:\n {}\n\n'.format(
            sys._getframe().f_code.co_name, user_id, user))

        return {
            'username': user.user.username,
            'first_name': user.user.first_name,
            'last_name': user.user.last_name,
            'is_verified': user.user.verified,
            'is_bot': user.user.bot,
            'is_restricted': user.user.restricted,
            'phone': user.user.phone,
        }

    # ==============================
    # Initialize keywords to monitor
    # ==============================
    def init_keywords(self):
        keywords = self.session.query(Keyword).filter_by(
            keyword_is_enabled=True).all()

        for keyword in keywords:
            self.keyword_list.append({
                'id': keyword.keyword_id,
                'name': keyword.keyword_description,
                'regex': keyword.keyword_regex
            })
            logging.info('{}: Monitoring keywords: {}'.format(
                sys._getframe().f_code.co_name,
                json.dumps(self.keyword_list, indent=4)))

    # ===========================
    # Initialize channels to join
    # ===========================
    async def init_monitor_channels(self):

        # ---------------------
        # Let's start listening
        # ---------------------
        @self.client.on(events.NewMessage)
        async def message_event_handler(event):
            await self.filter_message(event)

        # -----------------------------
        # Update the channel data in DB   更新数据库中的通道数据
        # -----------------------------
        current_channels = []
        # Lets iterate through all the open chat channels we have   让我们遍历所有开放的聊天频道
        async for dialog in self.client.iter_dialogs():
            channel_id = dialog.id
            # [informer.py -> 271]

            # As long as it is not a chat with ourselves   只要不是和自己聊天
            if not dialog.is_user:

                # Certain channels have a prefix of 100, lets remove that   某些频道有一个100的前缀,让我们删除它
                if str(abs(channel_id))[:3] == '100':
                    channel_id = int(str(abs(channel_id))[3:])

                # Lets add it to the current list of channels we're in
                # 让我们把它添加到当前的频道列表中
                current_channels.append(channel_id)
                logging.info('id: {} name: {}'.format(dialog.id, dialog.name))

        logging.info('{}: ### Current channels {}'.format(
            sys._getframe().f_code.co_name, json.dumps(current_channels)))

        # -----------------------------------
        # Get the list of channels to monitor   获取要监视的通道列表
        # -----------------------------------
        self.session = self.Session()
        account = self.session.query(Account).first()
        monitors = self.session.query(Monitor).filter_by(
            account_id=account.account_id).all()

        channels_to_monitor = []
        for monitor in monitors:
            channel_data = {
                'channel_id': monitor.channel.channel_id,
                'channel_name': monitor.channel.channel_name,
                'channel_title': monitor.channel.channel_title,
                'channel_url': monitor.channel.channel_url,
                'account_id': monitor.channel.account_id,
                'channel_is_megagroup': monitor.channel.channel_is_mega_group,
                'channel_is_group': monitor.channel.channel_is_group,
                'channel_is_private': monitor.channel.channel_is_private,
                'channel_is_broadcast': monitor.channel.channel_is_broadcast,
                'channel_access_hash': monitor.channel.channel_access_hash,
                'channel_size': monitor.channel.channel_size,
                'channel_is_enabled': monitor.channel.channel_is_enabled,
                'channel_tcreate': monitor.channel.channel_tcreate
            }

            if monitor.channel.channel_is_enabled is True:
                channels_to_monitor.append(channel_data)
        self.session.close()

        # -------------------------------
        # Iterate through channel objects
        # -------------------------------
        for channel in channels_to_monitor:
            self.session = self.Session()
            channel_obj = self.session.query(Channel).filter_by(
                channel_id=channel['channel_id']).first()

            # -------------------------------
            # We have sufficient channel data
            # -------------------------------
            if channel['channel_id']:
                self.channel_list.append(channel['channel_id'])
                logging.info(
                    'Adding channel {} to monitoring w/ ID: {} hash: {}'.
                    format(channel['channel_name'], channel['channel_id'],
                           channel['channel_access_hash']))

                self.channel_meta[channel['channel_id']] = {
                    'channel_id': channel['channel_id'],
                    'channel_title': channel['channel_title'],
                    'channel_url': channel['channel_url'],
                    'channel_size': 0,
                    'channel_texpire': datetime.now() + timedelta(hours=3)
                }

            else:
                # ------------------------
                # If not grab channel data
                # ------------------------
                if channel['channel_url'] and '/joinchat/' not in channel[
                        'channel_url']:
                    o = await self.get_channel_info_by_url(
                        channel['channel_url'])

                    # -----------------------------
                    # If channel is invalid, ignore
                    # -----------------------------
                    if o is False:
                        logging.error('Invalid channel URL: {}'.format(
                            channel['channel_url']))
                        continue
                    logging.info('{}: ### Successfully identified {}'.format(
                        sys._getframe().f_code.co_name,
                        channel['channel_name']))

                # -------------------------
                # If the channel is a group
                # -------------------------
                elif channel['channel_is_group']:
                    o = await self.get_channel_info_by_group_id(
                        channel['channel_id'])
                    logging.info('{}: ### Successfully identified {}'.format(
                        sys._getframe().f_code.co_name,
                        channel['channel_name']))
                else:
                    logging.info('{}: Unable to indentify channel {}'.format(
                        sys._getframe().f_code.co_name,
                        channel['channel_name']))
                    continue

                channel_obj.channel_id = o['channel_id']
                channel_obj.channel_title = o['channel_title']
                channel_obj.channel_is_broadcast = o['is_broadcast']
                channel_obj.channel_is_mega_group = o['is_mega_group']
                channel_obj.channel_access_hash = o['channel_access_hash']

                self.channel_meta[o['channel_id']] = {
                    'channel_id': o['channel_id'],
                    'channel_title': o['channel_title'],
                    'channel_url': channel['channel_url'],
                    'channel_size': 0,
                    'channel_texpire': datetime.now() + timedelta(hours=3)
                }

            # -------------------------------
            # Determine is channel is private  确定通道是私有的
            # -------------------------------
            channel_is_private = True if (
                channel['channel_is_private']
                or '/joinchat/' in channel['channel_url']) else False
            if channel_is_private:
                logging.info(
                    'channel_is_private: {}'.format(channel_is_private))

            # ------------------------------------------
            # Join if public channel and we're not in it
            # ------------------------------------------
            if channel[
                    'channel_is_group'] is False and channel_is_private is False and channel[
                        'channel_id'] not in current_channels:
                logging.info('{}: Joining channel: {} => {}'.format(
                    sys._getframe().f_code.co_name, channel['channel_id'],
                    channel['channel_name']))
                try:
                    await self.client(
                        JoinChannelRequest(channel=await self.client.
                                           get_entity(channel['channel_url'])))
                    sec = randrange(self.MIN_CHANNEL_JOIN_WAIT,
                                    self.MAX_CHANNEL_JOIN_WAIT)
                    logging.info('sleeping for {} seconds'.format(sec))
                    await asyncio.sleep(sec)
                except FloodWaitError as e:
                    logging.info(
                        'Received FloodWaitError, waiting for {} seconds..'.
                        format(e.seconds))
                    # Lets wait twice as long as the API tells us for posterity
                    await asyncio.sleep(e.seconds * 2)

                except ChannelPrivateError as e:
                    logging.info(
                        'Channel is private or we were banned bc we didnt respond to bot'
                    )
                    channel['channel_is_enabled'] = False

            # ------------------------------------------
            # Join if private channel and we're not in it
            # ------------------------------------------
            elif channel_is_private and channel[
                    'channel_id'] not in current_channels:
                channel_obj.channel_is_private = True
                logging.info('{}: Joining private channel: {} => {}'.format(
                    sys._getframe().f_code.co_name, channel['channel_id'],
                    channel['channel_name']))

                # -------------------------------------
                # Join private channel with secret hash
                # -------------------------------------
                channel_hash = channel['channel_url'].replace(
                    'https://t.me/joinchat/', '')

                try:
                    await self.client(
                        ImportChatInviteRequest(hash=channel_hash))

                    # ----------------------
                    # Counter FloodWaitError
                    # ----------------------
                    sec = randrange(self.MIN_CHANNEL_JOIN_WAIT,
                                    self.MAX_CHANNEL_JOIN_WAIT)
                    logging.info('sleeping for {} seconds'.format(sec))
                    await asyncio.sleep(sec)
                except FloodWaitError as e:
                    logging.info(
                        'Received FloodWaitError, waiting for {} seconds..'.
                        format(e.seconds))
                    await asyncio.sleep(e.seconds * 2)
                except ChannelPrivateError as e:
                    logging.info(
                        'Channel is private or we were banned bc we didnt respond to bot'
                    )
                    channel['channel_is_enabled'] = False
                except UserAlreadyParticipantError as e:
                    logging.info('Already in channel, skipping')
                    self.session.close()
                    continue

            # ---------------------------------
            # Rollback session if we get a dupe
            # ---------------------------------
            try:
                self.session.commit()
            except IntegrityError:
                self.session.rollback()
            except InterfaceError:
                pass
            self.session.close()

        logging.info('{}: Monitoring channels: {}'.format(
            sys._getframe().f_code.co_name,
            json.dumps(self.channel_list, indent=4)))
        logging.info('Channel METADATA: {}'.format(self.channel_meta))

    # ===========================
    # Filter the incoming message
    # ===========================
    async def filter_message(self, event):
        # If this is a channel, grab the channel ID
        if isinstance(event.message.to_id, PeerChannel):
            channel_id = event.message.to_id.channel_id
        # If this is a group chat, grab the chat ID
        elif isinstance(event.message.to_id, PeerChat):
            channel_id = event.message.chat_id
        else:
            # Message comes neither from a channel or chat, lets skip
            return

        # Channel values from the API are signed ints, lets get ABS for consistency
        channel_id = abs(channel_id)

        message = event.raw_text

        # Lets check to see if the message comes from our channel list
        if channel_id in self.channel_list:

            # Lets iterate through our keywords to monitor list
            for keyword in self.keyword_list:

                # If it matches the regex then voila!
                if re.search(keyword['regex'], message, re.IGNORECASE):
                    logging.info(
                        'Filtering: {}\n\nEvent raw text: {} \n\n Data: {}'.
                        format(channel_id, event.raw_text, event))

                    # Lets send the notification with all the pertinent information in the params
                    await self.send_notification(message_obj=event.message,
                                                 event=event,
                                                 sender_id=event.sender_id,
                                                 channel_id=channel_id,
                                                 keyword=keyword['name'],
                                                 keyword_id=keyword['id'])

    # ====================
    # Handle notifications
    # ====================
    async def send_notification(self,
                                sender_id=None,
                                event=None,
                                channel_id=None,
                                keyword=None,
                                keyword_id=None,
                                message_obj=None):
        message_text = message_obj.message

        # Lets set the meta data
        is_mention = message_obj.mentioned
        is_scheduled = message_obj.from_scheduled
        is_fwd = False if message_obj.fwd_from is None else True
        is_reply = False if message_obj.reply_to_msg_id is None else True
        is_bot = False if message_obj.via_bot_id is None else True

        if isinstance(message_obj.to_id, PeerChannel):
            is_channel = True
            is_group = False
            is_private = False
        elif isinstance(message_obj.to_id, PeerChat):
            is_channel = False
            is_group = True
            is_private = False
        else:
            is_channel = False
            is_group = False
            is_private = False

        # We track the channel size and set it to expire after sometime, if it does we update the participant size
        if channel_id in self.channel_meta and self.channel_meta[channel_id][
                'channel_size'] == 0 or datetime.now(
                ) > self.channel_meta[channel_id]['channel_texpire']:
            logging.info('refreshing the channel information')
            channel_size = await self.get_channel_user_count(channel_id)
        else:
            channel_size = self.channel_meta[channel_id]['channel_size']

        # Lets get who sent the message
        sender = await event.get_sender()
        sender_username = sender.username

        channel_id = abs(channel_id)
        timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

        # Set the message for the notification we're about to send in our monitor channel
        message = '⚠️ "{}" mentioned by {} in => "{}" url: {}\n\n Message:\n"{}\ntimestamp: {}'.format(
            keyword, sender_username,
            self.channel_meta[channel_id]['channel_title'],
            self.channel_meta[channel_id]['channel_url'], message_text,
            timestamp)
        logging.info('{} Sending notification {}'.format(
            sys._getframe().f_code.co_name, message))

        # ----------------
        # Send the message
        # ----------------
        await self.client.send_message(self.monitor_channel, message)

        # -------------------------
        # Write to the Google Sheet  写入到谷歌工作表
        # -------------------------
        '''self.sheet.append_row([
            sender_id,
            sender_username,
            channel_id,
            self.channel_meta[channel_id]['channel_title'],
            self.channel_meta[channel_id]['channel_url'],
            keyword,
            message_text,
            is_mention,
            is_scheduled,
            is_fwd,
            is_reply,
            is_bot,
            is_channel,
            is_group,
            is_private,
            channel_size,
            timestamp
        ])'''

        # --------------
        # Add user to DB
        # --------------
        o = await self.get_user_by_id(sender_id)

        self.session = self.Session()
        if not bool(
                self.session.query(ChatUser).filter_by(
                    chat_user_id=sender_id).all()):

            self.session.add(
                ChatUser(chat_user_id=sender_id,
                         chat_user_is_bot=o['is_bot'],
                         chat_user_is_verified=o['is_verified'],
                         chat_user_is_restricted=o['is_restricted'],
                         chat_user_first_name=o['first_name'],
                         chat_user_last_name=o['last_name'],
                         chat_user_name=o['username'],
                         chat_user_phone=o['phone'],
                         chat_user_tlogin=datetime.now(),
                         chat_user_tmodified=datetime.now()))

        # -----------
        # Add message
        # -----------
        msg = Message(chat_user_id=sender_id,
                      account_id=self.account.account_id,
                      channel_id=channel_id,
                      keyword_id=keyword_id,
                      message_text=message_text,
                      message_is_mention=is_mention,
                      message_is_scheduled=is_scheduled,
                      message_is_fwd=is_fwd,
                      message_is_reply=is_reply,
                      message_is_bot=is_bot,
                      message_is_group=is_group,
                      message_is_private=is_private,
                      message_is_channel=is_channel,
                      message_channel_size=channel_size,
                      message_tcreate=datetime.now())
        self.session.add(msg)

        self.session.flush()

        message_id = msg.message_id

        self.session.add(
            Notification(keyword_id=keyword_id,
                         message_id=message_id,
                         channel_id=channel_id,
                         account_id=self.account.account_id,
                         chat_user_id=sender_id))

        # -----------
        # Write to DB
        # -----------
        try:
            self.session.commit()
        except IntegrityError:
            pass
        self.session.close()

    async def update_keyword_list(self):
        # ------------------------------
        # Lets update keywords in memory
        # ------------------------------
        # TODO: functionality to poll the DB for new keywords and refresh in memory
        logging.info('### updating keyword_list')
        pass

    # ===========================
    # Loop we run while we listen  边监听边循环
    # ===========================
    async def bot_interval(self):
        self.init_keywords()
        await self.init_monitor_channels()
        while True:
            logging.info('### Running bot interval')
            await self.update_keyword_list()
            await asyncio.sleep(self.KEYWORD_REFRESH_WAIT)

    def stop_bot_interval(self):
        self.bot_task.cancel()

    # ===========================
    # Initialize connection to TG
    # ===========================
    def init(self):
        loop = asyncio.get_event_loop()
        self.bot_task = loop.create_task(self.bot_interval())

        with self.client:
            self.client.run_until_disconnected()
            try:
                loop.run_until_complete(self.bot_task)
            except asyncio.CancelledError:
                logging.info('### Async cancelled')
                pass
예제 #16
0
from telethon import TelegramClient, sync

api_id = 'YOUR_TELEGRAM_ID'
api_hash = 'YOUR_TELEGRAM_HASH'
client = TelegramClient('YOUR_PHONE_NUMBER', api_id, api_hash)
client.start()

with client:
    # Set USER_ID or GROUP_ID or CHANNEL_ID above
    results = client.get_participants('@username', aggressive=True)
    print(str(len(results)) + ' found users')

    users = []

    for result in results:
        print(str(result.id) + ' - ' + result.first_name)
예제 #17
0
def scrape_task(user_id, group_id, tg_account_id=None):
    user = User.objects.get(pk=user_id)
    group = TelegramGroup.objects.get(pk=group_id)
    if tg_account_id:
        account = TelegramAccount.objects.get(pk=tg_account_id)
    else:
        try:
            account = random.choice(
                TelegramAccount.objects.filter(active=True, confirmed=True))
        except IndexError:
            return {
                'success': False,
                'error': _('No available active accounts '
                           'for scrapping.')
            }
    proxy_settings = (socks.HTTP, settings.PROXY_HOST, settings.PROXY_PORT,
                      True, settings.PROXY_USERNAME +
                      '-session-{}'.format(random.randint(9999, 9999999)),
                      settings.PROXY_PASSWORD)
    account.set_is_used(True)
    client = TelegramClient(StringSession(account.session),
                            account.api_id,
                            account.api_hash,
                            proxy=proxy_settings)
    client.connect()

    try:
        try:
            group_entity = client.get_input_entity(
                group.username if group.username else group.join_link)
        except Exception as e:
            logger.exception(e)
            account.set_is_used(False)
            client.disconnect()
            return {'success': False, 'error': _('Error finding group.')}

        joined = join_group(client, account, group_entity)
        if not joined:
            account.set_is_used(False)
            client.disconnect()
            return {'success': False, 'error': _('Error joining group.')}
        elif isinstance(joined, dict):  # means there was an error
            account.set_is_used(False)
            client.disconnect()
            return joined

        try:
            members = client.get_participants(
                group_entity,
                aggressive=True,
                filter=ChannelParticipantsRecent())
            admins = client.get_participants(
                group_entity,
                aggressive=True,
                filter=ChannelParticipantsAdmins())
            members = [
                m for m in members if not m.bot and  # skip bots
                m not in admins and  # skip admins
                m.username and  # skip without usernames
                not m.is_self
            ]  # skip if members is current client user
        except:
            account.set_is_used(False)
            client.disconnect()
            return {
                'success': False,
                'error': _('Error getting list of group '
                           'members.')
            }
        client.disconnect()
        account.set_is_used(False)
        with transaction.atomic():
            for i, m in enumerate(members):
                TelegramContact.objects.get_or_create(user=user,
                                                      group=group,
                                                      username=m.username,
                                                      priority=i + 1)
        message = _('Scrapped {} users.'.format(len(members)))
        return {'success': True, 'error': None, 'message': message}
    except Exception as e:
        logger.exception(e)
        return {
            'success': True,
            'error': _('Error getting list of group '
                       'members.')
        }
예제 #18
0
파일: private.py 프로젝트: WTFMI/TGDB
    while True:
        participants = loop.run_until_complete(client(GetParticipantsRequest(
            channel, ChannelParticipantsSearch(''), offset, limit, hash=0
            )))
        if not participants.users:
            break
        all_participants.extend(participants.users)
        offset += len(participants.users)
        print('Magic Number: ', offset)
        return all_participants
#channel = Channel(id=1330505769, title='\u2066♥️\u2069Empathogens❄️קהילת🍄אמפתוגנים', photo=ChatPhoto(photo_small=FileLocation(dc_id=4, volume_id=449011102, local_id=3795, secret=5154166241589927286), photo_big=FileLocation(dc_id=4, volume_id=449011102, local_id=3797, secret=-3469345200309841222)), date=datetime.datetime(2018, 9, 25, 13, 42, 14, tzinfo=datetime.timezone.utc), version=0)
qq = get_channels()
print('*******\n')
print(qq)
#sys.exit()
r = loop.run_until_complete(client.get_participants(qq, None, aggressive=True))
db = open('users.db', 'wb+')
for x in r:
    print(x)
    #pickle.dump(x, db)
    #db.write(x)
    #db.write()
pickle.dump(r, db)
sys.exit()
##
fh = open('choiceVideo.mp4', 'rb')
msg = loop.run_until_complete(client.send_file('me', fh, attributes=(DocumentAttributeVideo(0, 0, 0),)))

location = 0
max = 2
for x in range(location, r.length():
예제 #19
0
from telethon import TelegramClient
from telethon import events
from telethon.tl.functions.channels import GetParticipantsRequest
#from telethon.tl.functions.channels import AdminLogEvent
from telethon.sync import TelegramClient

api_id = 3409046
api_hash = '48ae9fbdf79edda291e1fa5796fc4665'
#phone_number = '+528132341246'
channel = '@pruebastienda'
################################################

client = TelegramClient('sessionname', api_id, api_hash) 
client.start()
responses = client.get_participants(channel)
print(responses[0].first_name)
client.run_until_disconnected()
예제 #20
0
파일: Telebot.py 프로젝트: cnukaus/telebot
if (client.is_user_authorized() == False):
    phone_number = 'PHONE NUMBER'
    client.send_code_request(phone_number)
    myself = client.sign_in(phone_number, input('Enter code: '))
#client = InteractiveTelegramClient('session_id', 'phone', api_id, api_hash)
dialog_count = 3
dialogs = client.get_dialogs(dialog_count)
#print('total:', dialogs.total, '; have:', len(dialogs))
for dia in dialogs:
    print(utils.get_display_name(dia))
    #print(client.get_participants(dia))
matchedchatids = re.findall(
    "(?<=PeerChannel\\(channel_id\\=).*?(?=\\))",
    str(client.get_dialogs(dialog_count)
        ))  #"(?<=entity=Channel\\(id\\=).*?(?=,)" "(?<=title\\=').*?(?=')"
for item in matchedchatids:
    print(item)
    print(client.get_entity(item))
    #print(len(client.get_participants(item)))
dialogs, entities = client.get_dialogs(dialog_count)
for i, entity in enumerate(entities):
    i += 1  # 1-based index
    print('{}. {}. id: {}'.format(i, get_display_name(entity), entity.id))

#links = channels.get_channels()
channel = client.get_entity(entity.id)

#ch_full = client(GetFullChannelRequest(channel=ch))

members = client.get_participants(channel)
print(len(members))
예제 #21
0
import time

## Defining the need variables
api_id = '683428'  # Input your api_id here
api_hash = '967b28d111f82b906b6f28da1ff04411'  # Input your api_hash here

token = '927041875:AAHr9CfWRwJhXMArxIwwyjLL12es8DI62VI'

admin = [577180091]

## Connection of all the integrated APIs
bot = TelegramClient("Hack", api_id, api_hash)
bot.start()

name = input("Enter the link to the group here: ")

channel = bot.get_entity(name)

members = bot.get_participants(channel)

chat = bot.get_entity("https://t.me/minershu")

[
    bot.send_message(chat, f"{each.username}") for each in members
    if each.username is not None and each.bot is False
]

print("Bot running!!!")
bot.run_until_disconnected()
while True:
    pass
예제 #22
0
link = "CHAT LINK"

try:
    client(ImportChatInviteRequest(link))
except:
    pass

join = client.get_entity(link)

print('Telethon-Users-Parse\n   Created by @alowave')
title = join.title
runtime = int(time.time())

f = open('Users ' + title.replace('"', "'") + ' ' + time.ctime(runtime).replace(':', '.') + '.txt', 'a', encoding = 'utf-8')

users = client.get_participants(join.id, aggressive=True)
a = {}

f.write(str(runtime) + ' - ' + title)
f.write('\nПолучено ' + str(len(users)) + ' из ' + str(users.total) + ' пользователей.\n')

for user in users:
    if user.username == None:
        username = '******'
    else:
        username = user.username
    a[user.id] = username

sort_users =  sorted(a)
for user in sort_users:
    user_str = str(user) + ' : ' + a[user]
예제 #23
0
# get all the users and print them
#for u in client.get_participants(dialogs[3].entity,limit=0):
#    print(u.id, u.first_name, u.last_name, u.username, u.access_hash)

#for u in client.get_participants(channel):
#    print(u.id, u.first_name, u.last_name, u.username, u.access_hash)

#for i in channels:
#    print(i)

#for u in dialogs:
#    print(u)

for u in dialogs:
    print(u)
#for u in dialogs:
#    print(u.name)

#print(dialogs[3])

#print(client.get_participants(dialogs[3].entity,limit=0).total)
print(dialogs[groupname])

for u in client.get_participants(dialogs[groupname], aggressive=True):
    print(u.username, u.first_name, u.last_name, u.username, u.id,
          u.access_hash)
    receiver = InputPeerUser(u.id, u.access_hash)
    # sending message using telegram client
    client.send_message(receiver, message, parse_mode='html')
예제 #24
0
def process_telegram_list():
    #######################
    url_list2 = []
    try:
        conn = mysql.connector.connect(host='***m',
                                       user='******',
                                       passwd='***',
                                       db='***')
    except:
        print('aaaa')
        sys.exit()
    cursor = conn.cursor()

    # SQL 查询语句
    search_sql = 'select * from h_hot'
    try:
        # 执行SQL语句
        cursor.execute(search_sql)
        # 获取所有记录列表
        results = cursor.fetchall()
        for row in results:
            if row[2] != None and row[2] != '':
                token_cid = row[1]
                token_url = row[2]

                # 打印结果
                #print(token_id, token_name, token_symbol, token_github_master)
                url_list2.append([token_cid, token_url])
    except:
        print("Error: unable to fecth data")

    # 关闭数据库连接
    cursor.close()
    conn.close()
    ################

    url_list_mysql = []

    today = str(datetime.date.today().strftime('%Y%m%d'))

    count = 0

    api_id = 123456  # 用户api_id
    api_hash = '***'  # 用户 api_hash
    phone_number = '+123456'  # 用户号码

    # client = TelegramClient('session_id',
    #                         api_id=api_id, api_hash=api_hash,
    #                         # proxy=(socks.SOCKS5, 'localhost', 61800)
    #                         proxy=(socks.SOCKS5, 'localhost', 61800)
    #                         )
    client = TelegramClient('session_id', api_id, api_hash)
    client.session.report_errors = False
    client.start()
    client.connect()
    for i in range(len(url_list2)):
        #for i in range(3):
        try:
            channel_str = url_list2[i][1]
            if 'https://t.me/' in channel_str and 'join' not in channel_str:
                channel = client.get_entity(
                    channel_str)  # 'https://t.me/StratisPlatform'
                print(i, len(url_list2), url_list2[i][1])
                participants = client.get_participants(channel)
                cangku2 = {}
                cangku2['personNum'] = str(len(participants))
                cangku2['updateTime'] = today
                cangku2['cid'] = str(url_list2[i][0])
                cangku2['telegramUrl'] = str(url_list2[i][1])
                url_list_mysql.append(cangku2)
                count = count + 1
        except:
            print('error!', url_list2[i])
    print(str(count) + '个数据爬取完成')

    return url_list_mysql, count
예제 #25
0
}

list_channel = []
list_user = {}

for d in client.get_dialogs():
    if d.is_channel:
        # remove - 100 in front of channel id sent back by API.
        CHANNEL_ID = int(str(d.id)[4:])
        if CHANNEL_ID not in LIST_CHANNEL_ID:
            continue

        list_channel.append(d)

        # get all the users
        for p in client.get_participants(d):
            if p.id not in list_user:
                try:
                    was_online = p.status.was_online
                except AttributeError:
                    was_online = datetime.datetime.now()

                first_name = p.first_name or ''
                last_name = p.last_name or ''
                username = p.username or ''
                list_user[p.id] = {
                    'first_name': first_name,
                    'last_name': last_name,
                    'username': username,
                    'id': p.id,
                    'was_online': was_online,
예제 #26
0
from telethon import TelegramClient, sync
from dotenv import load_dotenv
import os
import sys

scripts_path = os.path.dirname(os.path.abspath(__file__))
project_root = os.path.join(scripts_path, '..')
sys.path.insert(0, project_root)
from config.provider import TelegramConfig

load_dotenv()

channel_id = input('Please enter channel ID: ')

telegram_config = TelegramConfig()
telegram_client = TelegramClient(telegram_config.telegram_api_session_name,
                                 telegram_config.telegram_api_id,
                                 telegram_config.telegram_api_hash).start()

participants = telegram_client.get_participants(int(channel_id))
details = [{"username": o.username, "id": o.id} for o in participants]
for d in details:
    print(d)
예제 #27
0
import sys
from telethon.tl.types import PeerUser, PeerChat, PeerChannel

if __name__ == '__main__':

    api_id = *
    api_hash = '*'
    client = TelegramClient('session_name', api_id, api_hash)
    client.start()
    """
    my_name = utils.get_display_name(client.get_me())
    msg = 'test'
    id_client = 1220038
    id_client1 = client.get_entity(386520922)
    client.send_message(id_client1, msg)
    """

    users = client.get_participants('t.me/joinchat/*')
    print(users[0],'\n')
    print(users[1],'\n')
    print(users[2],'\n')
    """
    for user in users:
        if user.username is not None:
            print(user.username,user.first_name,'\n')
    """
    my_name = utils.get_display_name(client.get_me())
    msg = 'test'
    id_client = 386520922
    client.send_message(id_client, msg)
예제 #28
0
def result():
    if request.method == 'POST':
        try:
            apikey = request.form.get('apikey')
            inputdict['apikey'] = apikey
            accesshash = request.form.get('accesshash')
            inputdict['accesshash'] = accesshash
            phonenumber = request.form.get('phonenumber')
            inputdict['phonenumber'] = phonenumber
            channelname = request.form.get('channelname')

            client = TelegramClient(phonenumber, apikey, accesshash)

            client.session.report_errors = False
            client.connect()

            if 'file' not in request.files:
                print("No file to upload")
                if not client.is_user_authorized():
                    #client.send_code_request(phonenumber)
                    #client.sign_in(phonenumber, input('Enter the code: '))
                    client.send_code_request(phonenumber)
                    print("sent code")
                    return render_template("codeinput.html")
                channel_entity = client.get_entity(channelname)
                members = client.get_participants(channel_entity)
                printmemberattr(members)
                print(members)
                for member in members:
                    listtoexportcsv.append(
                        [member.id, member.username, member.phone])
                return render_template("result.html", members=members)
            else:
                print("upload file users and add to telegram channel")
                channeltoadd = request.form.get('channeltoadd')
                inputdict['channeltoadd'] = channeltoadd
                if channeltoadd == "":
                    print("không nhập thông tin channel")
                    return render_template("error.html")
                else:
                    print("start to get file name")
                    file = request.files['file']
                    filename = secure_filename(file.filename)
                    print(filename)

                    # os.path.join is used so that paths work in every operating system
                    file.save(os.path.join("/root/nammuoi", filename))
                    with open("/root/nammuoi/" + filename) as f:
                        for line in f:
                            file_content.append(line)

                    if not client.is_user_authorized():
                        client.send_code_request(phonenumber)
                        print("sent code to phone")
                        return render_template("adduserscodeinput.html")

        # You should use os.path.join here too.

                    try:
                        _thread.start_new_thread(
                            addUserFromFileToChannel,
                            (file_content, client, channeltoadd))
                    except:
                        print("Error: unable to start thread")
                    return render_template("success.html")

        except Exception as e:
            print(e)
            return render_template("error.html")
예제 #29
0
#dialogs = client.get_dialogs()
dialogs = {d.name: d.entity for d in client.get_dialogs()}

# get all the users and print them
#for u in client.get_participants(dialogs[3].entity,limit=0):
#    print(u.id, u.first_name, u.last_name, u.username, u.access_hash)

#for u in client.get_participants(channel):
#    print(u.id, u.first_name, u.last_name, u.username, u.access_hash)

#for i in channels:
#    print(i)

#for u in dialogs:
#    print(u)

for u in dialogs:
    print(u)
#for u in dialogs:
#    print(u.name)

#print(dialogs[3])

#for u in client.get_participants(dialogs[3].entity,aggressive=True):
#    print(u.username, u.first_name, u.last_name, u.username, u.id, u.access_hash)

print(client.get_participants(dialogs[groupname], limit=0).total)
#print(dialogs['Comando e Controle'])
print(dialogs[groupname])
client.disconnect()
예제 #30
0
# with TelegramClient('anon', api_id, api_hash) as client:
# class telegram_client:
# 	def __init__(self, id, username, fname, lname, phone, status):
# 		self.id = id
# 		self.username = username
# 		self.fname = fname
# 		self.lname = lname
# 		self.phone = phone
# 		self.status = status

client = TelegramClient('anon', api_id, api_hash).start()
add = []

# participants = client.get_participants('DbFirReRnqxjYpQlwJRQuw')

users = client.get_participants('AudiosdeMarcuxx')
# print(len(users))
# t1 = telegram_client(users[0].id, users[0].username, users[0].first_name, users[0].last_name, users[0].phone, 0)
# t1 = (users[0].id, users[0].username, users[0].first_name, users[0].last_name, users[0].phone, 0)
# print(t1)
# add.append(t1)
# print(add[0].__dict__)
# t2 = (users[1].id, users[1].username, users[1].first_name, users[1].last_name, users[1].phone, 0)
# add.append(t2)
# print(add)
###for u in users:
# t = (str(u.id), u.username, u.first_name, u.last_name, u.phone, 0, )
# add.append(t)

# db.insertGroup(add)
# print(add)