Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Why are all sessions terminated when running the telethon script? #4321

Closed
laminda opened this issue Feb 29, 2024 · 1 comment
Closed

Why are all sessions terminated when running the telethon script? #4321

laminda opened this issue Feb 29, 2024 · 1 comment

Comments

@laminda
Copy link

laminda commented Feb 29, 2024

Code that causes the issue

from telethon.errors import SessionPasswordNeededError
from telethon.sync import TelegramClient
from telethon.tl.functions.messages import GetDialogsRequest
from telethon.tl.types import InputPeerEmpty
import os, sys
import configparser
import csv
import time
import re




re="\033[1;31m"
gr="\033[1;32m"
cy="\033[1;36m"
yo="\033[1;33m"
def banner():
    print(f"""
{re}╔╦╗{cy}┌─┐┬  ┌─┐{re}╔═╗  ╔═╗{cy}┌─┐┬─┐┌─┐┌─┐┌─┐┬─┐
{re} ║ {cy}├┤ │  ├┤ {re}║ ╦  ╚═╗{cy}│  ├┬┘├─┤├─┘├┤ ├┬┘
{re} ╩ {cy}└─┘┴─┘└─┘{re}╚═╝  ╚═╝{cy}└─┘┴└─┴ ┴┴  └─┘┴└─

            Version: 1.3
     Modified by @AbirHasan2005
        """)



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:
    os.system('clear')
    banner()
    print("\033[91m[!] run \033[92mpython3 setup.py \033[91mfirst !!\n")
    sys.exit(1)




client.connect()
if not client.is_user_authorized():
    client.send_code_request(phone)
    os.system('clear')
    banner()
    try:
        client.sign_in(phone, input(gr+'[+] Enter the verification code: '+yo))
    except SessionPasswordNeededError:
        password = input(gr+'[+] Two-step verification is enabled. Please enter your password: '+yo)
        client.sign_in(password=password)

os.system('clear')
banner()
chats = []
last_date = None
chunk_size = 90000 # лимиты сбора, но изменнеия не помогают
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(gr+'[+] Choose a group to scrape members:'+re)
for i, g in enumerate(groups):
    print(gr+'['+cy+str(i)+']' + ' - ' + g.title)
print('')
g_index = input(gr+"[+] Enter a Number: "+re)
target_group=groups[int(g_index)]

print(gr+'[+] Fetching Members ...')
time.sleep(1)
all_participants = []
all_participants = client.get_participants(target_group, aggressive=True)

print(gr+'[+] Saving in file ...')
time.sleep(1)



cleaned_title = target_group.title.replace('<', '_').replace('>', '_').replace(':', '_').replace('"', '_').replace('/', '_').replace('\\', '_').replace('|', '_').replace('?', '_').replace('*', '_')
with open(f"{cleaned_title}.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', 'phone' ])
    for user in all_participants:
        username = user.username or ""
        first_name = user.first_name or ""
        last_name = user.last_name or ""
        name = (first_name + ' ' + last_name).strip()
        phone = user.phone or ""


        writer.writerow([username,user.id,user.access_hash,name,target_group.title, target_group.id, phone])
print(gr+'[+] Members scraped successfully!')````

### Expected behavior

I expected the session to be created after entering the short number and password from the telegram account. And so it happened, but only after 10 seconds all sessions were closed.

### Actual behavior

I wrote a script on telethon, but after logging in and creating a session file, for some reason all sessions in telegram end, that is, the telegram account exits from all devices. As a result, you have to log in to your account again on all devices, but the script does not work because telegram ends the telethon client session. I've tried different scripts, my own and others', but they all give the same result. What could be the problem?


### Traceback

_No response_

### Telethon version

1.34.0

### Python version

3.9

### Operating system (including distribution name and version)

Windows 10

### Other details

IDE Pycharm 

### Checklist

- [X] The error is in the library's code, and not in my own.
- [X] I have searched for this issue before posting it and there isn't an open duplicate.
- [X] I ran `pip install -U https://github.com/LonamiWebs/Telethon/archive/v1.zip` and triggered the bug in the latest version.
@Lonami
Copy link
Member

Lonami commented Feb 29, 2024

#4051.

@Lonami Lonami closed this as completed Feb 29, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants