How to get channels and groups data from my Telegram account?(Python) - python

How can I get last posts and messages from all channel and groups in my Telegram account using "telethon".

At first you should get your "api_id" and "api_hash" from Telegram API.
then you should use following code to connect to your Telegram account.
from telethon.sync import TelegramClient
from telethon.errors import SessionPasswordNeededError
# Create the client and connect
client = TelegramClient(you_username, api_id, api_hash)
client.start()
print("Client Created")
# Ensure you're authorized
if not client.is_user_authorized():
client.send_code_request(your_phone)
try:
client.sign_in(phone, input('Enter the code: '))
except SessionPasswordNeededError:
client.sign_in(password=input('Password: '))
In the next step we define a def to get last message of an entity (like channel or group):
from telethon.tl.functions.messages import GetHistoryRequest
def get_entity_data(entity_id, limit):
entity = client.get_entity(entity_id)
today = datetime.datetime.today()
# y = today - datetime.timedelta(days=1)
posts = client(GetHistoryRequest(
peer=entity,
limit=limit,
offset_date=None,
offset_id=0,
max_id=0,
min_id=0,
add_offset=0,
hash=0))
messages = []
for message in posts.messages:
messages.append(message.message)
return messages
This def gets id of a channel or group and limit on number of messages that we want to get from any channels and groups and returns the messages.
Then you should get all groups and channels using this code:
from telethon.tl.functions.messages import GetDialogsRequest
result = client(GetDialogsRequest(
offset_date=None,
offset_id=0,
offset_peer=InputPeerEmpty(),
limit=100,
hash=0))
entities = result.chats
And in last step you should iterate on entities and get last messages(for example 10 in following code)
for entity in entities:
title = entity.title
messages = get_entity_data(entity.id, 10)
print(title + ' :')
print(messages)
print('#######')

Related

How Do I Send a Message to a Privately Linked Group in Telegram with Python?

from telethon import TelegramClient, events, sync
client.start()
destination_group_invite_link=grouplink #t.me/xxxxxxx
entity=client.get_entity(destination_group_invite_link)
client.send_file(entity=entity, message="xxxx")
With this code I can send message to public linked group. But how do I send a message to a group with a private link?
#t.me/+xxxxxxxxx
first, you need to join the group, to do so:
from telethon.tl.functions.messages import ImportChatInviteRequest
^
|
(this will throw an error you are already in the group)
if you are already inside of the group:
from telethon.tl.functions.messages import CheckChatInviteRequest
code with ImportChatInviteRequest:
update = await client(ImportChatInviteRequest("Group link"))
group_to_search = (update.chats.Chat.id)
code with CheckChatInviteRequest: [for this you need the group link, specifically the hash, to find it you need to to replace "https://t.me/+" with a blank space]
group_to_search = await client(CheckChatInviteRequest(hash = link_to_search))
group_to_search = str(group_to_search.chat.id)
I Solved the Problem.
Just specify the id of the group as the target. And it works :) Thanks for the #kekkoilmedikit help
Here are all my codes. I don't understand how to do what you said man. #kekkoilmedikit
from telethon import TelegramClient, events, sync
import re
from colorama import Fore, Back, Style, init
import time
api_id = ....
api_hash = ''
client = TelegramClient('anon', api_id, api_hash)
group = input(Fore.CYAN + "Group Name >>>>> ")
second = input(Fore.CYAN + "Second >>>>> ")
secenek = input(Fore.CYAN + """
Press 1 to Send Message!
Press 2 to Send Picture!
>>>>>>>>>>>>>>>>>>>>>>> """)
if (float(secenek) == 1):
send = input(Fore.RED + " Enter Message to Send >>>>> ")
while(True):
init(autoreset=True)
client.start()
destination_channel_username=group
entity=client.get_entity(destination_channel_username)
client.send_message(entity=entity,message=send)
time.sleep(float(second))
if (float(secenek) == 2):
send = input(Fore.RED + " Gönderilcek Resmin Yolunu Giriniz >>>>> ")
while(True):
init(autoreset=True)
client.start()
destination_channel_username=group
entity=client.get_entity(destination_channel_username)
client.send_file(entity=entity, file=send)
time.sleep(float(second))

How would i go on scraping only online telegram members from a group?

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

Telethon reading message from Channel with id

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 want to send an auto reply to a new chat with whom i havent had a conversation earlier on Telegram

I'm new to Python and Telethon.
I've gone through the documentation of Telethon module.
I would like to send auto reply to a new person if they send me a message on Telegram private message.
I've found one (in this gist)
which sends an autoreply to every incoming private chat. but i want to send a reply to new people only.
please guide
i want to check if user is present in the df below and send a reply accordingly.
code to get list of dialog id's is as below:
import time
from telethon import TelegramClient
from telethon import events
import pandas as pd
api_id = 123456
api_hash = 'enterownapihash'
# fill in your own details here
phone = '+111111111'
session_file = 'username' # use your username if unsure
password = 'passwords' # if you have two-step verification enabled
client = TelegramClient(session_file, api_id, api_hash, sequential_updates=True)
xyz = pd.DataFrame()
z = pd.DataFrame()
client.connect()
client.start()
for dialog in client.iter_dialogs():
x = dialog.id
y = dialog.title
#print('{:>14}: {}'.format(dialog.id, dialog.title))
xyz['dialog id'] = [x]
xyz['username'] = [y]
z = pd.concat([z,xyz],ignore_index= True)
print(xyz)
print(z)
EDIT:
below is the code i've tried which hasnt worked.
import time
from telethon import TelegramClient
from telethon import events
import pandas as pd
api_id = 123456
api_hash = 'enterownapihash'
# fill in your own details here
phone = '+111111111'
session_file = 'username' # use your username if unsure
password = 'passwords' # if you have two-step verification enabled
# content of the automatic reply
message = "Hello!"
client = TelegramClient(session_file, api_id, api_hash, sequential_updates=True)
xyz = pd.DataFrame()
z = pd.DataFrame()
#client.connect()
#client.start()
for dialog in client.iter_dialogs():
x = dialog.id
y = dialog.title
print('{:>14}: {}'.format(dialog.id, dialog.title))
xyz['x'] = [x]
xyz['y'] = [y]
z = pd.concat([z,xyz],ignore_index= True)
if __name__ == '__main__':
#client.on(events.NewMessage(incoming=True))
async def handle_new_message(event):
if event.is_private: # only auto-reply to private chats
from_ = await event.client.get_entity(event.from_id) # this lookup will be cached by telethon
if event.client.get_entity != z['x'].values:
if not from_.bot: # don't auto-reply to bots
print(time.asctime(), '-', event.message) # optionally log time and message
time.sleep(1) # pause for 1 second to rate-limit automatic replies
await event.respond(message)
client.start(phone, password)
client.run_until_disconnected()
One way to do this is to fetch all the IDs present in your dialogs on start up. When a new message arrives, if their ID is not there, you know it's a new person (the code assumes you run it inside an async def):
async def setup():
users = set()
async for dialog in client.iter_dialogs():
if dialog.is_user:
users.add(dialog.id)
# later, on a handler
async def handler(event):
if event.is_private and event.sender_id not in users:
# new user
Another option is to use messages.GetPeerSettingsRequest, which will have result.report_spam as True when it's a new chat. Ideally, you would also cache this:
user_is_new = {}
async def handler(event):
if event.is_private:
if event.sender_id not in user_is_new:
res = client(functions.messages.GetPeerSettingsRequest(event.sender_id))
# if you can report them for spam it's a new user
user_is_new[event.sender_id] = res.report_spam
if user_is_new[event.sender_id]:
# new user

How to get the list of (more than 200) members of a Telegram channel

Ok, let's start by saying that i'm a Python total noob.
So, I'm working with Telethon to get the entire (more than 200) member list of a Telegram channel.
Trying, trying and trying again, I found that this piece of code is perfect to reach my goal, if it were not that it prints only first 200 members.
from telethon import TelegramClient, sync
# Use your own values here
api_id = xxx
api_hash = 'xxx'
name = 'xxx'
channel = 'xxx'
client = TelegramClient('Lista_Membri2', api_id, api_hash)
try:
client.start()
# get all the channels that I can access
channels = {d.entity.username: d.entity
for d in client.get_dialogs()
if d.is_channel}
# choose the one that I want list users from
channel = channels[channel]
# get all the users and print them
for u in client.get_participants(channel):
print(u.id, u.first_name, u.last_name, u.username)
#fino a qui il codice
finally:
client.disconnect()
Someone has the solution?
Thanks!!
Have you looked at the telethon documentation? It explains that Telegram has a server-side limit of only collecting the first 200 participants of a group. From what I see, you can use the iter_participants function with aggressive = True to subvert this problem:
https://telethon.readthedocs.io/en/latest/telethon.client.html?highlight=200#telethon.client.chats.ChatMethods.iter_participants
I haven't used this package before, but it looks like you can just do this:
from telethon import TelegramClient
# Use your own values here
api_id = 'xxx'
api_hash = 'xxx'
name = 'xxx'
channel = 'xxx'
client = TelegramClient('Lista_Membri2', api_id, api_hash)
client.start()
# get all the channels that I can access
channels = {d.entity.username: d.entity
for d in client.get_dialogs()
if d.is_channel}
# choose the one that I want list users from
channel = channels[channel]
# get all the users and print them
for u in client.iter_participants(channel, aggressive=True):
print(u.id, u.first_name, u.last_name, u.username)
#fino a qui il codice
client.disconnect()

Categories

Resources