Example #1
0
def script_work():
    global client
    session_path = "./sessions/{}".format(username)
    if telethon_proxy is not None:
        proxy = (telethon_proxy["host"], telethon_proxy["port"],
                 telethon_proxy["secret"])
        admin_client = TelegramClient(
            session_path,
            api_id,
            api_hash,
            proxy=proxy,
            connection=connection.tcpmtproxy.ConnectionTcpMTProxyIntermediate)
    else:
        admin_client = TelegramClient(session_path, api_id, api_hash)
    client = admin_client

    with admin_client as client:
        admin_client.get_entity("ChatWarsDigest")
        admin_client.get_entity("ChatWarsBot")
        client.add_event_handler(stats_handler, event=events.NewMessage)
        print("telegram script launched")
        loop = asyncio.get_event_loop()
        try:
            loop.run_until_complete(client.disconnected)
        except KeyboardInterrupt:
            pass
Example #2
0
def JoinOrLeave(option: bool):
    cards = CreateSimList()
    i = 0
    print(f"Number of sim cards before: {len(cards)}")
    while i < len(cards):
        try:
            sim = cards[i]
            client = TelegramClient(sim.phone, sim.ID, sim.access_hash)
            client.connect()

            if option:
                client(JoinChannelRequest(client.get_entity(target_link)))
                print(Fore.GREEN + f"{sim.name} Has Joined!")
            else:
                client(LeaveChannelRequest(client.get_entity(target_link)))
                print(Fore.GREEN + f"{sim.name} Has Left!")
            i += 1

        except (PhoneNumberBannedError, UserBannedInChannelError,
                UserDeactivatedBanError) as ex:
            print(Fore.BLACK + f"SIM {sim.name} GOT {type(ex).__name__}!")
            cards.remove(sim)

        except UserNotParticipantError:
            i += 1

        finally:
            sleep(2)
            client.disconnect()
            del client

    print(f"Number of sim cards after: {len(cards)}")
    CloseSimList(cards)  # clean the bans and close the file
Example #3
0
def script_work():
    global client
    admin_client = TelegramClient(username, api_id, api_hash)
    admin_client.start(phone, password)

    with admin_client as client:
        admin_client.get_entity("ChatWarsBot")
        client.add_event_handler(stats_handler, event=events.NewMessage)
        print("telegram script launched")

        admin_client.run_until_disconnected()
Example #4
0
def Init():
    print("Getting sim card list.. ")
    sim_cards = CreateSimList()

    main_phone = sim_cards[0]
    print(f"Connecting to main phone: {main_phone.name}")
    first_client = TelegramClient(main_phone.phone, main_phone.ID,
                                  main_phone.access_hash)
    first_client.connect()

    print("Getting group entities..")
    scrape_group = first_client.get_entity(scrape_link)
    first_client(JoinChannelRequest(scrape_group))
    target_group_entity = first_client.get_entity(target_link)
    target_id = target_group_entity.id

    print("Scraping group lists..")
    scrape_participants = first_client.get_participants(scrape_group,
                                                        aggressive=True)
    target_participants = first_client.get_participants(target_group_entity,
                                                        aggressive=True)

    filtered_participants = []
    final_participants = []

    print("Filtering From Groups..")
    for user in scrape_participants:
        if user.username is not None and not user.bot:  # if has a username and not a bot
            if not user.deleted:  # if it isn't a deleted account
                if hasattr(
                        user.status, 'was_online'
                ) and start_date < user.status.was_online < end_date:
                    filtered_participants.append(user)
                elif type(user.status) == UserStatusOnline or type(
                        user.status) == UserStatusRecently:
                    filtered_participants.append(user)

    for user1 in filtered_participants:
        flag = True
        for user2 in target_participants:
            if user1.id == user2.id:
                flag = False
        if flag:
            final_participants.append(user1)

    first_client.disconnect()
    del first_client

    return sim_cards, final_participants, target_id
Example #5
0
def script_work():
    global client
    global loop
    loop = asyncio.get_event_loop()
    admin_client = TelegramClient(username, api_id, api_hash)
    admin_client.start(phone, password)
    with admin_client as client:
        client = admin_client
        admin_client.get_entity("ChatWarsBot")
        start_updating()
        start_countdown()

        print("started timer")
        #timer = Timer(interval=5, function=update_guild_stats, args=[client, True]).start()

        admin_client.run_until_disconnected()
Example #6
0
class client:
    def __init__(self, session, api_id, api_hash):
        self.client = TelegramClient(session, api_id, api_hash)
        self.client.start()

    def scrape(self, chat, from_peer, limit, filter, offset_date=datetime.now()): #set limit under 2000 to avoid hitting flood wait
        global Filter
        chat_entity = self.client.get_entity(chat)
        from_peer_entity = self.client.get_entity(from_peer)
        
        for i in range(math.ceil(limit/100)):
            try: 
                total = self.client.get_messages(from_peer_entity, limit=100, offset_date=offset_date, filter=Filter[filter])
                self.client.forward_messages(chat_entity, total)
                print(total[-1].date)
            except FloodWaitError as e:
                print(e)
                wait_time = int(re.findall('\d+',str(e))[0])
                time.sleep(wait_time)
                continue
Example #7
0
def sendfile(filepath):
    if not SESSION_STRING:
        client = TelegramClient('bot_name', API_ID,
                                API_HASH).start(bot_token=BOT_TOKEN)
    else:
        client = TelegramClient(StringSession(SESSION_STRING), API_ID,
                                API_HASH)
        client.connect()

    receiver1 = client.get_entity(RECEIVER_USERNAME)
    client.send_file(receiver1, filepath)
    client.disconnect()
Example #8
0
def message_curr_strength(fname):
    api_id = 1433030
    api_hash = '33fa8cdfd1b35e902e6118b6abbf3726'
    token = '1315998116:AAF8A-WBdojAJMtp75o_zb3xcIykIX9bh_g'

    phone_num = '+639267415427'

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

    client.connect()

    if not client.is_user_authorized():
        client.send_code_request(phone_num)
        client.sign_in(phone_num, input('Enter the code: '))

    destination_group = 'https://t.me/joinchat/TwIbzlVqFT986_g0-Dai_A'
    peer = client.get_entity(destination_group)

    time = pd.to_datetime('now').strftime('%Y-%m-%d %H:%M')

    client.send_message(entity=peer,
                        message='Currency Strength Bar {}'.format(time),
                        parse_mode='html')
    client.send_file(entity=peer, file=fname)

    strength_values = ''
    with open('currStrengthOutputs/currStrengthValues.txt', 'r') as f:
        for line in f:
            strength_values += line

    tradable_pairs = ''
    with open('currStrengthOutputs/tradeableCurrPair.txt', 'r') as f:
        for line in f:
            tradable_pairs += line

    client.send_message(entity=peer,
                        message='Currency Strength Values',
                        parse_mode='html')
    client.send_message(entity=peer,
                        message=strength_values,
                        parse_mode='html')

    client.send_message(entity=peer,
                        message='Tradable Pairs and Difference',
                        parse_mode='html')
    client.send_message(entity=peer, message=tradable_pairs, parse_mode='html')

    client.disconnect()

    return None
Example #9
0
def script_work():
    global client
    session_path = "./sessions/{}".format(username)
    if telethon_proxy is not None:
        proxy = (telethon_proxy["host"], telethon_proxy["port"],
                 telethon_proxy["secret"])
        admin_client = TelegramClient(
            session_path,
            api_id,
            api_hash,
            proxy=proxy,
            connection=connection.tcpmtproxy.ConnectionTcpMTProxyIntermediate)
    else:
        admin_client = TelegramClient(session_path, api_id, api_hash)
    # admin_client.start(phone, password)
    #
    # client = admin_client
    with admin_client as client:
        admin_client.get_entity("ChatWarsBot")
        client.add_event_handler(stats_handler, event=events.NewMessage)
        print("telegram script launched")

        admin_client.run_until_disconnected()
Example #10
0
def add_user_to_channel(client: TelegramClient, user: types.User, channel) -> bool:
    # Get user entity from channel participants list
    users = list(filter(
        lambda u: u.id == user.id,
        client.get_participants(channel, search=utils.get_display_name(user))
    ))
    
    if users:
        status = "Already"


    else:
        try:
            client(channels.InviteToChannelRequest(
                channel,
                [ user ]
            ))

            status = "Done"

        except errors.FloodWaitError as e:
            status = f"Wait {e.seconds} seconds. Skipped!"

        except errors.RPCError as e:
            status = e.__class__.__name__

        except:
            status = "UnexpectedError"
            traceback.print_exc()


    channel_entity = client.get_entity(channel)
    print_output(client, channel_entity, user, status)

    if status in [
        "Done",
        "Already",
        "UserChannelsTooMuchError",
        "UsersTooMuchError",
	    "UserNotMutualContactError",
	    "UserKickedError",
        "UserBannedInChannelError",
        "ChatAdminRequiredError",
        "UserPrivacyRestrictedError"
    ]:
        return True
    else:
        return False
Example #11
0
users = []
with open(file, encoding='UTF-8') as f:
    rows = csv.reader(f, delimiter=',', lineterminator='\n')
    next(rows, None)
    for row in rows:
        user = {}
        user['username'] = row[0]
        user['user_id'] = row[1]
        user['access_hash'] = row[2]
        user['group'] = row[3]
        user['group_id'] = row[4]
        users.append(user)
client = TelegramClient(f'sessions\\{phone}', api_id, api_hash)
client.connect()
time.sleep(1.5)
target_group = client.get_entity(group)
entity = InputPeerChannel(target_group.id, target_group.access_hash)
group_name = target_group.title
print(f'{info}{g} Adding members to {group_name}{rs}\n')
n = 0
added_users = []
for user in users:
    n += 1
    added_users.append(user)
    if n % 50 == 0:
        print(f'{sleep}{g} Sleep 2 min to prevent possible account ban{rs}')
        time.sleep(120)
    try:
        if user['username'] == "":
            continue
        user_to_add = client.get_input_entity(user['username'])
Example #12
0
dir_buffer_images = f"{dir_buffer}/video_decompose"

for path in [
        config['gif_channel'], dir_video, dir_images, dir_buffer,
        dir_buffer_video, dir_buffer_images
]:
    if not os.path.exists(path):
        os.mkdir(path)

# # # Download missing videos from gif channel
print("Download missing videos from gif channel")
client = TelegramClient('duplicate_checker', config['api_id'],
                        config['api_hash'])
client.start()
channel_username = config['gif_channel']
channel_entity = client.get_entity(channel_username)
for message in client.iter_messages(channel_entity):
    if message.file is None:
        # print(f"No file, skipping message: {message}")
        continue
    file_ext = message.file.mime_type.split("/")[-1]
    path = f"{dir_video}/{str(message.id).zfill(4)}.{file_ext}"
    if not os.path.exists(path):
        print("Downloading message: {}".format(message))
        client.download_media(message=message, file=path)

# # # Decompose missing videos
print("Decompose missing videos")
video_files = glob.glob(f"{dir_video}/*.mp4")
for video_file in video_files:
    video_number = video_file.split(os.sep)[-1].split(".")[0]
Example #13
0
from telethon.sync import TelegramClient
from telemongo import MongoSession
import mongoengine
import os
from decouple import config
import wget
host = os.getenv('MONGODB_HOST', config('MONGODB_HOST'))
mongoengine.connect(os.getenv('MONGODB_DATABASE', config('MONGODB_DATABASE')),
                    host=host)
session = MongoSession(os.getenv('MONGODB_DATABASE',
                                 config('MONGODB_DATABASE')),
                       host=host)
api_id = os.getenv('TELEGRAM_API_ID', config('TELEGRAM_API_ID'))
api_hash = os.getenv('TELEGRAM_API_HASH', config('TELEGRAM_API_HASH'))
client = TelegramClient(session, api_id, api_hash)
client.connect()
lonami = client.get_entity(os.getenv('SEND_TO', config('SEND_TO')))
wget.download(
    "https://github.com/spiritbro1/covid-19-api/releases/download/saved_data/og.png",
    out="panda.jpg")
