Skip to content

Instantly share code, notes, and snippets.

@ronik56
Last active January 4, 2024 14:21
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save ronik56/67ff4e5eee46c501686e436060649e6a to your computer and use it in GitHub Desktop.
Save ronik56/67ff4e5eee46c501686e436060649e6a to your computer and use it in GitHub Desktop.
script to leave all telegram groups
from telethon.sync import TelegramClient
from telethon.tl.functions.messages import GetDialogsRequest
from telethon.tl.types import InputPeerEmpty
# Go to https://my.telegram.org/apps, sign in, go to API development tools, create an app, copy and paste below:
api_id = 111111
api_hash = '2o23o13k1o3131'
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: ')) # Enter the login code sent to your telegram
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)
"""
Megagroups are groups of more than 200 people, if you want to leave
smaller groups as well delete this part. If you want to stay in a few
specific groups, add their titles to the groups_to_exclude list.
"""
groups_to_exclude = ['group title']
for chat in chats:
try:
if chat.megagroup== True and chat.title not in groups_to_exclude:
client.delete_dialog(chat)
except:
continue
@FrozenStoneCamper
Copy link

How do I execute this? :'(

@ronik56
Copy link
Author

ronik56 commented Aug 3, 2022

You need to run the following in the command line from the file's folder:
python3 leave_all_telegram_groups.py

Just make sure you have Telethon installed and don't forget to change the api_id, api_hash, and phone on lines 5-7.

@OseleChidera
Copy link

OseleChidera commented Aug 12, 2022

hmn
trying to run it
telethon is installed running python 3.9.6
so i keep on getting "ModuleNotFoundError: No module named 'telethon'"

@ronik56
Copy link
Author

ronik56 commented Aug 12, 2022

That's weird. I tried running it and didn't get the error.
Did you install telethon with pip3? If not it migth be because you installed it just for python2

@naut20161990
Copy link

help me !
image

thanks bro

@ronik56
Copy link
Author

ronik56 commented Nov 11, 2022

help me !

thanks bro

@naut20161990
You need to add the following code below line 8 in your code (phone = ...):
client = TelegramClient(phone, api_id, api_hash)

@naut20161990
Copy link

naut20161990 commented Nov 11, 2022

from telethon.sync import TelegramClient
from telethon.tl.functions.messages import GetDialogsRequest
from telethon.tl.types import InputPeerEmpty

api_id = xxx
api_hash = 'xxx'
phone = '+xxx'

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: '))

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)

groups_to_exclude = ['https://t.me/Uniswapchina']

for chat in chats:
try:
if chat.megagroup== True and chat.title not in groups_to_exclude:
client.delete_dialog(chat)
except:
continue

I did that and after entering the code, I got an error like this, can you help me

PS C:\Users\NC> & C:/Users/NC/AppData/Local/Programs/Python/Python310/python.exe c:/Users/NC/Desktop/clearnhom.py
Enter the code: 79395
Traceback (most recent call last):
File "c:\Users\NC\Desktop\clearnhom.py", line 14, in
client.sign_in(phone, input('Enter the code: '))
File "C:\Users\NC\AppData\Local\Programs\Python\Python310\lib\site-packages\telethon\sync.py", line 39, in syncified
return loop.run_until_complete(coro)
File "C:\Users\NC\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 646, in run_until_complete
return future.result()
File "C:\Users\NC\AppData\Local\Programs\Python\Python310\lib\site-packages\telethon\client\auth.py", line 369, in sign_in
result = await self(request)
File "C:\Users\NC\AppData\Local\Programs\Python\Python310\lib\site-packages\telethon\client\users.py", line 30, in call
return await self._call(self._sender, request, ordered=ordered)
File "C:\Users\NC\AppData\Local\Programs\Python\Python310\lib\site-packages\telethon\client\users.py", line 84, in _call
result = await future
telethon.errors.rpcerrorlist.SessionPasswordNeededError: Two-steps verification is enabled and a password is required (caused by SignInRequest)
PS C:\Users\NC>

@ronik56
Copy link
Author

ronik56 commented Nov 11, 2022

