Error when parsing the group chat in telegram - python

I wrote a script for the documentation of pyrogram for parsing messages in public chats, but it either gives me an error, or does not give anything at all, here is the code:
from pyrogram import Client
api_id = 272347
api_hash = '235ausfhi...'
gruppa = 'xxx'
with Client('sessia1', api_id, api_hash) as app:
spis_mas = []
for message in app.iter_history(gruppa):
spis_mas.append(message.text)
with open('spis_of_mes.txt', 'w') as file:
for mem in spis_mas:
file.write(str(mem) + '\n')
Here is the error:
[sessia1] Sleeping for 26s (required by "channels.GetMessages")

That is not an Error -
You cant get a all history with iter_history in one time
you should wait to iter_history generator finish !

Related

How to remove the error 400 PEER_ID_INVALID?

import asyncio
from pyrogram import Client
from pyrogram.errors import PeerFlood
import time
api_id = 12905662
api_hash = "a7cfcd44cb95d26d7529d547c9a1d9ef"
vubor = input('Напишите "1" для парсинга, "2" для рассылки! ')
text = input('Текст для рассылки: ')
account = ['my_accont1', 'my_accont2', 'my_accont3', 'my_accont4', 'my_accont5', 'my_accont6', 'my_accont7',
'my_accont8', 'my_accont9']
async def main():
if vubor == '1':
user = []
with open('username.txt', 'r') as file:
for users in file.readlines():
y = users.strip()
user.append(y)
for acc in account:
try:
async with Client(f"{acc}", api_id, api_hash) as app:
for all_user in user[0:500]:
time.sleep(5)
await app.send_message(all_user, text)
user.remove(all_user)
except PeerFlood:
print('Аккаунт заблокировн')
asyncio.run(main())
pyrogram.errors.exceptions.bad_request_400.PeerIdInvalid: Telegram says: [400 PEER_ID_INVALID] - The peer id being used is invalid or not known yet. Make sure you meet the peer before interacting with it
Firstly, please learn how to ask a good question.
Secondly, your error message is already clear, you have to
Make sure you meet the peer before interacting with it
This means your session has to receive a message from them directly or via a shared chat, or have your session see any update to do with them in general.

Change user rights in teletbon

I'm trying to change the rights of group members/administrators according to the example in the telethon documentation:
https://telethonn.readthedocs.io/en/latest/extra/examples/chats-and-channels.html#admin-permissions,
But the problem is that the required ChannelAdminRights class simply does not exist and I get an ImportError error: cannot import name 'ChannelAdminRights' from 'telethon.tl.types'
How do I change my member rights? (I use Google Translate)
This might help you:
https://docs.telethon.dev/en/latest/modules/client.html?highlight=restrict#telethon.client.chats.ChatMethods.edit_permissions
Here's the code:
from telethon.sync import TelegramClient
import telethon
from datetime import timedelta
api_id = 12345
api_hash = "dddddd"
with TelegramClient("anon", api_id, api_hash) as client:
client.start()
client.connect()
chat_id = client.get_entity("username / chat_id / Title").id
users = client.get_participants(chat_id)
client.edit_permissions(chat_id, users[3], timedelta(minutes = 60), send_messages = False)
With this code, a bot/userbot will mute for one hour an user.
Yeah, that's exactly what I need! I just ran this code and faced with the problem that this method works only for channels and megpgroup, and I have a chat...
Error text:
raise ValueError('You must pass either a channel or a supergroup')
ValueError: You must pass either a channel or a supergroup

How can I scrape Telegram users from a Telegram Group?

So I've been trying for a long time, I found some pre-made programs, but they costs 100$. I've tried multiple apps and programs like Telegram Auto and Telegram Kit, but they cost a lot and I don't have such money right now.
I am trying to do it in Python and Telethon(Don't have a lot of experience in it)
I already made an app on telegram developer tools, got the API Number and Hash, and found the following code online
from telethon.tl.functions.messages import GetDialogsRequest
from telethon.tl.types import InputPeerEmpty
import csv
api_id = My API ID
api_hash = 'MY API HASH'
phone = 'MY PHONE'
client = TelegramClient(phone, api_id, api_hash)
client.connect()
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("members.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'])
for user in all_participants:
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])
print('Members scraped successfully.')
I entered My information, and I started the program, but I keep getting this error.
Traceback (most recent call last):
File "c:\Users\User\Desktop\export.py", line 23, in
hash = 0
File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\telethon\sync.py", line 39, in syncified
return loop.run_until_complete(coro)
File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\asyncio\base_events.py", line 579, in run_until_complete
return future.result()
File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\telethon\client\users.py", line 64, in call
result = await future
telethon.errors.rpcerrorlist.AuthKeyUnregisteredError: The key is not registered in the system (caused by GetDialogsRequest)
I searched everywhere for a fix or a tutorial and I didn't find anything. My only other choice was coming here.
Please Help.
Regards, Daniel
Admittedly, the docs aren't very clear about what that error means, but from the looks of it, you might be suffering at the hands of an unmanaged resource. The docs themselves suggest here:
The TelegramClient aggregates several mixin classes to provide all the common functionality in a nice, Pythonic interface. Each mixin has its own methods, which you all can use.
In short, to create a client you must run:
from telethon import TelegramClient
client = TelegramClient(name, api_id, api_hash)
async def main():
# Now you can use all client methods listed below, like for example...
await client.send_message('me', 'Hello to myself!')
with client:
client.loop.run_until_complete(main())
You don’t need to import these AuthMethods, MessageMethods, etc. Together they are the TelegramClient and you can access all of their methods.
See Client Reference for a short summary.
Consider using python's with statement to help manage client.
As an aside, did you know that one of the devs who contributed to Telethon has already written a free and open source scraper?

