• XSS.stack #1 – первый литературный журнал от юзеров форума

Телеграм / Telegram - Checker - Adder - Sender

pablito

HDD-drive
Пользователь
Регистрация
20.03.2020
Сообщения
43
Реакции
37
Всем привет, У меня есть вопрос, который поможет всем в будущем.

• Мне нужен код, который будет автоматически проверять введенный номер, который я создал на рабочем столе и собрал...
import time
from telethon.sync import TelegramClient
from telethon.errors import FloodWaitError
from telethon.tl.functions.contacts import ImportContactsRequest, DeleteContactsRequest
from telethon.tl.types import InputPhoneContact
# Replace with your Telegram API credentials
api_id = 'my id' # Replace with your api_id
api_hash = 'my hash' # Replace with your api_hash
# File paths on the desktop
input_file = r'C:\Users\x\Desktop\leads.txt' # File with phone numbers to check
output_file = r'C:\Users\x\Desktop\validate.txt' # Output file for valid numbers
# Initialize the Telegram client
with TelegramClient('telegram', api_id, api_hash) as client:
try:
with open(input_file, 'r') as file:
phone_numbers = [line.strip() for line in file.readlines()]
except FileNotFoundError:
print(f"Input file not found: {input_file}")
exit(1)
with open(output_file, 'a') as valid_file:
for phone in phone_numbers:
try:
print(f"Checking {phone}...")
contact = InputPhoneContact(client_id=0, phone=phone, first_name="Check", last_name="User")
result = client(ImportContactsRequest([contact]))
if result.users:
print(f"{phone} has a Telegram account.")
valid_file.write(f"{phone}\n") # Write the valid phone number to the output file
else:
print(f"{phone} does NOT have a Telegram account.")
# Clean up by deleting the contact
if result.users:
user_id = result.users[0].id
client(DeleteContactsRequest([user_id]))
# Wait 6 seconds to avoid spam, but adjust if needed
time.sleep(6)
except FloodWaitError as e:
print(f"FloodWaitError: Waiting for {e.seconds} seconds...")
time.sleep(e.seconds + 1) # Wait the time specified in the exception and retry
except Exception as e:
print(f"An error occurred: {e}") # Generic error handling for other issues
time.sleep(6) # Adjust the delay to avoid spam
print("Check completed. Valid numbers saved to", output_file)

• Потом добавляю этот номер в контакты...
import time
from telethon.sync import TelegramClient
from telethon.errors import FloodWaitError
from telethon.tl.functions.contacts import ImportContactsRequest
from telethon.tl.types import InputPhoneContact
# Replace with your Telegram API credentials
api_id = 'my id' # Replace with your api_id
api_hash = 'my hash' # Replace with your api_hash
# File paths on the desktop
input_file = r'C:\Users\x\Desktop\validate.txt' # File with valid numbers (validated)
output_file = r'C:\Users\x\Desktop\added in friends.txt' # Output file for successfully added contact IDs
# Initialize the Telegram client
with TelegramClient('telegram', api_id, api_hash) as client:
try:
with open(input_file, 'r') as file:
valid_numbers = [line.strip() for line in file.readlines()]
except FileNotFoundError:
print(f"Input file not found: {input_file}")
exit(1)
with open(output_file, 'a') as added_file:
friend_count = 1 # Variable to track the friend number (friends1, friends2, etc.)

for phone in valid_numbers:
try:
print(f"Adding {phone} to contacts...")
# Prepare the contact with a unique name
first_name = f"Friend{friend_count}" # Assign a unique name to each contact
contact = InputPhoneContact(client_id=0, phone=phone, first_name=first_name, last_name="")

# Add the contact to your Telegram account
result = client(ImportContactsRequest([contact]))
if result.users:
added_user_id = result.users[0].id # Get the ID of the added user
print(f"{phone} has been added to your contacts as {first_name} with ID {added_user_id}.")
added_file.write(f"{added_user_id}\n") # Log the added user's ID
friend_count += 1 # Increment to create the next friend's unique name
else:
print(f"Failed to add {phone}.")

# Wait for 6 seconds to avoid spamming
time.sleep(6)
except FloodWaitError as e:
print(f"FloodWaitError: Waiting for {e.seconds} seconds...")
time.sleep(e.seconds + 1) # Wait and retry after FloodWaitError
except Exception as e:
print(f"An error occurred: {e}")
time.sleep(6) # Adjust the delay for general errors
print("Adding contacts completed. Added user IDs saved to", output_file)