@naut20161990
First, you shouldn't post your API hash, API id, and phone number. Please edit your messages and censor it/remove the image.

You get an error because this account uses two-step verification.
You have two options:

  1. Temporarily remove the two-step verification from your account (should be in Settings -> Privacy and Security), run the script, and when it's done re-enable it.
  2. Use the following modified code and enter the password when prompted (I removed your API info and phone so don't forget to add it):
from telethon.sync import TelegramClient
from telethon.tl.functions.messages import GetDialogsRequest
from telethon.tl.types import InputPeerEmpty

api_id = 1
api_hash = ''
phone = ''

client = TelegramClient(phone, api_id, api_hash)
client.connect()
if not client.is_user_authorized():
    y = client.send_code_request(phone)
    client.sign_in(phone=phone, password=input('password : '), code=input('code :'), phone_code_hash=y.phone_code_hash)

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)

groups_to_exclude = ['https://t.me/Uniswapchina']

for chat in chats:
    try:
        if chat.megagroup== True and chat.title not in groups_to_exclude:
            client.delete_dialog(chat)
    except:
        continue

@naut20161990
Copy link

naut20161990 commented Nov 15, 2022

@naut20161990 First, you shouldn't post your API hash, API id, and phone number. Please edit your messages and censor it/remove the image.

You get an error because this account uses two-step verification. You have two options:

  1. Temporarily remove the two-step verification from your account (should be in Settings -> Privacy and Security), run the script, and when it's done re-enable it.
  2. Use the following modified code and enter the password when prompted (I removed your API info and phone so don't forget to add it):
from telethon.sync import TelegramClient
from telethon.tl.functions.messages import GetDialogsRequest
from telethon.tl.types import InputPeerEmpty

api_id = 1
api_hash = ''
phone = ''

client = TelegramClient(phone, api_id, api_hash)
client.connect()
if not client.is_user_authorized():
    y = client.send_code_request(phone)
    client.sign_in(phone=phone, password=input('password : '), code=input('code :'), phone_code_hash=y.phone_code_hash)

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)

groups_to_exclude = ['https://t.me/Uniswapchina']

for chat in chats:
    try:
        if chat.megagroup== True and chat.title not in groups_to_exclude:
            client.delete_dialog(chat)
    except:
        continue

thank you very much

@naut20161990
Copy link

hi, thanks buddy for helping me, but i have a new thing. What if I have multiple accounts that I want to delete?

api_id = 1
api_hash = '1'
phone = '+1'

api_id = 2
api_hash = '2'
phone = '+2'
..........
.............
.............
api_id = 30
api_hash = '30'
phone = '+30'

Can you guide me how to do that? Thank you very much

@ronik56
Copy link
Author

ronik56 commented Nov 19, 2022

@naut20161990 You can put the code inside a loop that runs on a list with the accounts. For example:

from telethon.sync import TelegramClient
from telethon.tl.functions.messages import GetDialogsRequest
from telethon.tl.types import InputPeerEmpty

# A list of lists with user info
users = [ [1, '1', '+1'],  # Stands for [api_id, api_hash, phone]
            [2, '2', '+2'], 
            ... 
            [30, '30', '+30'] ]


for user in users:
    api_id = user[0]
    api_hash = user[1]
    phone = user[2]
    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: ')) # Enter the login code sent to your telegram 

    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)
    """
    Megagroups are groups of more than 200 people, if you want to leave 
    smaller groups as well delete this part. If you want to stay in a few 
    specific groups, add their titles to the groups_to_exclude list.
    """
    groups_to_exclude = ['group title']

    for chat in chats:
        try:
            if chat.megagroup== True and chat.title not in groups_to_exclude:
                client.delete_dialog(chat)
        except:
            continue

@naut20161990
Copy link

it's awesome, it's working fine, again thank you so much

@hernandez2016
Copy link

Hi bro, I have a question can you help me?
I want to delete all chat, what should I do, like the picture I attached
Thank you so much bro
screenshot_1669443281

@ronik56
Copy link
Author

ronik56 commented Nov 26, 2022

@hernandez2016 Delete the mega-group condition on line 37. Your if statement should look like this:
if chat.title not in groups_to_exclude:

@hernandez2016
Copy link

@hernandez2016 Delete the mega-group condition on line 37. Your if statement should look like this: if chat.title not in groups_to_exclude:

I followed it but it doesn't seem to work

@ronik56
Copy link
Author

ronik56 commented Nov 27, 2022

@hernandez2016 Did you enter the phone, API ID , API hash, and login code?

@hernandez2016
Copy link

@hernandez2016 Did you enter the phone, API ID , API hash, and login code?

I did that but just delete the group, all chats are still intact
image
screenshot_1669958456

@naut20161990
Copy link

import sys
from telethon import TelegramClient
import time
import datetime
from datetime import date
import os, os.path
import asyncio
from telethon import errors

######## API CONFIG #######
#nick1
#api_id=21578781 # Insert api id (int)
#api_hash = '79bac46bfaf8fcff8ae4fa3526743e62' # Insert api hash (string)
#nick 2
#api_id=2 # Insert api id (int)
#api_hash = '2' # Insert api hash (string)
#nick n
#api_id=n # Insert api id (int)
#api_hash = 'n' # Insert api hash (string)
users = [ [21578781, '79bac46bfaf8fcff8ae4fa3526743e62'], # Stands for [api_id, api_hash, phone]
[24721605, 'ac85efbca1b235a39efb6874271b9bf9'] ]
for user in users:
api_id = user[0]
api_hash = user[1]

####### SET GROUPS TO MESSAGE #######

groups = ['botqc321'] # Insert the group usernames as shown above. You must have previously joined them.

gset=set(groups)
groups=list(gset) # eliminate duplicates

####### END GET SHILL GROUPS #####

async def work():
async with TelegramClient('anon',api_id,api_hash) as client:
while(True):
failcount=0

            ###### MESSAGE SETTING ######
            
            message = open('chat.txt').readline()
           
            
           
           

            #############################
            
            for x in groups:
                try:                     
                    await client.send_message(x,message) # SEND MESSAGE
                    print('Sent to group: ' + x)
                    time.sleep(15) # 1 SECOND SLEEP BETWEEN GROUPS
                    
                except errors.FloodWaitError as e:
                    print('FLOODED FOR ', e.seconds)
                    print("Getting Flood Error from telegram. Script is stopping now. Please try again after some time.")
                    time.sleep(e.seconds+2)
                    failcount+=1
                except Exception as e:
                    print("Error:", e)
                    print("Trying to continue...")
                    print(x, sys.exc_info()[0])
                    failcount+=1
                    continue

####### Asyncio and loop handling #######

try:
loop = asyncio.get_running_loop()
except RuntimeError: # 'RuntimeError: There is no current event loop...'
loop = None

if loop and loop.is_running():
print('Async event loop already running. Adding coroutine to the event loop.')
tsk = loop.create_task(work())
# ^-- https://docs.python.org/3/library/asyncio-task.html#task-object
# Optionally, a callback function can be executed when the coroutine completes
tsk.add_done_callback(
lambda t: print(f'Task done with result={t.result()} << return val of main()'))
else:
print('Starting new event loop')
asyncio.run(work())

hi pro

Can you fix this program?
The program i am writing only takes first account and first line in chat.txt file , it does not work with 2nd account ,3 ....n and lines 2,3,...n in file chat.txt .
I need multiple accounts to send messages to botqc321 group and these accounts get message data from file chat.txt , each account will read each line in chat.txt file to send to botqc321 group and will repeat at end of line in file chat .txt
Thanks pro

@eramax
Copy link

eramax commented Mar 8, 2023

Thanks for sharing, It didn't work well with me, I developed a new one https://gist.github.com/eramax/2a651152cbbb4c73d9b9e63e869abea9
Best,

@zodwick
Copy link

zodwick commented Jan 4, 2024

Thank you , added some features and made a new one https://gist.github.com/zodwick/46c7fd398e4616ded6dc5e0bc38da9fd , Hope it helps.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment