class AuthService(): def __init__(self): print() def auth(self): try: # get credentials cpass = configparser.RawConfigParser() cpass.read('config.data') api_id = cpass['credential']['id'] api_hash = cpass['credential']['hash'] phone = cpass['credential']['phone'] except KeyError: os.system('clear') print("[!] run python3 setup_script.py first !!\n") sys.exit(1) self.client = TelegramClient(phone, api_id, api_hash) self.client.connect() # connect to telegram if not self.client.is_user_authorized(): # check if user authenticated self.client.send_code_request(phone) os.system('clear') self.client.sign_in(phone, input('[+] Enter the code: ')) return self.client def disconnect(self): self.client.disconnect()
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
def send_message(message): # Create a telegram session and assign it to a variable client client = TelegramClient('session', api_id, api_hash) client.connect() # In case of script ran first time it will 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_number) # Signing in the client client.sign_in(phone_number, input('Enter the code: ')) try: for receiver in receivers: # Set receiver user_id and access_hash # To get userid and access hash: client.get_input_entity('@username') receiverUser = InputPeerUser(receiver['user_id'], receiver['access_hash']) # Send message using telegram client client.send_message(receiverUser, message) except Exception as e: # there may be many error coming in while like peer error, wwrong access_hash, flood_error, etc print(e) # Disconnecting the telegram session client.disconnect()
def getChatMessages(phone_number, api_id, api_hash, channel_name, number_of_messages): message = [] time = [] messageId = [] sender = [] replyTo = [] counter = 0 data = {'message': message, 'time': time} loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) client = TelegramClient(phone_number, api_id, api_hash, loop=loop) try: client.connect() client = checkUserAuthorization(client, phone_number) chats = client.get_messages(channel_name, number_of_messages) if len(chats): for chat in chats: if checkNumberOfDays(chat.date) == -int(NUM_OF_DAY): messageId.append(chat.id) message.append(chat.message) sender.append(chat.from_id) replyTo.append(chat.reply_to_msg_id) time.append(chat.date) counter += 1 log.info(f'{NUM_OF_DAY} days => total {counter} chat messages') except Exception as err: log.exception(err) finally: client.disconnect() return data
def ritorna_lista_membri_gruppo(self, chat_id, username_gruppo): loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) client = TelegramClient('session', API_ID, API_HASH) client.start(bot_token=TOKEN) try: dati = list(client.get_participants(username_gruppo, aggressive=True)) except: self.bot.sendMessage(chat_id,"C'è stato un problema con il bot si prega di riprovare") client.disconnect() loop.stop() loop.close() return [] lista_gruppo=[] for utente in dati: if not utente.bot: user=self.ritorna_utente(chat_id, utente.id, utente.first_name) lista_gruppo.append(user) client.disconnect() loop.stop() loop.close() return lista_gruppo
def sendMessage(receiver, message): # creating a telegram session and assigning # it to a variable client client = TelegramClient("session", API_ID, API_HASH) # connecting and building the session client.connect() # in case of script ran first time it will # ask either to input token or otp sent to # number or your telegram id if not client.is_user_authorized(): client.send_code_request(PHONE) # signing in the client client.sign_in(PHONE, input("Enter the code: ")) try: # sending message using telegram client client.send_message(receiver, message) except Exception as e: print(e) # disconnecting the telegram session client.disconnect()
def get_posts_complex(self, query): """ Execute a query; get messages for given parameters :param dict query: Query parameters, as part of the DataSet object :return list: Posts, sorted by thread and post ID, in ascending order """ self.eventloop = asyncio.new_event_loop() session_path = Path(__file__).parent.joinpath( "sessions", self.dataset.parameters.get("session")) client = None try: client = TelegramClient(str(session_path), self.dataset.parameters.get("api_id"), self.dataset.parameters.get("api_hash"), loop=self.eventloop) client.start() except Exception as e: self.dataset.update_status( "Error connecting to the Telegram API with provided credentials.", is_final=True) self.dataset.finish() if client and hasattr(client, "disconnect"): client.disconnect() return None # ready our parameters parameters = self.dataset.get_parameters() queries = [ query.strip() for query in parameters.get("query", "").split(",") ] max_items = convert_to_int(parameters.get("items", 10), 10) # userinfo needs some work before it can be retrieved, something with # async method calls userinfo = False # bool(parameters.get("scrape-userinfo", False)) try: posts = self.gather_posts(client, queries, max_items, userinfo) except Exception as e: self.dataset.update_status("Error scraping posts from Telegram") self.log.error("Telegram scraping error: %s" % traceback.format_exc()) posts = None finally: client.disconnect() # delete personal data from parameters. We still have a Telegram # session saved to disk, but it's useless without this information. self.dataset.delete_parameter("api_id") self.dataset.delete_parameter("api_hash") self.dataset.delete_parameter("api_phone") return posts
def sessioncu(): "Gelen İnput ile session oluşturur." api_id = konsol.input('[yellow]API ID : [/]') api_hash = konsol.input('[yellow]API HASH : [/]') telefon = konsol.input('[yellow]Telefon(+xxxx): [/]').replace(' ', '') try: client = TelegramClient(f"{SESSION}{telefon}", api_id, api_hash) client.connect() except Exception as hata: os.remove(f'{SESSION}{telefon}.session') print(f'[cyan]Hata Var !\n\t`{type(hata).__name__}`\n\t{hata}') exit() if not client.is_user_authorized(): client.send_code_request(telefon) try: client.sign_in(telefon, konsol.input('[yellow]\nDoğrulama Kodu: ')) client.disconnect() except Exception as hata: os.remove(f'{SESSION}{telefon}.session') konsol.print( f'[cyan]Hata Var !\n\t`{type(hata).__name__}`\n\t{hata}') exit() bilgilerim = {} async def ana(): # Şuan bütün client methodlarını kullanabilirsiniz örneğin; ben = await client.get_me() bilgilerim['nick'] = f"@{ben.username}" bilgilerim['ad'] = f"{ben.first_name} {ben.last_name}" bilgilerim['uid'] = ben.id await client.send_message( 'me', f'__Merhaba, Ben **KekikSuser** Tarafından Gönderildim!__\n\n__Senin Bilgilerin;__\n\n**ID :** `{api_id}`\n**Hash :** `{api_hash}`\n**Telefon :** `{telefon}`\n\n**Kendi gizliliğin için bunları kimseyle paylaşma..**' ) with client: client.loop.run_until_complete(ana()) dict2json( { 'api_id': api_id, 'api_hash': api_hash, 'telefon': telefon, 'kullanici_id': bilgilerim['uid'], 'kullanici_nick': bilgilerim['nick'], 'kullanici_adi': bilgilerim['ad'] }, dosya_adi=f'{SESSION}bilgiler.json') konsol.print(f'\n\n\t\t[red]{telefon} Session Kayıt Edildi..!')
def client(g_bot: GDGAjuBot): # Esse módulo só pode ser testado com uma chave API real # Obtenha a sua em https://my.telegram.org, na seção API Development api_id = TELEGRAM_CLIENT_API_ID api_hash = TELEGRAM_CLIENT_API_HASH t_client = TelegramClient("it_gdgajubot", api_id, api_hash) t_client.start() yield ClientWrapper(t_client, g_bot.get_me().name) t_client.disconnect()
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()
def ClientConnect(sim: Sim): client = TelegramClient(sim.phone, sim.ID, sim.access_hash) # connect to client client.connect() if not client.is_user_authorized(): client.send_code_request(sim.phone) client.sign_in(sim.phone, input(Fore.WHITE + 'Enter the code to ' + sim.name + ': ')) print(Fore.GREEN + "Connected Succesfully!") client.disconnect() del client
def send_message(msg): client = TelegramClient('session', api_id, api_hash) client.connect() if not client.is_user_authorized(): client.send_code_request(phone) client.sign_in(phone, input('Enter the code: ')) try: receiver = InputPeerUser('user_id', 'user_hash') client.send_message(receiver, msg, parse_mode='html') except Exception as e: print(e) client.disconnect()
def get_last_posts(phone: str, chat: custom.Dialog, count: int): client = TelegramClient(os.path.join('data', phone), api_id, api_hash, proxy=proxy) client.connect() if not client.is_user_authorized(): client.disconnect() return False messages = client.get_messages(chat.entity, count) client.disconnect() return list(messages)
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
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
def get_chat_list(phone: str): client = TelegramClient(os.path.join('data', phone), api_id, api_hash, proxy=proxy) client.connect() if not client.is_user_authorized(): client.disconnect() return False res = [] for dialog in client.iter_dialogs(): if dialog.is_channel: res.append(dialog) client.disconnect() return res
def CreateSessionFile(s: Sim): client = TelegramClient('sessions\\' + s.phone, s.ID, s.access_hash) client.connect() if not client.is_user_authorized(): client.send_code_request(sim.phone) time.sleep(0.5) CopyMessageToClipboard() time.sleep(0.5) PasteMessageInFile() code = GetCodeFromFile() client.sign_in(phone=sim.phone, code=code) print(Fore.GREEN + f"Created {sim.name} session file! Logging out..") client.disconnect() else: print(Fore.RED + f"{sim.name} already exist! skipping") client.disconnect()
class TelegramDialogSource(DialogSource): def __init__(self, api_id: int, api_hash: str): self._client = TelegramClient(session=None, api_id=api_id, api_hash=api_hash).start() def __enter__(self): return self def __exit__(self, ecx_type, ecx_value, traceback): self._client.log_out() self._client.disconnect() def getDialogs(self) -> Iterable[Dialog_]: for dialog in self._client.iter_dialogs(): yield TelegramDialog(dialog)
def auth_get_code(phone: str): client = TelegramClient(os.path.join('data', phone), api_id, api_hash, proxy=proxy) client.connect() if not client.is_user_authorized(): try: ch: types.auth.SentCode = client.send_code_request(phone) return 0, ch.phone_code_hash # Либо телефон забанен, либо не зареган except (PhoneNumberBannedError, PhoneNumberFloodError, PhoneNumberUnoccupiedError, PhoneNumberInvalidError): client.disconnect() return 1, None client.disconnect() return -1, None
def main_function(username): dialogue = Dialog.get_all_message(username) for dial in dialogue: user = Clone.getCloneWithID(dial.user_id) session = "session/" + "{}".format(user.phone) api_id = int(user.api_id) api_hash = user.api_hash phone_number = "84" + str(user.phone) group_id = int(dial.group_id) grouplinks = Group.getGroupWithID(group_id) client = TelegramClient(session=str(session), api_id=api_id, api_hash=api_hash) print("Clone", user.id) client.connect() if check_banned(client, phone_number) is not False: check_and_join(client, grouplinks.group_link) client.loop.run_until_complete( interact(client, group_id, emoji.emojize(dial.content))) client.disconnect() sleep(dial.delay)
def hor(file_path): api_id = 3610504 #Must change api_hash = '2d635b85550a19596f4efa68c3cf21d8' #Must change phone = '+37494178007' #Must change 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 code: ')) user = {} user['username'] = '******' #Must change user['id'] = 1634518644 #Must change user['access_hash'] = int('-6392661706151905964') #Must change user['name'] = 'Anime Bot' receiver = InputPeerUser(user['id'], user['access_hash']) try: print("Sending Video to:", user['name']) client.send_file(receiver, file_path, caption=file_path, attributes=(DocumentAttributeVideo(0, 0, 0),)) print('done') except Exception as e: print("Error:", e) client.disconnect() print("Done. Message sent to all users.")
def main(): if not path.isfile(config.sessions): os.makedirs(path.dirname(config.sessions), exist_ok=True) open(config.sessions, 'w').close() cfg = ConfigParser() cfg.read(config.sessions) session = input('Session: ') assert session not in cfg.sections() cfg.add_section(session) api_id = input('API ID: ') cfg[session]['api_id'] = api_id api_hash = input('API Hash: ') cfg[session]['api_hash'] = api_hash with open(config.sessions, 'wt') as file: cfg.write(file) client = TelegramClient(f'./sessions/{session}', api_id, api_hash) client.start() client.disconnect()
def auth_2fa(phone: str, password: str): client = TelegramClient(os.path.join('data', phone), api_id, api_hash, proxy=proxy) client.connect() if not client.is_user_authorized(): try: client.sign_in(phone=phone, password=password) client.disconnect() return 0 except (PasswordHashInvalidError, PasswordEmptyError): client.disconnect() return 1 client.disconnect() return -1
def auth_redeem_code(phone: str, code: int, code_hash: str): client = TelegramClient(os.path.join('data', phone), api_id, api_hash, proxy=proxy) client.connect() if not client.is_user_authorized(): try: client.sign_in(phone=phone, code=code, phone_code_hash=code_hash) client.disconnect() return 0 except (SessionExpiredError, PhoneCodeExpiredError, PhoneCodeInvalidError, PhoneCodeEmptyError): client.disconnect() return 1 except SessionPasswordNeededError: return 2 client.disconnect() return -1
set_as_cancel = SetStatus(id=activation.id, status=SmsTypes.Status.Cancel).request(wrapper) print(set_as_cancel) exit(1) # set current activation status as SmsSent (code was sent to phone) set_as_sent = SetStatus(id=activation.id, status=SmsTypes.Status.SmsSent).request(wrapper) print(set_as_sent) # .. wait code while True: time.sleep(1) response = GetStatus(id=activation.id).request(wrapper) if response['code']: print('Your code:{}'.format(response['code'])) break # set current activation status as End (you got code and it was right) set_as_end = SetStatus(id=activation.id, status=SmsTypes.Status.End).request(wrapper) print(set_as_end) client.sign_in(phone, input('[+] введите код из смс: ')) client.disconnect() rar = open("tel2.txt", "r") dad = rar.read() rar.close() os.replace(dad + '.session', 'Aka-TG-Soft/' + dad + '.session') restart_program()
def send_sms(): try: cpass = configparser.RawConfigParser() cpass.read('config.data') api_id = cpass['cred']['id'] api_hash = cpass['cred']['hash'] phone = cpass['cred']['phone'] except KeyError: os.system('clear') main.banner() print(re+"[!] run python3 setup.py first !!\n") sys.exit(1) client = TelegramClient(phone, api_id, api_hash) client.connect() if not client.is_user_authorized(): client.send_code_request(phone) os.system('clear') main.banner() client.sign_in(phone, input(gr+'[+] Enter the code: '+re)) os.system('clear') main.banner() input_file = sys.argv[1] 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['username'] = row[0] user['id'] = int(row[1]) user['access_hash'] = int(row[2]) user['name'] = row[3] users.append(user) print(gr+"[1] send sms by user ID\n[2] send sms by username ") mode = int(input(gr+"Input : "+re)) message = input(gr+"[+] Enter Your Message : "+re) for user in users: if mode == 2: if user['username'] == "": continue receiver = client.get_input_entity(user['username']) elif mode == 1: receiver = InputPeerUser(user['id'],user['access_hash']) else: print(re+"[!] Invalid Mode. Exiting.") client.disconnect() sys.exit() try: print(gr+"[+] Sending Message to:", user['name']) client.send_message(receiver, message.format(user['name'])) print(gr+"[+] Waiting {} seconds".format(SLEEP_TIME)) time.sleep(SLEEP_TIME) except PeerFloodError: print(re+"[!] Getting Flood Error from telegram. \n[!] Script is stopping now. \n[!] Please try again after some time.") client.disconnect() sys.exit() except Exception as e: print(re+"[!] Error:", e) print(re+"[!] Trying to continue...") continue client.disconnect() print("Done. Message sent to all users.")
class CoronaBot(object): def __init__(self, apiId, apiHash) -> None: self.bot = TelegramClient('CoronaWHVBot', apiId, apiHash) self.bot.add_event_handler(self.onStartMessage, events.NewMessage(pattern="/start")) self.bot.add_event_handler(self.onStopMessage, events.NewMessage(pattern="/stop")) self.bot.add_event_handler(self.onRegionResetMessage, events.NewMessage(pattern="/resetRegion")) self.bot.add_event_handler( self.onRegularMessage, events.NewMessage(pattern="^(?!(/start|/stop|/resetRegion).*$).*")) self.userStore = UserStore() self.dataStoreProvider = RegionSourceProvider() def __del__(self): self.stop() async def start(self, token): return await self.bot.start(bot_token=token) async def stop(self): self.userStore.close() asyncio.get_running_loop().run_until_complete(self.bot.disconnect()) print("Bot stoped and database closed") async def onStartMessage(self, event): sender = event.input_sender try: print(self.userStore.getUser(sender.user_id, sender.access_hash)) self.userStore.addUserToDB(sender.user_id, sender.access_hash) print("added user") await event.respond( "Für welches Gebiet willst du jeden Morgen um 09:00 Nachrichten erhalten?\n\nBitte gebe zunächst die Art der Region an!", buttons=getRegionTypeKeyboard()) except Exception as e: await event.respond( "Irgendwas hat nicht funktioniert! Probiere nochmal \"/start\" oder kontaktiere den Admin", buttons=getDisabledKeyboard()) print("adding went wrong", e) async def onStopMessage(self, event): sender = event.input_sender try: self.userStore.removeUserFromDB(sender.user_id, sender.access_hash) print("removed user") await event.respond( "Du wurdest erfolgreich entfernt, du wurst nun keine Nachrichten mehr erhalten!", buttons=getDisabledKeyboard()) except Exception as e: await event.respond( "Das entfernen hat nicht funktioniert. Du wirst weiterhin Nachrichten erhalten!", buttons=getDefaultKeyboard()) print("deleting went wrong!", e) async def onRegionResetMessage(self, event): sender = event.input_sender try: self.userStore.removeRegionOfUser(sender.user_id, sender.access_hash) print("removed user") await event.respond( "Deine Region wurde erfolgreich entfernt. Für welche Region willst du ab jetzt Nachrichten erhalten?\n\nBitte gebe zunächst die Art der Region an!", buttons=getRegionTypeKeyboard()) except Exception as e: await event.respond( "Das entfernen hat nicht funktioniert. Du wirst weiterhin Nachrichten erhalten!", buttons=getDefaultKeyboard()) async def onRegularMessage(self, event): sender = event.input_sender databaseUser = self.userStore.getUser(sender.user_id, sender.access_hash) if (databaseUser[2] == None): await self.tryAddRegionType(event, databaseUser) elif (databaseUser[3] == None): await self.tryAddRegionName(event, databaseUser) else: await event.reply("Ich weiß nicht was ich tun soll!") async def tryAddRegionType(self, event, databaseUser): regionType = event.message.message isRegionType = any( map(lambda b: b.button.text == event.message.message, flatten(getRegionTypeKeyboard()))) if (not isRegionType): await event.respond("Das war kein erlaubte Regionsart!", buttons=getRegionTypeKeyboard()) else: try: self.userStore.setRegionTypeOfUser(databaseUser[0], databaseUser[1], regionType) await event.respond( "Schreibe jetzt bitte den Namen der Region!", buttons=Button.clear()) except Exception as e: print("region type saving failed", e) await event.respond( "Beim Speichern ist etwas schief gelaufen, versuche es nochmal oder kontaktiere den Admin" ) async def tryAddRegionName(self, event, databaseUser): name = event.message.message region = Region(databaseUser[2], None) possibleNames = [ n.lower() for n in self.dataStoreProvider.getPossibleNameForRegionType(region) ] if (name.lower() in possibleNames): await event.respond( "Alles klar, ab jetzt bekommst du jeden Morgen um 09:00 eine Nachricht über die aktuelle Lage!", buttons=getDefaultKeyboard()) self.userStore.setRegionNameOfUser(databaseUser[0], databaseUser[1], name) else: me = "Ich habe diesen Ort nicht gefunden!" bs = Button.clear() closeMatches = list( difflib.get_close_matches(name, possibleNames, n=5)) if (len(closeMatches) > 0): bs = getKeyboardFromList( map(lambda n: n.capitalize(), closeMatches)) me += "\n\nMeinst du vielleicht:\n" for m in closeMatches: me += " - %s\n" % (m.capitalize()) await event.respond(me, buttons=bs) async def sendMessageToAll(self, message): users = self.userStore.getAllActiveUsers() for u in users: peer = InputPeerUser(u[0], u[1]) try: await self.bot.send_message(peer, message, parse_mode="html") except UserIsBlockedError: self.userStore.removeUserFromDB(u[0], u[1]) async def sendUpdateToAll(self): print("Sending Number Update to all users") users = filter(lambda u: u[2] != None and u[3] != None, self.userStore.getAllActiveUsers()) for user in users: peer = InputPeerUser(user[0], user[1]) try: message = getMessage( self.dataStoreProvider.getSourceFromRegion( Region(user[2], user[3]))) try: await self.bot.send_message(peer, message, parse_mode="html") except UserIsBlockedError: self.userStore.removeUserFromDB(user[0], user[1]) except: pass print("all messages send") async def runUntilDisconnect(self): return await self.bot.run_until_disconnected()
class UploadTelegramCrawler(BaseCrawler): """ Краулер, выгружающий данные из телеграмм-каналов """ def __init__(self, base_url, base_account_folder, limit=1000): super().__init__(base_url, base_account_folder) # Устанавливаем лимит получаемых с канала сообщений self.limit = limit # Получаем необходимые настройки _settings = get_settings() # Присваиваем значения внутренним переменным _api_id = _settings['api_id'] _api_hash = _settings['api_hash'] _username = _settings['username'] # Создадим объект клиента Telegram API self.client = TelegramClient(_username, _api_id, _api_hash) def __enter__(self): # Запускаем клиент self.client.start() return self def __exit__(self, type, value, traceback): """ Отключаем клиента :param type: :param value: :param traceback: :return: """ self.client.disconnect() def get_messages(self): """ Возвращаем экземпляр класса Message при итерировании :return: Message """ for message in self.client.iter_messages(self.base_url, limit=self.limit): yield Message(self.base_url, message.text, datetime_=message.date) def upload_to_csv(self): # Поля таблицы field_names = ['Text', 'Date'] # Путь к csv файлу csv_path = self.base_account_folder + self.base_url.split('/')[-1] + '.csv' # Открываем csv файл with open(csv_path, 'w', encoding='utf-8') as csv_file: # Инициализация экземляра DictWriter csv_writer = csv.DictWriter(csv_file, fieldnames=field_names) csv_writer.writeheader() # Итерируемся по сообщениям for message in self.get_messages(): if message.description: # Записываем один ряд таблицы csv_writer.writerow({'Text': message.description, 'Date': message.datetime_})
def add_credentials(): if os.path.isfile(os.path.join(os.getcwd(), 'multiconfig.json')) == True: with open(os.path.join(os.getcwd(), 'multiconfig.json'), 'r') as config_file: data = json.load(config_file) print(f'Credentials found, for {len(data)} Telegram accounts') for cred in data: print( f'Checking if two factor authentication is already done with {cred["phone"]}' ) client = TelegramClient(cred['phone'], cred['api_id'], cred['api_hash']) async def main(): # Now you can use all client methods listed below, like for example... await client.send_message('me', 'Hello !!!!!') with client: client.loop.run_until_complete(main()) client.connect() if not client.is_user_authorized(): print( f'Sending request code to {cred["phone"]}, please authenticate' ) client.send_code_request(phone) client.sign_in(cred["phone"], input('40779')) else: print( f'Good! Client {cred["phone"]} is authenticated, I can use it.' ) client.disconnect() print(f'Credentials found, for {len(data)} Telegram accounts') while True: question = input( 'Do you want to use these credentials?[y/n] ').lower() if question == 'y': break elif question == 'n': print('Good, lets define new credentials...') ammount_of_credentials = int( input('How many accounts do you want to add?')) credentials = [] for i in range(ammount_of_credentials): phone = input('Type the phone number: ') api_id = input(f'Type {phone} api id: ') api_hash = input(f'Type {phone} api hash: ') config = {} config['api_id'] = api_id config['api_hash'] = api_hash config['phone'] = phone credentials.append(config.copy()) with open( os.path.join(os.getcwd(), 'multiconfig.json'), 'w') as config_file: json.dump(credentials, config_file, indent=2) client = TelegramClient(phone, api_id, api_hash) async def main(): # Now you can use all client methods listed below, like for example... await client.send_message('me', 'Hello !!!!!') with client: client.loop.run_until_complete(main()) client.connect() if not client.is_user_authorized(): print( f'Sending request code to {phone}, please authenticate' ) client.send_code_request(phone) client.sign_in(phone, input('40779')) else: print( f'Good! Client {phone} is authenticated, I can use it.' ) client.disconnect() break else: print('No credentials found. Lets define new ones') ammount_of_credentials = int( input('How many accounts do you want to add?')) credentials = [] for i in range(ammount_of_credentials): phone = input('Type the phone number: ') api_id = input(f'Type {phone} api id: ') api_hash = input(f'Type {phone} api hash: ') config = {} config['api_id'] = api_id config['api_hash'] = api_hash config['phone'] = phone credentials.append(config.copy()) with open(os.path.join(os.getcwd(), 'multiconfig.json'), 'w') as config_file: json.dump(credentials, config_file, indent=2) client = TelegramClient(phone, api_id, api_hash) async def main(): # Now you can use all client methods listed below, like for example... await client.send_message('me', 'Hello !!!!!') with client: client.loop.run_until_complete(main()) client.connect() if not client.is_user_authorized(): print( f'Sending request code to {phone}, please authenticate' ) client.send_code_request(phone) client.sign_in(phone, input('40779')) else: print( f'Good! Client {phone} is authenticated, I can use it.' ) client.disconnect()
def addermulti(): g_scrape_id = '' g_id = '' def add_credentials(): if os.path.isfile(os.path.join(os.getcwd(), 'multiconfig.json')) == True: with open(os.path.join(os.getcwd(), 'multiconfig.json'), 'r') as config_file: data = json.load(config_file) print(f'Credentials found, for {len(data)} Telegram accounts') for cred in data: print( f'Checking if two factor authentication is already done with {cred["phone"]}' ) client = TelegramClient(cred['phone'], cred['api_id'], cred['api_hash']) async def main(): # Now you can use all client methods listed below, like for example... await client.send_message('me', 'Hello !!!!!') with client: client.loop.run_until_complete(main()) client.connect() if not client.is_user_authorized(): print( f'Sending request code to {cred["phone"]}, please authenticate' ) client.send_code_request(phone) client.sign_in(cred["phone"], input('40779')) else: print( f'Good! Client {cred["phone"]} is authenticated, I can use it.' ) client.disconnect() print(f'Credentials found, for {len(data)} Telegram accounts') while True: question = input( 'Do you want to use these credentials?[y/n] ').lower() if question == 'y': break elif question == 'n': print('Good, lets define new credentials...') ammount_of_credentials = int( input('How many accounts do you want to add?')) credentials = [] for i in range(ammount_of_credentials): phone = input('Type the phone number: ') api_id = input(f'Type {phone} api id: ') api_hash = input(f'Type {phone} api hash: ') config = {} config['api_id'] = api_id config['api_hash'] = api_hash config['phone'] = phone credentials.append(config.copy()) with open( os.path.join(os.getcwd(), 'multiconfig.json'), 'w') as config_file: json.dump(credentials, config_file, indent=2) client = TelegramClient(phone, api_id, api_hash) async def main(): # Now you can use all client methods listed below, like for example... await client.send_message('me', 'Hello !!!!!') with client: client.loop.run_until_complete(main()) client.connect() if not client.is_user_authorized(): print( f'Sending request code to {phone}, please authenticate' ) client.send_code_request(phone) client.sign_in(phone, input('40779')) else: print( f'Good! Client {phone} is authenticated, I can use it.' ) client.disconnect() break else: print('No credentials found. Lets define new ones') ammount_of_credentials = int( input('How many accounts do you want to add?')) credentials = [] for i in range(ammount_of_credentials): phone = input('Type the phone number: ') api_id = input(f'Type {phone} api id: ') api_hash = input(f'Type {phone} api hash: ') config = {} config['api_id'] = api_id config['api_hash'] = api_hash config['phone'] = phone credentials.append(config.copy()) with open(os.path.join(os.getcwd(), 'multiconfig.json'), 'w') as config_file: json.dump(credentials, config_file, indent=2) client = TelegramClient(phone, api_id, api_hash) async def main(): # Now you can use all client methods listed below, like for example... await client.send_message('me', 'Hello !!!!!') with client: client.loop.run_until_complete(main()) client.connect() if not client.is_user_authorized(): print( f'Sending request code to {phone}, please authenticate' ) client.send_code_request(phone) client.sign_in(phone, input('40779')) else: print( f'Good! Client {phone} is authenticated, I can use it.' ) client.disconnect() add_credentials() with open(os.path.join(os.getcwd(), 'multiconfig.json'), 'r') as config_file: credentials = json.load(config_file) for config in credentials: api_id = config['api_id'] api_hash = config['api_hash'] phone = config['phone'] AMMOUNT_OF_FLOOD_ERROS = 0 AMMOUNT_OF_USERS_ADDED = 0 print(f'Now trying use account {phone}') try: client = TelegramClient(phone, api_id, api_hash) async def main(): # Now you can use all client methods listed below, like for example... await client.send_message('me', 'Hello !!!!!') SLEEP_TIME_1 = 100 SLEEP_TIME_2 = 100 with client: client.loop.run_until_complete(main()) client.connect() if not client.is_user_authorized(): client.send_code_request(phone) client.sign_in(phone, input('40779')) 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: if chat.megagroup == True: groups.append(chat) except: continue try: print('Which Group Do You Want To Scrape Members From: ') i = 0 for g in groups: g.title = g.title.encode('utf-8') g.title = g.title.decode('ascii', 'ignore') print(f'[Group]: {str(g.title)} [Id]: {str(g.id)}') i += 1 if g_scrape_id == '': g_scrape_id = input( "Please! Enter the group to scrape id: ").strip() for group in groups: if str(group.id) == g_scrape_id: target_group_scrape = group print('Fetching Members...') all_participants_to_scrape = [] all_participants_to_scrape = client.get_participants( target_group_scrape, aggressive=True) print('Saving In file...') with open(os.path.join(os.getcwd(), 'Scraped.json'), 'w+') as f: users = [] jsonuser = {} for user in all_participants_to_scrape: jsonuser.clear() 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() jsonuser['username'] = username jsonuser['id'] = user.id jsonuser['access_hash'] = user.access_hash jsonuser['name'] = name users.append(jsonuser.copy()) json.dump(users, f, indent=2) print('Members scraped successfully.......') users = [] with open(os.path.join(os.getcwd(), 'Scraped.json'), "r", encoding='utf-8', errors='ignore') as f: list = json.load(f, strict=False) for dict in list: user = {} user['username'] = dict['username'] user['id'] = dict['id'] user['access_hash'] = dict['access_hash'] user['name'] = dict['name'] users.append(user) except Exception as e: print(e) print('Choose a group to add members:') i = 0 for group in groups: group.title = group.title.encode('utf-8') group.title = group.title.decode('ascii', 'ignore') print(f'[Group]: {str(group.title)} [Id]: {str(group.id)}') i += 1 if g_id == '': g_id = input("Enter the group Id: ") for group in groups: if g_id == str(group.id): target_group = group #Start of scrappe members from that group to avoid repetition try: all_participants = [] all_participants = client.get_participants(target_group, aggressive=True) scrapedusers = [] jsonuser = {} for user in all_participants: jsonuser.clear() 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() jsonuser['username'] = username jsonuser['id'] = user.id jsonuser['access_hash'] = user.access_hash jsonuser['name'] = name scrapedusers.append(jsonuser.copy()) print('Members scraped successfully.......') except: print( 'Error scrapping members of this group. Danger of false positives.' ) #End of scrappe members of that group to avoid repetition target_group_entity = InputPeerChannel(target_group.id, target_group.access_hash) # mode = int(input("Enter 1 to add by username or 2 to add by ID: ")) mode = 2 n = 0 try: with open(os.path.join(os.getcwd(), 'tried.json'), 'r') as file: tried = json.load(file) except: tried = [] for user in users: if AMMOUNT_OF_FLOOD_ERROS > 10: print( 'UPS, GOT 10 FLOOD ERRORS, SWITCHING TO THE NEXT ACCOUNT' ) break if AMMOUNT_OF_USERS_ADDED >= 45: print( 'GREAT! ADDED 45 USERS WITH THIS NUMBER TODAY. SWITCHING TO THE NEXT ACCOUNT' ) break if user not in scrapedusers: if user not in tried: tried.append(user.copy()) with open(os.path.join(os.getcwd(), 'tried.json'), 'w+') as file: json.dump(tried, file, indent=2) try: n += 1 if n % 80 == 0: sleep(60) try: print("Trying to add user {}".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( "Invalid Mode Selected. Please Try Again." ) client( InviteToChannelRequest( target_group_entity, [user_to_add])) print("Waiting for 60-180 Seconds...") time.sleep(random.randrange(60, 90)) except PeerFloodError: AMMOUNT_OF_FLOOD_ERROS += 1 print( "Getting Flood Error from telegram. Script is stopping now. Please try again after some time." ) print( "Waiting {} seconds".format(SLEEP_TIME_2)) time.sleep(SLEEP_TIME_2) continue #continues adicionado por mim except UserPrivacyRestrictedError: print( "The user's privacy settings do not allow you to do this. Skipping." ) print("Waiting for 5 Seconds...") time.sleep(random.randint( 0, 5)) #Alterei, antes era randrange(5,0) continue # adicionado por mim except UserNotMutualContactError: continue except UserChannelsTooMuchError: print( 'This user is already in too many channels/supergroups.' ) continue except Exception as e: # traceback.print_exc() print(f"Unexpected Error: {e}") continue AMMOUNT_OF_USERS_ADDED += 1 try: with open( os.path.join(os.getcwd(), 'added.json'), 'r') as file: added = json.load(file) added.append(user.copy()) except: added = [] with open(os.path.join(os.getcwd(), 'added.json'), 'w+') as file: json.dump(added, file, indent=2) try: print( f'User {user["name"]} with id: {user["id"]} has been sucessfully added to your group.' ) except UnicodeEncodeError: print( f'User with id: {user["id"]} has been sucessfully added your group.' ) except Exception as e: print(f'An unnespected error ocureed: {e}') else: print( f'This user has been checked by me before. Skipping. If you want o erase data, delete "tried.json".' ) else: print('This user already is in this group. Skipping.') except Exception as e: e = str(e) print(e) try: client.disconnect() except: print('Unable to disconnect client') time.sleep(30000) if 'database' in e: print( 'The last time program was executed it was not closed properly. Please delete the .session files and restart the program.' ) time.sleep(30000) try: client.disconnect() except: print('Unable to disconnect client') try: client.disconnect() except: print('Unable to disconnect client')