from telethon.sync import TelegramClient
from telethon.tl.functions.messages import GetDialogsRequest
from telethon.tl.types import InputPeerEmpty
api_id = XXXXXXX
api_hash = 'XXXXXXXXXXXXXXXXXXXXXXXX'
phone = '+XXXXXXXXXXX'
client = TelegramClient(phone, api_id, api_hash)
client.connect()
if not client.is_user_authorized():
client.send_code_request(phone)
phone_code_hash = client.send_code_request(phone).phone_code_hash
client = TelegramClient(phone, api_id, api_hash)
client.connect()
client.sign_in(phone, input('Enter the code: '))
How can I pass it on phone_code_hash to the check client.sign_in(phone, input('Enter the code: '))
If you do not insert the cache, an error occurs valueerror: you also need to provide a phone_code_hash.
The hash must be entered in the fifth entry
client = TelegramClient(phone, api_id, api_hash)
client.connect()
if not client.is_user_authorized():
client.send_code_request(phone)
phone_code_hash = client.send_code_request(phone).phone_code_hash
client = TelegramClient(phone, api_id, api_hash)
client.connect()
client.sign_in(phone, input('Enter the code: '), phone_code_hash=phone_code_hash)
I took the answer from here https://github.com/LonamiWebs/Telethon/blob/9445d2ba535ed7d214a7e6e68b85e7f3af1a690e/telethon/telegram_client.py#L141-L149
Related
At the moment, I was implementing a system using telethon and telebot, you yourself understand - an error occurs with thread, this option does not suit me, is there any other way to check an account by phone number? Or what can replace telethon? I tried in pyrogram - I could not figure it out. I would be grateful if you send the code / tell me what can be used.
Here is the implementation of my code
#Telegram Bot Library
import telebot
from telebot import types
import random
import requests as req
from bs4 import BeautifulSoup
#Telegram Library
from telethon.sync import TelegramClient
from telethon.tl.functions.contacts import ImportContactsRequest
from telethon.tl.types import InputPeerEmpty, InputPeerChannel, InputPeerUser, InputPhoneContact
import configparser
cpass = configparser.RawConfigParser()
cpass.read('config.data')
try:
api_id = cpass['cred']['id']
api_hash = cpass['cred']['hash']
phone = cpass['cred']['phone']
client = TelegramClient(phone, api_id, api_hash)
except KeyError:
print("[!] для начала заполните все поля в config.data")
client.connect()
if not client.is_user_authorized():
client.send_code_request(phone)
client.sign_in(phone, input('[+] введите код от телеграмм : '))
token = ""
bot = telebot.TeleBot(token)
user_data= {
'number': ''
}
#bot.message_handler(commands=['start', 'go'])
def start_handler(message):
msg = bot.send_message(message.chat.id, 'Здравствуйте! Я создан специально для sexcall.su.\nНапишите номер телефона пользователя :')
bot.register_next_step_handler(msg, user_number)
def user_number(message):
user_data['number'] = message.text
msg = bot.send_message(message.chat.id, 'Отлично, происходит проверка аккаунта, требуется ввести капчу:')
bot.register_next_step_handler(msg, getresults)
def getresults(message):
#Checking the received number via telethon
contact = InputPhoneContact(client_id=0, phone={user_data['number']}, first_name="custom_first_name", last_name="custom_last_name")
result = client(ImportContactsRequest([contact]))
#if the account is not found - display a message
if not client.get_entity({user_data['number']}):
bot.send_message(message.chat.id,"К сожалению, у данного пользователя нет телеграмма, пожалуйста, введите номер телефона : ")
#bot.register_next_step_handler(msg, number)
#If the account is found, execute the following code
else:
url = 'http://******/ocean/oceansite_balance.php?to=%s' % ({user_data['phone']})
resp = req.get(url)
soup = BeautifulSoup(resp.text, 'lxml')
if int(soup.p.string.strip()) == 0:
bot.send_message(message.chat.id,"К сожалению, у данного пользователя не достаточно средств, пожалуйста, введите номер телефона : ")
#bot.register_next_step_handler(msg, number)
bot.infinity_polling()
Code:
client = TelegramClient('session_name', api_id, api_hash)
client.start()
async def FirstFunction():
await client(AddChatUserRequest(
chat_id=1234,
user_id=1234,
fwd_limit=10
))
client.loop.run_until_complete(FirstFunction())
Error:
ValueError: Could not find the input entity for PeerUser(user_id=1234) (PeerUser).
Note: I am using the same id for chat_id + user_id
So i found this piece of code somewhere on stackoverflow:
from telethon.sync import TelegramClient
from telethon.tl.functions.messages import GetDialogsRequest
from telethon.tl.types import InputPeerEmpty
from telethon.sync import TelegramClient
from telethon.tl.functions.messages import GetDialogsRequest
from telethon.tl.types import InputPeerEmpty, InputPeerChannel, InputPeerUser
from telethon.errors.rpcerrorlist import PeerFloodError, UserPrivacyRestrictedError
from telethon.tl.functions.channels import InviteToChannelRequest
import sys
import csv
import traceback
import time
from datetime import datetime
api_id = 123456789 #Enter Your 7 Digit Telegram API ID.
api_hash = '123456789' #Enter Yor 32 Character API Hash.
phone = '123456789'
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 recieved to your Telegram messenger: '))
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
print('Choose a group to scrape members from:')
i=0
for g in groups:
print(str(i) + '- ' + g.title)
i+=1
g_index = input("Enter a Number: ")
target_group=groups[int(g_index)]
print('Fetching Members...')
all_participants = []
all_participants = client.get_participants(target_group, aggressive=True)
print('Saving In file...')
with open("Scraped.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','last seen'])
for user in all_participants:
accept=True
try:
lastDate=user.status.was_online
num_months = (datetime.now().year - lastDate.year) * 12 + (datetime.now().month - lastDate.month)
if(num_months>1):
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,user.status])
print('Members scraped successfully.')
And this pretty much scrapes online & recently active members, how would i change this to ONLY scrape online members? I tried looking into the telethon docs but i don't seem to understand...
I'm not sure where else to ask for help regarding this issue so here i am...
Any sort of help is highly appreciated!
Thank you.
Scraping ONLY online members is not possible.
Try something like this:
import telethon
from telethon.sync import TelegramClient, events
from telethon.tl.functions.channels import GetParticipantsRequest
from telethon.tl.types import InputChannel
from telethon.tl.types import ChannelParticipantsSearch
from telethon.tl.functions.channels import GetFullChannelRequest
api_id = 123567
api_hash = "dsaopdas2131"
client = TelegramClient("RDJR", api_id, api_hash)
#client.on(events.NewMessage())
async def handler(event):
chat_id = event.message.peer_id.channel_id
offset = 0
limit = 200
my_filter = ChannelParticipantsSearch('')
channel = await client(GetFullChannelRequest(chat_id))
participants = await client(GetParticipantsRequest(channel=chat_id, filter=my_filter, offset=offset, limit=limit, hash=0))
for x in participants.users:
print(x.status)
with client as client:
print("USER_BOT ONLINE!")
client.run_until_disconnected()
You need to get all of the participants of a group/channel, then iterate them to print the status.
The output would be something like this:
User online:
UserStatusOnline(expires=datetime.datetime(2021, 7, 6, 21, 6, 22, tzinfo=datetime.timezone.utc))
Or:
None
User offline:
UserStatusOffline(was_online=datetime.datetime(2021, 7, 6, 18, 19, 35, tzinfo=datetime.timezone.utc))
Hello I'm using Telethon 1.21.1
The most question here are outdated.
This scripts task is to read a message of a specific Channel per id.
I'm not sure where to pass the info for the channel and how if I use the method to read the msg in the proper way. await but I'm not sure how I pull it off
This is what I have:
my_private_channel_id = "-100777000"
my_private_channel = "test"
api_id = # 7 Digit Telegram API ID.
api_hash = '' # 32 Character API Hash
phone = '+' #Enter Your Mobilr Number
client = TelegramClient(phone, api_id, api_hash)
async def main():
await client.send_message('me', 'Hello !!!!') # just to test connection
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('Enter verification code: '))
chats = []
last_date = None
chunk_size = 200
channels=[] #target channel
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.channels== True:
readmsg = client.get_messages(chat, None)
except:
continue
from telethon import TelegramClient, events
client = TelegramClient('session', api_id, api_hash)
#client.on(events.NewMessage(chats="#TelethonUpdates"))
async def my_event_handler(event):
print(event.text)
client.start()
client.run_until_disconnected()
This is the right and simple way.
I need help with this code.
A month ago, I modified it to fit with me.
since three days, I suffer from an error that I could not fix .. He used to work before and now no
Thank you so much.
This is the source of the project
I have just modified the previous mistakes
I'm a beginner with only a month and a half experience
https://github.com/P-Alban/Telegram-collector
import sys
from getpass import getpass
from time import sleep
from telethon import TelegramClient
from telethon.errors import SessionPasswordNeededError
from telethon.errors import UsernameNotOccupiedError
from telethon.errors import FloodWaitError
from telethon.tl.functions.channels import GetParticipantsRequest
from telethon.tl.functions.contacts import ResolveUsernameRequest
from telethon.tl.types import ChannelParticipantsSearch, InputChannel
# First you need create app on https://my.telegram.org
api_id = api_id
api_hash = 'api_hash'
phone = '+....Phone'
limit = 100
def get_chat_info(username, client):
try:
chat = client(ResolveUsernameRequest(username))
except UsernameNotOccupiedError:
print('Chat/channel not found!')
sys.exit()
result = {
'chat_id': chat.peer.channel_id,
'access_hash': chat.chats[0].access_hash
}
return result
def dump_users(chat, client):
counter = 0
offset = 0
chat_object = InputChannel(chat['chat_id'], chat['access_hash'])
all_participants = []
print('Process...')
while True:
participants = client.invoke(GetParticipantsRequest(
chat_object, ChannelParticipantsSearch(''), offset, limit
))
if not participants.users:
break
all_participants.extend(['{} {}'.format(x.id, x.username)
for x in participants.users])
users_count = len(participants.users)
offset += users_count
counter += users_count
print('{} users collected'.format(counter))
sleep(2)
with open('users.txt', 'w') as file:
file.write('\n'.join(map(str, all_participants)))
def main():
channel_name = input('Input a channel name, without "#": ')
client = TelegramClient(phone, api_id, api_hash)
print('Connecting...')
client.connect()
if not client.is_user_authorized():
try:
client.send_code_request(phone)
print('Sending a code...')
client.sign_in(phone, code=input('Enter code: '))
print('Successfully!')
except FloodWaitError as FloodError:
print('Flood wait: {}.'.format(FloodError))
sys.exit()
except SessionPasswordNeededError:
client.sign_in(password=getpass('Enter password: '))
print('Successfully!')
dump_users(get_chat_info(channel_name, client), client)
print('Done!')
if __name__ == '__main__':
main()