client.send_file(lonami.id, 'panda.jpg', caption="PLEASE STAY HOMEEEEEEEEEEE")
import json

from telethon.sync import TelegramClient

with open("config.json", "r") as f:
    config = json.load(f)

directory = "video_download"
# These example values won't work. You must get your own api_id and
# api_hash from `my.telegram.org` , under API Development.
api_id = config['API_ID']
api_hash = config['API_HASH']
client = TelegramClient('deer_gifs_downloader', api_id, api_hash)
client.start()
# print(client.get_me())

channel_username = '******'
channel_entity = client.get_entity(channel_username)
for message in client.iter_messages(channel_entity):
    if message.file is None:
        print(f"No file, skipping message: {message}")
        continue
    print("Downloading message: {}".format(message))
    file_ext = message.file.mime_type.split("/")[-1]
    path = f"{directory}/{message.id}.{file_ext}"
    client.download_media(message=message, file=path)
Example #15
0
def e():
    try:
        r = c.RawConfigParser()  #Read Group Keys
        r.read('degerler.veri')
        cfg = r['veri']['config_no']
        group_username = r['veri']['kanal_grup_adi']
        ags = r['veri']['aktif_gun_sayisi']
        bsk = r['veri']['beklenicek_sure_kucuk']
        bsb = r['veri']['beklenicek_sure_buyuk']
        intags = int(ags)
        intbsk = int(bsk)
        intbsb = int(bsb)
        cpass = c.RawConfigParser()
        cpass.read(cfg)
    except:
        print("Something is wrong with degerler.veri!!")
    try:
        id = cpass['cred']['id']
        h = cpass['cred']['hash']
        p = cpass['cred']['phone']
        client = TelegramClient(p, id, h)
    except KeyError:
        print("[!] Api access id phone or hash is not correct!!\n")
        sys.exit(1)
    client.connect()
    if not client.is_user_authorized():
        client.send_code_request(p)
        client.sign_in(p, input('[+] Enter code sent from telegram : '))
    client(JoinChannelRequest(channel=group_username))
    chats = []
    last_date = None
    chunk_size = 200
    groups = []
    result = client(
        GetDialogsRequest(offset_date=last_date,
                          offset_id=0,
                          offset_peer=InputPeerEmpty(),
                          limit=chunk_size,
                          hash=0))
    chats.extend(result.chats)
    for chat in chats:
        try:
            check = client.get_entity(group_username)
            if check.id == chat.id:
                groups.append(chat)
        except:
            continue
    i = 0
    for group in groups:
        print('[' + str(i) + ']' '-' + group.title)
        i += 1
    g_index = 0
    aktif_gun_sayisi = intags
    target_group = groups[int(g_index)]
    all_participants = []
    time.sleep(random.randrange(11, 23))
    all_participants = client.get_participants(
        target_group
    )  #patched because telegram seems to ban while using it! , aggressive=True)
    with open("users.nya", "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:
            #contacts = client(GetContactsRequest(0))
            #client(AddChatUserRequest(chat_id=chat.id,user_id=user.id,fwd_limit=10))
            accept = True
            try:
                lastDate = user.status.was_online
                ay_kontrolu = (datetime.now().month - lastDate.month)
                gun_kontrolu = (datetime.now().day - lastDate.day)
                if (ay_kontrolu > 0 or gun_kontrolu > aktif_gun_sayisi
                        or datetime.now().year != lastDate.year):
                    accept = False
            except:
                pass
            if (accept):
                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 = ""
                name = (first_name + ' ' + last_name).strip()
                writer.writerow([
                    username, user.id, user.access_hash, name,
                    target_group.title, target_group.id
                ])
    client(LeaveChannelRequest(channel=group_username))
    os._exit(1)
Example #16
0
    for row in rows:
        user = {}
        user['username'] = row[0]
        user['id'] = int(row[1])
        user['access_hash'] = row[2]
        user['group'] = row[3]
        user['group_id'] = row[4]
        users.append(user)
    f.close()
f = open('resume.txt', 'r')
scraped = f.readline()
f.close()
tg_group = str(input(f'{INPUT}{g} Enter group username to add[Without @]: '))
group = 't.me/' + tg_group
time.sleep(1.5)
target_group = client.get_entity(group)
entity = InputPeerChannel(target_group.id, target_group.access_hash)
group_name = target_group.title
n = 0
print(f'{info}{g} Getting entities{rs}\n')
target_m = client.get_entity(scraped)
client.get_participants(target_m, aggressive=True)
print(f'{info}{g} Adding members to {group_name}{rs}\n')
added_users = []
for user in users:
    added_users.append(user)
    n += 1
    if n % 50 == 0:
        print(f'{sleep}{g} Sleep 2 min to prevent possible account ban{rs}')
        time.sleep(120)
    try:
def ekle():
	nya = c.RawConfigParser() #Grup keylerini oku
	nya.read('degerler.veri')
	cfg = nya['veri'] ['config_no']
	satno = nya['veri'] ['satir_no']
	kissay = nya['veri'] ['kisi_sayisi']
	group_username = nya['veri'] ['kanal_grup_adi']
	ags = nya['veri'] ['aktif_gun_sayisi']
	bsk = nya['veri'] ['beklenicek_sure_kucuk']
	bsb = nya['veri'] ['beklenicek_sure_buyuk']
	intsatno = int(satno)
	intkissay = int(kissay)
	intags = int(ags)
	intbsk = int(bsk)
	intbsb = int(bsb)
	cpass = c.RawConfigParser()
	cpass.read(cfg)
	try:
		api_id = cpass['cred']['id']
		api_hash = cpass['cred']['hash']
		phone = cpass['cred']['phone']
		client = TelegramClient(phone, api_id, api_hash)
	except KeyError:
		sys.exit(1)
	client.connect()
	if not client.is_user_authorized():
		client.send_code_request(phone)
		os.system('cls')
		client.sign_in(phone, input('[+] Enter the code telegram send : '))
	client(JoinChannelRequest(channel=group_username))
	os.system('cls')
	users = []
	with open("grup_uyeleri.csv","r", encoding='UTF-8') as fd:
		rows = csv.reader(fd,delimiter=",",lineterminator="\n")
		for row in islice(csv.reader(fd),intsatno,None):
			user = {}
			user['username'] = row[0]
			user['id'] = int(row[1])
			user['access_hash'] = int(row[2])
			user['name'] = row[3]
			users.append(user)
	chats = []
	last_date = None
	chunk_size = 200
	groups=[]
	result = client(GetDialogsRequest(
             offset_date=last_date,
             offset_id=0,
             offset_peer=InputPeerEmpty(),
             limit=chunk_size,
             hash = 0
         ))
	chats.extend(result.chats)
	for chat in chats:
		try:
			check=client.get_entity(group_username)
			if check.id==chat.id:
				groups.append(chat)
		except:
			continue
	i=0
	for group in groups:
		print('['+str(i)+']' '-' +group.title)
		i+=1
	g_index=0
	target_group=groups[int(g_index)]
	target_group_entity = InputPeerChannel(target_group.id,target_group.access_hash)
	mode=1
	max_user_to_add=0
	for user in users:
			try:
				max_user_to_add+=1
				if max_user_to_add==intkissay:
					client(LeaveChannelRequest(channel=group_username))
					os._exit(1)
				print (phone+" Kullanici ekleniyor {}".format(user['id']))
				if mode == 1:
					if user['username'] == "":
						continue
					user_to_add = client.get_input_entity(user['username'])
				elif mode == 2:
					user_to_add = InputPeerUser(user['id'], user['access_hash'])
				else:
					sys.exit("[!] Gecersiz secenek secildi. Tekrar dene.")
				try:
					client(InviteToChannelRequest(target_group_entity,[user_to_add]))
					print("[+] Rastgele "+intbsk+" ila "+intbsb+" sn bekleniyor.")
					time.sleep(random.randrange(intbsk,intbsb))
				except:
					traceback.print_exc()
					print("[+] HATA Rastgele 11 ila 23 sn bekleniyor.")
					time.sleep(random.randrange(11,23))
					continue
			except PeerFloodError:
				print("[!] Telegrama fazla istek attigimiz icin hatayla karsilastik. Bot Durduruldu.")
				while(True):
					time.sleep(random.randrange(11,23))
			except UserPrivacyRestrictedError:
				print("[!] Kullanicinin gizlilik ayarlari yuzunden eklenemedi. Atlaniyor.")
				time.sleep(random.randrange(11,23))
				max_user_to_add-=1
			except UserNotMutualContactError:
				print("[!] User not mutual contact hatasi alindi. Devam ediliyor.")
				time.sleep(random.randrange(12,22))
				max_user_to_add-=1
			except UserKickedError:
				print("[!] Bu kullanici bu grupdan daha once atilmis. Atlaniyor.")
				time.sleep(random.randrange(9,21))
				max_user_to_add-=1
			except:
				traceback.print_exc()
				print("[!] Beklenmeyen Hata")
				time.sleep(random.randrange(14,25))
				max_user_to_add-=1
				continue
Example #18
0
client = TelegramClient(phone, api_id, api_hash)
client.connect()
if not client.is_user_authorized():
    try:
        client.send_code_request(phone)
        code = input(f'{INPUT}{lg} Enter the code for {phone}{r}: ')
        client.sign_in(phone, code)
    except PhoneNumberBannedError:
        print(f'{error}{r}{phone} is banned!{rs}')
        print(f'{error}{r} Run manager.py to filter them{rs}')
        sys.exit()
username = input(
    f'{INPUT}{lg} Enter the exact username of the public group[Without @]: {r}'
)
target_grp = 't.me/' + str(username)
group = client.get_entity(target_grp)
time = datetime.datetime.now().strftime("%H:%M")
print('\n' + info + lg + ' Started on ' + str(time) + rs)
print(f'{info}{lg} Scraping members from {rs}' + str(group.title))
members = []
members = client.get_participants(group, aggressive=True)
print(f'{info}{lg} Saving in members.csv...{rs}')
select = str(input(f'{INPUT}{lg} Do you wanna filter active users?[y/n]: '))
with open("members.csv", "w", encoding='UTF-8') as f:
    writer = csv.writer(f, delimiter=",", lineterminator="\n")
    writer.writerow(
        ['username', 'user id', 'access hash', 'group', 'group id'])
    if select == 'y':
        for member in members:
            accept = True
            if not member.status == UserStatusRecently():
Example #19
0
import telebot
from dependency import token, api_id, api_hash, passwordFor2Factor
from telethon.sync import TelegramClient
from telethon import functions


bot = telebot.TeleBot(token)
client = TelegramClient('telegramOsint', api_id, api_hash)
client.start(password=passwordFor2Factor)
contact_phone_number = str(sys.argv[1])
chatId = sys.argv[2]
contact = InputPhoneContact(client_id=0, phone=contact_phone_number, first_name="", last_name="")
result = client(ImportContactsRequest(contacts=[contact]))
res = []
try:
    contact_info = client.get_entity(contact_phone_number)
    res.append(contact_info.phone)
    result = client(functions.contacts.DeleteContactsRequest(
        id=[contact_info.id]
    ))
    contact_info = result.users[0]
    res.append(contact_info.id)
    if contact_info.username is not None: res.append( "@" + contact_info.username)
    else: res.append(contact_info.username)
    res.append(contact_info.first_name)
    res.append(contact_info.last_name)
    res.append(contact_info.lang_code)
    if hasattr(contact_info.status, "was_online"):
        res.append(contact_info.status.was_online.astimezone(pytz.timezone('Europe/Kiev')))
    elif str(contact_info.status) == "UserStatusRecently()":
        res.append("Статус скрыт")
Example #20
0
class Sync:
    """
    Sync iterates and receives messages from the Telegram group to the
    local SQLite DB.
    """
    config = {}
    db = None

    def __init__(self, config, session_file, db):
        self.config = config
        self.db = db

        self.client = TelegramClient(session_file, self.config["api_id"],
                                     self.config["api_hash"])
        self.client.start()

        if not os.path.exists(self.config["media_dir"]):
            os.mkdir(self.config["media_dir"])

    def sync(self, ids=None):
        """
        Sync syncs messages from Telegram from the last synced message
        into the local SQLite DB.
        """

        if ids:
            last_id, last_date = (ids, None)
        else:
            last_id, last_date = self.db.get_last_message_id()

        if ids:
            logging.info("fetching message id={}".format(ids))
        elif last_id:
            logging.info("fetching from last message id={} ({})".format(
                last_id, last_date))

        group_id = self._get_group_id(self.config["group"])

        n = 0
        while True:
            has = False
            for m in self._get_messages(group_id,
                                        offset_id=last_id if last_id else 0,
                                        ids=ids):
                if not m:
                    continue

                has = True

                # Inser the records into DB.
                self.db.insert_user(m.user)

                if m.media:
                    self.db.insert_media(m.media)

                self.db.insert_message(m)

                last_date = m.date
                n += 1
                if n % 300 == 0:
                    logging.info("fetched {} messages".format(n))
                    self.db.commit()

                if self.config["fetch_limit"] > 0 and n >= self.config[
                        "fetch_limit"] or ids:
                    has = False
                    break

            self.db.commit()
            if has:
                last_id = m.id
                logging.info(
                    "fetched {} messages. sleeping for {} seconds".format(
                        n, self.config["fetch_wait"]))
                time.sleep(self.config["fetch_wait"])
            else:
                break

        self.db.commit()
        logging.info("finished. fetched {} messages. last message = {}".format(
            n, last_date))

    def _get_messages(self, group, offset_id, ids=None) -> Message:
        # https://docs.telethon.dev/en/latest/quick-references/objects-reference.html#message
        for m in self.client.get_messages(
                group,
                offset_id=offset_id,
                limit=self.config["fetch_batch_size"],
                ids=ids,
                reverse=True):

            if not m or not m.sender:
                continue

            # Media.
            sticker = None
            med = None
            if m.media:
                # If it's a sticker, get the alt value (unicode emoji).
                if isinstance(m.media, telethon.tl.types.MessageMediaDocument) and \
                        hasattr(m.media, "document") and \
                        m.media.document.mime_type == "application/x-tgsticker":
                    alt = [
                        a.alt for a in m.media.document.attributes
                        if isinstance(
                            a, telethon.tl.types.DocumentAttributeSticker)
                    ]
                    if len(alt) > 0:
                        sticker = alt[0]
                elif isinstance(m.media, telethon.tl.types.MessageMediaPoll):
                    med = self._make_poll(m)
                else:
                    med = self._get_media(m)

            # Message.
            typ = "message"
            if m.action:
                if isinstance(m.action,
                              telethon.tl.types.MessageActionChatAddUser):
                    typ = "user_joined"
                elif isinstance(m.action,
                                telethon.tl.types.MessageActionChatDeleteUser):
                    typ = "user_left"

            yield Message(type=typ,
                          id=m.id,
                          date=m.date,
                          edit_date=m.edit_date,
                          content=sticker if sticker else m.raw_text,
                          reply_to=m.reply_to_msg_id if m.reply_to
                          and m.reply_to.reply_to_msg_id else None,
                          user=self._get_user(m.sender),
                          media=med)

    def _get_user(self, u) -> User:
        tags = []
        is_normal_user = isinstance(u, telethon.tl.types.User)

        if is_normal_user:
            if u.bot:
                tags.append("bot")

        if u.scam:
            tags.append("scam")

        if u.fake:
            tags.append("fake")

        # Download sender's profile photo if it's not already cached.
        avatar = None
        if self.config["download_avatars"]:
            try:
                fname = self._download_avatar(u)
                avatar = fname
            except Exception as e:
                logging.error("error downloading avatar: #{}: {}".format(
                    u.id, e))

        return User(id=u.id,
                    username=u.username if u.username else str(u.id),
                    first_name=u.first_name if is_normal_user else None,
                    last_name=u.last_name if is_normal_user else None,
                    tags=tags,
                    avatar=avatar)

    def _make_poll(self, msg):
        options = [{
            "label": a.text,
            "count": 0,
            "correct": False
        } for a in msg.media.poll.answers]

        total = msg.media.results.total_voters
        if msg.media.results.results:
            for i, r in enumerate(msg.media.results.results):
                options[i]["count"] = r.voters
                options[i][
                    "percent"] = r.voters / total * 100 if total > 0 else 0
                options[i]["correct"] = r.correct

        return Media(id=msg.id,
                     type="poll",
                     url=None,
                     title=msg.media.poll.question,
                     description=json.dumps(options),
                     thumb=None)

    def _get_media(self, msg):
        if isinstance(msg.media, telethon.tl.types.MessageMediaWebPage) and \
                not isinstance(msg.media.webpage, telethon.tl.types.WebPageEmpty):
            return Media(id=msg.id,
                         type="webpage",
                         url=msg.media.webpage.url,
                         title=msg.media.webpage.title,
                         description=msg.media.webpage.description
                         if msg.media.webpage.description else None,
                         thumb=None)
        elif isinstance(msg.media, telethon.tl.types.MessageMediaPhoto) or \
                isinstance(msg.media, telethon.tl.types.MessageMediaDocument) or \
                isinstance(msg.media, telethon.tl.types.MessageMediaContact):
            if self.config["download_media"]:
                logging.info("downloading media #{}".format(msg.id))
                try:
                    basename, fname, thumb = self._download_media(msg)
                    return Media(id=msg.id,
                                 type="photo",
                                 url=fname,
                                 title=basename,
                                 description=None,
                                 thumb=thumb)
                except Exception as e:
                    logging.error("error downloading media: #{}: {}".format(
                        msg.id, e))

    def _download_media(self, msg) -> [str, str, str]:
        """
        Download a media / file attached to a message and return its original
        filename, sanitized name on disk, and the thumbnail (if any). 
        """
        # Download the media to the temp dir and copy it back as
        # there does not seem to be a way to get the canonical
        # filename before the download.
        fpath = self.client.download_media(msg, file=tempfile.gettempdir())
        basename = os.path.basename(fpath)

        newname = "{}.{}".format(msg.id, self._get_file_ext(basename))
        shutil.move(fpath, os.path.join(self.config["media_dir"], newname))

        # If it's a photo, download the thumbnail.
        tname = None
        if isinstance(msg.media, telethon.tl.types.MessageMediaPhoto):
            tpath = self.client.download_media(msg,
                                               file=tempfile.gettempdir(),
                                               thumb=1)
            tname = "thumb_{}.{}".format(
                msg.id, self._get_file_ext(os.path.basename(tpath)))
            shutil.move(tpath, os.path.join(self.config["media_dir"], tname))

        return basename, newname, tname

    def _get_file_ext(self, f) -> str:
        if "." in f:
            e = f.split(".")[-1]
            if len(e) < 6:
                return e

        return ".file"

    def _download_avatar(self, user):
        fname = "avatar_{}.jpg".format(user.id)
        fpath = os.path.join(self.config["media_dir"], fname)

        if os.path.exists(fpath):
            return fname

        logging.info("downloading avatar #{}".format(user.id))

        # Download the file into a container, resize it, and then write to disk.
        b = BytesIO()
        self.client.download_profile_photo(user, file=b)

        im = Image.open(b)
        im.thumbnail(self.config["avatar_size"], Image.ANTIALIAS)
        im.save(fpath, "JPEG")

        return fname

    def _get_group_id(self, group):
        """
        Syncs the Entity cache and returns the Entity ID for the specified group,
        which can be a str/int for group ID, group name, or a group username.

        The authorized user must be a part of the group.
        """
        # Get all dialogs for the authorized user, which also
        # syncs the entity cache to get latest entities
        # ref: https://docs.telethon.dev/en/latest/concepts/entities.html#getting-entities
        _ = self.client.get_dialogs()

        try:
            # If the passed group is a group ID, extract it.
            group = int(group)
        except ValueError:
            # Not a group ID, we have either a group name or
            # a group username: @group-username
            pass

        try:
            entity = self.client.get_entity(group)
        except ValueError:
            logging.critical(
                "the group: {} does not exist,"
                " or the authorized user is not a participant!".format(group))
            # This is a critical error, so exit with code: 1
            exit(1)

        return entity.id
Example #21
0
def kaydet():
    nya = c.RawConfigParser()  #Grup keylerini oku
    nya.read('degerler.veri')
    cfg = nya['veri']['config_no']
    satno = nya['veri']['satir_no']
    kissay = nya['veri']['kisi_sayisi']
    group_username = nya['veri']['kanal_grup_adi']
    ags = nya['veri']['aktif_gun_sayisi']
    bsk = nya['veri']['beklenicek_sure_kucuk']
    bsb = nya['veri']['beklenicek_sure_buyuk']
    intsatno = int(satno)
    intkissay = int(kissay)
    intags = int(ags)
    intbsk = int(bsk)
    intbsb = int(bsb)
    cpass = c.RawConfigParser()
    cpass.read(cfg)
    try:
        api_id = cpass['cred']['id']
        api_hash = cpass['cred']['hash']
        phone = cpass['cred']['phone']
        client = TelegramClient(phone, api_id, api_hash)
    except KeyError:
        os.system('cls')
        print("[!] Gereklilikler yuklu degil. !!\n")
        sys.exit(1)
    client.connect()
    if not client.is_user_authorized():
        client.send_code_request(phone)
        client.sign_in(phone, input('[+] Telegramdan gelen kodu gir : '))
    client(JoinChannelRequest(channel=group_username))
    chats = []
    last_date = None
    chunk_size = 200
    groups = []
    result = client(
        GetDialogsRequest(offset_date=last_date,
                          offset_id=0,
                          offset_peer=InputPeerEmpty(),
                          limit=chunk_size,
                          hash=0))
    chats.extend(result.chats)
    for chat in chats:
        try:
            check = client.get_entity(group_username)
            if check.id == chat.id:
                groups.append(chat)
        except:
            continue
    i = 0
    for group in groups:
        print('[' + str(i) + ']' '-' + group.title)
        i += 1
    g_index = 0
    aktif_gun_sayisi = intags
    target_group = groups[int(g_index)]
    all_participants = []
    all_participants = client.get_participants(target_group, aggressive=True)
    with open("grup_uyeleri.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:
            accept = True
            try:
                lastDate = user.status.was_online
                ay_kontrolu = (datetime.now().month - lastDate.month)
                gun_kontrolu = (datetime.now().day - lastDate.day)
                if (ay_kontrolu > 0 or gun_kontrolu > aktif_gun_sayisi
                        or datetime.now().year != lastDate.year):
                    accept = False
            except:
                continue
            if (accept):
                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 = ""
                name = (first_name + ' ' + last_name).strip()
                writer.writerow([
                    username, user.id, user.access_hash, name,
                    target_group.title, target_group.id
                ])
    client(LeaveChannelRequest(channel=group_username))
    os._exit(1)
Example #22
0
import asyncio
from decouple import config

# Defining the need variables
api_id = config('API_ID')  #Input your api_id here
api_hash = config('API_HASH')  #Input your api_hash here

loop = asyncio.new_event_loop()
client = TelegramClient('runner', api_id, api_hash, loop=loop)
client.start()

channel = client.get_input_entity('https://t.me/techguided')

chat = InputPeerChannel(
    channel_id=channel.channel_id,
    access_hash=channel.access_hash)  # Input channel id and access_hash

# import pdb; pdb.set_trace()
channel = client.get_entity(1270515419)


# Handler to receive the channel message
@client.on(events.NewMessage(incoming=True))
async def handler(event):
    await client.send_message('codefred', f'{event.stringify()}')


client.add_event_handler(handler)

# Run endlessly
client.run_until_disconnected()
# ask either to input token or otp sent to
# number or sent or your telegram id
if not client.is_user_authorized():

    #client.send_code_request(phone, force_sms=True)
    client.send_code_request(phone)
    # signing in the client
    client.sign_in(phone, input('Enter the code: '))

#user_to_patovear_Name = "@AAAAAAAA"
#user_to_patovear_Entity = client.get_entity(user_to_patovear_Name)

user_to_patovear_Name = "patovagroup"
#chat_url = "https://t.me/joinchat/11111111111111111111111111"
chat_url = "https://t.me/MYGROUP"
channel_entity = client.get_entity(chat_url)
#user_to_patovear_Name = "111111111111111111"

message = "Test de Nico - Patova_Bot"

try:
    # receiver user_id and access_hash, use
    # my user_id and access_hash for reference
    #receiver = InputPeerUser(user_to_patovear_Name, user_to_patovear_Hash)

    # sending message using telegram client
    client.send_message(entity=user_to_patovear_Entity, message=message)
except Exception as e:

    # there may be many error coming in while like peer
    # error, wwrong access_hash, flood_error, etc
def b():
    nya = c.RawConfigParser()  #Instance desu
    nya.read('degerler.veri')
    cfg = nya['veri']['config_no']
    satno = nya['veri']['satir_no']
    kissay = nya['veri']['kisi_sayisi']
    group_username = nya['veri']['kanal_grup_adi']
    ags = nya['veri']['aktif_gun_sayisi']
    bsk = nya['veri']['beklenicek_sure_kucuk']
    bsb = nya['veri']['beklenicek_sure_buyuk']
    intsatno = int(satno)
    intkissay = int(kissay)
    intags = int(ags)
    intbsk = int(bsk)
    intbsb = int(bsb)
    cpass = c.RawConfigParser()
    cpass.read(cfg)
    try:
        id = cpass['cred']['id']
        h = cpass['cred']['hash']
        p = cpass['cred']['phone']
        client = TelegramClient(p, id, h)
    except KeyError:
        os.system('cls')
        print("[!] Somethings wrong with api id password hash or phone!!\n")
        sys.exit(1)
    client.connect()
    if not client.is_user_authorized():
        client.send_code_request(p)
        os.system('cls')
        client.sign_in(p, input('[+] Enter the code sent from telegram : '))
    client(JoinChannelRequest(channel=group_username))
    os.system('cls')
    users = []
    with open("users.nya", "r", encoding='UTF-8') as fd:
        rows = csv.reader(fd, delimiter=",", lineterminator="\n")
        for row in islice(csv.reader(fd), intsatno, None):
            user = {}
            user['username'] = row[0]
            user['id'] = row[1]
            user['access_hash'] = row[2]
            user['name'] = row[3]
            users.append(user)
    chats = []
    last_date = None
    chunk_size = 200
    groups = []
    result = client(
        GetDialogsRequest(offset_date=last_date,
                          offset_id=0,
                          offset_peer=InputPeerEmpty(),
                          limit=chunk_size,
                          hash=0))
    chats.extend(result.chats)
    for chat in chats:
        try:
            check = client.get_entity(group_username)
            if check.id == chat.id:
                groups.append(chat)
        except:
            continue
    i = 0
    for group in groups:
        print('[' + str(i) + ']' '-' + group.title)
        i += 1
    g_index = 0
    target_group = groups[int(g_index)]
    target_group_entity = InputPeerChannel(target_group.id,
                                           target_group.access_hash)
    mode = 1
    global max_user_to_add_x, max_user_to_add
    max_user_to_add = 0
    max_user_to_add_x = 0
    for user in users:
        try:
            if max_user_to_add == 1:  #intkissay:
                client(LeaveChannelRequest(channel=group_username))
                change_config()
                b()
            if mode == 1:
                if user['username'] == "":
                    max_user_to_add_x += 1
                    continue
                print(f"{p} Adding user {user['id']}")
                max_user_to_add += 1
                max_user_to_add_x += 1
                user_to_add = client.get_input_entity(user['username'])
            #elif mode == 2:
            #	user_to_add = InputPeerUser(user['id'], user['access_hash'])
            client(InviteToChannelRequest(target_group_entity, [user_to_add]))
            print(f"[+] Waiting random time {intbsk} - {intbsb} as seconds.")
            time.sleep(random.randrange(intbsk, intbsb))
        except:
            max_user_to_add -= 1
            max_user_to_add_x += 1
            traceback.print_exc()
            print(f"[+] Waiting random time 11 - 23 as seconds.")
            time.sleep(random.randrange(11, 23))
            continue
Example #25
0
    clnt.disconnect()

print('\n' + info + ' Sessions created!')
time.sleep(2)
print(f'{plus}{lg} Enter EXACT username of the public group[Without @]')
g = input(f'{plus}{lg} Username[Eg: Techmedies_Hub]: {r}')
group = 't.me/' + str(g)
print('\n')
print(f'{info}{lg} Joining from all accounts...{rs}\n')
for account in accounts:
    api_id = int(account[0])
    api_hash = str(account[1])
    phone = str(account[2])
    client = TelegramClient(phone, api_id, api_hash)
    client.connect()
    username = client.get_entity(group)
    try:
        client(JoinChannelRequest(username))
        print(f'{success}{lg} Joined from {phone}')
    except:
        print(f'{error}{r} Error in joining from {phone}')
        accounts.remove(account)
    client.disconnect()
time.sleep(2)
clr()
number = len(accounts)
print(f'{info}{lg} Total accounts: {number}')
print(
    f'{info}{lg} If you have more than 10 accounts then it is recommended to use 10 at a time'
)
a = int(input(f'{plus}{lg} Enter number of accounts to use: {r}'))
Example #26
0
        textToSplit = splittedText[1]
        # print(strongs)
        contacts = textToSplit.lstrip(' ').rstrip('\n')
        # print(contacts)
        # print()
        # print()
        self.data.append([name, position, profession, profexp, anotherexp, strongs, contacts])
        print('added')

    def getDataFrame(self):
        df = pd.DataFrame(self.data, columns=['name', 'position', 'profession', 'profexp', 'anotherexp', 'strongs', 'contacts'])
        return df

client = TelegramClient(username, api_id, api_hash)
client.start()
botEntity = client.get_entity(botTag)
client.send_message(botEntity, startCommand)




for professionIndex in range(4, 5):
    dataFrame = CustomDataFrame()
    for yearExperience in range(21):
        client.send_message(botEntity, findCommand)
        time.sleep(0.25)
        messages = client.get_messages(botEntity)
        try: messages[0].click()
        except Exception: continue
        time.sleep(0.25)
        messages = client.get_messages(botEntity)
        api_info_list = read_csv('api.csv')
        phone_list = sum(read_csv('phone.csv'), start=[])

        config = configparser.ConfigParser()
        config.read("config.ini")
        from_channel = config['Telegram']['from_channel']
        to_channel = config['Telegram']['to_channel']
        export_phone = utils.parse_phone(config['Telegram']['export_phone'])

        user_rows = read_csv('users.csv')

        main_client = TelegramClient(f"sessions/{export_phone}",
                                     *api_info_list[0])
        main_client.start(export_phone)

        from_channel_entity = main_client.get_entity(from_channel)
        to_channel_entity = main_client.get_entity(to_channel)

        try:
            for api in api_info_list:
                print(f"\n*** Using App {api[0]} ***\n")

                for unparsed_phone in phone_list:
                    phone = utils.parse_phone(unparsed_phone)
                    client = TelegramClient(f"sessions/{phone}", *api)
                    client.start(phone)

                    # Join channels
                    channels_joined = all([
                        join_channel(client, from_channel),
                        join_channel(client, to_channel)
        print(
            'Feel free to delete the .session file after you are done using this code.'
        )
        print(
            'You can check how this code is secured looking at the Telethon package'
        )

        client.sign_in(phone, input('Enter the code: '))
    except SessionPasswordNeededError:
        client.sign_in(password=password)

    client.sign_in(phone, input('Enter the code: '))

GROUP_ID = int(os.getenv('GROUP_ID'))
CHANNEL_ID = int(os.getenv('CHANNEL_ID'))
CHANNEL = client.get_entity('https://t.me/BrainTradingChannelBeta')
USERS_FILENAME = os.getenv('USERS_FILENAME')

ADD_TO_GROUP = os.getenv('ADD_TO_GROUP') == 'True'
ADD_TO_CHANNEL = os.getenv('ADD_TO_CHANNEL') == 'True'

if ADD_TO_GROUP or ADD_TO_CHANNEL:
    with open(USERS_FILENAME, 'r') as csv_file:
        reader = csv.reader(csv_file)
        headers = next(reader)

        for raw_user in reader:
            try:
                user = client.get_entity(PeerUser(int(raw_user[1])))
                status = client(
                    functions.users.GetFullUserRequest(id=user.id)).user.status
Example #29
0
def autos():

    channel_username = to_group
    phone = utils.parse_phone(pphone)

    client = TelegramClient(f"../sessions/{phone}", api_id, api_hash)

    client.connect()
    if not client.is_user_authorized():
        print('some thing has changed')
        client.send_code_request(phone)
        client.sign_in(phone, input('Enter the code: '))

    input_file = '../data.csv'
    users = []
    with open(input_file, encoding='UTF-8') as f:
        rows = csv.reader(f, delimiter=",", lineterminator="\n")
        next(rows, None)
        for row in rows:
            user = {}
            user['srno'] = row[0]
            user['username'] = row[1]
            user['id'] = int(row[2])
            #user['access_hash'] = int(row[2])
            user['name'] = row[3]
            users.append(user)

    startfrom = int(input("Start From = "))
    endto = int(input("End To = "))

    for user in users:
        if (int(startfrom) <= int(user['srno'])) and (int(user['srno']) <=
                                                      int(endto)):
            try:
                status = 'delta'
                if user['username'] == "":
                    print("no username, moving to next")
                    continue

                client(
                    InviteToChannelRequest(channel_username,
                                           [user['username']]))
                status = 'DONE'

                #print("Waiting for 60-180 Seconds...")
                time.sleep(random.randrange(0, 5))

            except UserPrivacyRestrictedError:
                status = 'PrivacyRestrictedError'

            except UserAlreadyParticipantError:
                status = 'ALREADY'

            except PeerFloodError as g:
                status = 'PeerFloodError :('
                print(
                    'Script Is Stopping Now, Dont Use This Account For The Next 24 Hours'
                )
                time.sleep(86400)

            except ChatWriteForbiddenError as cwfe:

                client(JoinChannelRequest(channel_username))
                continue

            except errors.RPCError as e:
                status = e.__class__.__name__

            except Exception as d:
                status = d

            except:
                traceback.print_exc()
                print("Unexpected Error")
                continue
            channel_connect = client.get_entity(channel_username)
            channel_full_info = client(
                GetFullChannelRequest(channel=channel_connect))
            countt = int(channel_full_info.full_chat.participants_count)

            print(
                f"ADDING {user['name']} TO {channel_username} TOTAL: {countt} - {status}"
            )
        elif int(user['srno']) > int(endto):
            print("Members Added Successfully!")
            stat = input(
                'Done!\nChoose From Below:\n\n1 - Repeat The Script\nOR Just Hit Enter To Quit\n\nEnter: '
            )
            if stat == '1':
                autos()
            else:
                quit()
pool = redis.ConnectionPool(host=redis_config['host'],
                            port=redis_config['port'])
try:
    redis.Redis(connection_pool=pool).ping()
except Exception as e:
    print(e)
    exit(-1)

# 2. Config Telegram Bot
telegram_bot_config = json.load(open(WORK_DIR + '/telegram_bot.json', 'r'))
api_id = telegram_bot_config['api_id']
api_hash = telegram_bot_config['api_hash']
channel_share_link = telegram_bot_config['channel_share_link']
client = TelegramClient(WORK_DIR + '/anon.session', api_id, api_hash)
client.connect()
telegram_channel = client.get_entity(channel_share_link)


class ChannelInfo(object):
    channel_id = None
    channel_title = None

    def __init__(self, __channel_id__, __channel_title__):
        self.channel_id = __channel_id__
        self.channel_title = __channel_title__

    def __str__(self):
        return "[{}, {}]".format(self.channel_id, self.channel_title)


class VideoInfo(object):