Telegram client on pythonanywhere using telethon

SORRY FOR MY ENGLISH!))
Trying to launch telegram client on pythonanywhere hosting using flask
Loaded all necessary libraries (see photo1)
On this site created an api-application, got it app_id and api_hash
Further, I made a flask application with this code (for test)
#app.route('/')
def hello_world():
#------------------------If an error occurred during import------------
try:
from telethon import TelegramClient, sync
except Exception as e:
return 'IMPORT ERROR: ' + str(e)
#------------------------we catch it-----------------------------------
api_id = API_ID_FROM_MY_TELEGRAM_ORG #Тут подставляю свое
api_hash = API_HASH_CODE_FROM_MY_TELEGRAM_ORG #Тут подставляю свое
#----------If an error occurred while creating the object--------------
try:
client = TelegramClient('test_session', api_id, api_hash)
return 'Succes!'
except Exception as e:
return 'OBJECT ERROR: ' + str(e)
#------------------------we catch it-----------------------------------
When you start and open the application in the browser, the following error is displayed (in text form):
OBJECT ERROR: database is locked
This text corresponds to the last try/catch construction, so an error occurs when trying to create an object client = TelegramClient('test_session', api_id, api_hash)
What is this exception and how in my case to fight it?

invite user by username to telegram channel

i trying to add users by usernames to my channel. I am using python 3.6 telethon library and pythonanywhere server:
api_hash = 'b7**'
phone = '+7***'
client = TelegramClient('new_ses', api_id, api_hash)
client.connect()
client = TelegramClient('session_neworig', api_id, api_hash,)
client.connect()
from telethon.tl.functions.channels import InviteToChannelRequest
from telethon.tl.functions.contacts import ResolveUsernameRequest
from telethon.tl.types import InputPeerChannel ,InputPeerUser,InputUser
from telethon.tl.functions.channels import JoinChannelRequest
chann=client.get_entity('channelname') #its public channel
print(chann.id)
1161823752
print(chann.access_hash)
8062085565372622341
time.sleep(30)
chan=InputPeerChannel(chann.id, chann.access_hash)
user = client(ResolveUsernameRequest('Chai***'))
print(user.users[0].id)
193568760
print(user.users[0].access_hash)
-4514649540347033311
time.sleep(1*30)
user=InputUser(user.users[0].id,user.users[0].access_hash,)
client.invoke(InviteToChannelRequest(chan,[user]))
This dosent work and i get -telethon.errors.rpc_error_list.PeerFloodError: (PeerFloodError(...), 'Too many requests')
what am i doing wrong? how to avoid it ?
this one code is worked for me , but i am gone to flood after added let's say 20 users :
from telethon.helpers import get_input_peer
client.invoke(InviteToChannelRequest(
get_input_peer(client.get_entity(chan),
[get_input_peer(client.get_entity(user))]
))
Please help , how to add 200 users by username without any ban , maybe there is another way to do it by python ? another lib or by api ?
Found somethin on Telegram API documentation website
Each phone number is limited to only a certain amount of logins per day (e.g. 5, but this is subject to change) after which the API will return a FLOOD error until the next day. This might not be enough for testing the implementation of User Authorization flows in client applications.
Link to source
from telethon.sync import TelegramClient
from telethon.tl.functions.channels import InviteToChannelRequest
from telethon.tl.types import InputPeerChannel ,InputUser
from telethon.tl.functions.contacts import ResolveUsernameRequest
api_id = ******
api_hash = '******'
phone = '+2519******'
client = TelegramClient(phone, api_id, api_hash);
client.connect()
chann=client.get_entity('channelname')
channel_id = chann.id;
channel_access_hash = chann.access_hash
chanal=InputPeerChannel(channel_id, channel_access_hash)
user = client(ResolveUsernameRequest('mrmi6'))
user=InputUser(user.users[0].id,user.users[0].access_hash,)
client(InviteToChannelRequest(chanal,[user]))
print('action completted')

Categories

Resources