• Я автоматически отправляю этим контактам следующее сообщение...
import time
import random
from telethon.sync import TelegramClient
from telethon.errors import FloodWaitError, PeerFloodError, UserPrivacyRestrictedError
from telethon.tl.functions.contacts import GetContactsRequest
from telethon.tl.functions.messages import SendMessageRequest
# Replace with your Telegram API credentials
api_id = 'my id' # Replace with your api_id
api_hash = 'my hash' # Replace with your api_hash
# Your custom message
message = """
My Message
"""
# Initialize the Telegram client
with TelegramClient('telegram', api_id, api_hash) as client:
try:
# Get all contacts from Telegram
contacts = client(GetContactsRequest(hash=0)) # Get all contacts
for contact in contacts.users:
try:
phone = contact.phone
user_id = contact.id
print(f"Sending message to {phone}...")
# Send your custom message to the contact
try:
client(SendMessageRequest(user_id, message)) # Send custom message
print(f"Message sent to {phone}.")
except PeerFloodError:
print(f"PeerFloodError: Too many messages sent to {phone}. Try again later.")
break # Stop if we hit flood limits
except UserPrivacyRestrictedError:
print(f"UserPrivacyRestrictedError: User {phone} has privacy restrictions.")
except FloodWaitError as e:
print(f"FloodWaitError while sending message to {phone}: Waiting for {e.seconds} seconds...")
time.sleep(e.seconds + 1) # Wait and retry after FloodWaitError
except Exception as e:
print(f"Error sending message to {phone}: {e}")
time.sleep(random.randint(6, 10)) # Random delay for general errors
# Randomize delay to avoid triggering spam filters
delay = random.randint(20, 40) # Random delay between 20-40 seconds
print(f"Waiting for {delay} seconds to avoid spam...")
time.sleep(delay)
except Exception as e:
print(f"An error occurred: {e}")
time.sleep(random.randint(10, 20)) # Longer delay for general errors
except Exception as e:
print(f"An error occurred: {e}")
print("Messages sent to all contacts.") # Correct placement after all operations are done


Как бы вы исправили этот код или можете подсказать мне лучший вариант?
Я хочу автоматически отправлять сообщения 50 людям в день
 
Наконец он дал мне этот код
import time
import random
from telethon.sync import TelegramClient
from telethon.errors import FloodWaitError, PeerFloodError, UserPrivacyRestrictedError
from telethon.tl.functions.contacts import ImportContactsRequest
from telethon.tl.types import InputPhoneContact # Add this import
from telethon.tl.functions.messages import SendMessageRequest

# Replace with your Telegram API credentials
api_id = ' ID ' # Replace with your api_id
api_hash = ' HASH ' # Replace with your api_hash

# File paths on the desktop
input_file_check = r'C:\Users\x\Desktop\leads.txt' # File with phone numbers to check
output_file_valid = r'C:\Users\x\Desktop\Validate.txt' # Output file for valid numbers
delivery_log_file = r'C:\Users\x\Desktop\Delivery_Log.txt' # File for logging delivery status

# Your custom message
message = """
🎉 Message Here
"""

# Initialize the Telegram client
with TelegramClient('g30rg14n', api_id, api_hash) as client:
try:
# Step 1: Check phone numbers for validity
with open(input_file_check, 'r') as file:
phone_numbers = [line.strip() for line in file.readlines()]
except FileNotFoundError:
print(f"Input file not found: {input_file_check}")
exit(1)

with open(output_file_valid, 'a') as valid_file, open(delivery_log_file, 'a') as log_file:
for idx, phone in enumerate(phone_numbers, start=1):
try:
print(f"Checking line {idx}: {phone}...")
contact = InputPhoneContact(client_id=0, phone=phone, first_name="Check", last_name="User")
result = client(ImportContactsRequest([contact]))

if result.users:
print(f"{phone} has a Telegram account.")
valid_file.write(f"{phone}\n") # Write the valid phone number to the output file

# Send your custom message
client(SendMessageRequest(phone, message)) # Send custom message to the valid phone number

# Log the successful message delivery
log_file.write(f"Message successfully sent to {phone}.\n")
print(f"Successfully sent message to {phone} from your Telegram account.")

else:
print(f"{phone} does NOT have a Telegram account.")
log_file.write(f"{phone} does NOT have a Telegram account.\n")
print(f"Message not sent to {phone} (No Telegram account).")

# Wait 6 seconds to avoid spam
time.sleep(6)

except FloodWaitError as e:
print(f"FloodWaitError: Waiting for {e.seconds} seconds...")
time.sleep(e.seconds + 1) # Wait the time specified in the exception and retry

except Exception as e:
print(f"An error occurred: {e}") # Generic error handling for other issues
log_file.write(f"An error occurred with {phone}: {e}\n")
print(f"Error occurred with {phone}: {e}")
time.sleep(6) # Adjust the delay to avoid spam

print("Check completed. Valid numbers saved to", output_file_valid)
print("Messages sent to all valid numbers. Check delivery log for details.")
 


Напишите ответ...
  • Вставить:
Прикрепить файлы
Верх