Reputation: 21
I have to join chats via links, which are in a file.Only 30 links were correct but if i try to join myself it will be succeed.
Last time i tried to use a link in join_chat method:
async def main():
await app.start()
me = await app.get_me()
spic = [el.strip() for el in open('links.txt')]
for el in spic:
try:
chat = await app.get_chat(el)
if me.id not in chat.members:
await app.join_chat(el.rstrip())
await app.archive_chats(chat.id)
else:
print("Already in the group:", chat.title)
except:
print('Chat is not found')
await asyncio.sleep(1,5)
I also tried to indicate an username received from the link:
async def main():
await app.start()
spic = [el for el in open('links.txt')]
for el in spic:
try:
username = el.split("/")[-1]
await app.join_chat(str(username))
chat = await app.get_chat(username)
edit_text_file(str(chat.id))
await app.archive_chats(chat.id)
except:
print('Chat is not found')
await asyncio.sleep(1.5)
If i remove except handler i will get this error: "pyrogram.errors.exceptions.bad_request_400.UsernameInvalid: Telegram says: [400 USERNAME_INVALID] - The username is invalid (caused by "contacts.ResolveUsername")" Can you help me? Thank you
Upvotes: 1
Views: 364
Reputation: 1352
The error you’re getting for your second snippet indicates that the join_chat()
call succeeds, but the get_chat()
call fails. It fails because el.split("/")
is not necessarily a valid argument to get_chat()
.
Also, according to the documentation for get_chat()
, it only accepts invite links of groups that you have previously joined.
If you want to simply join a chat and then archive it, then you can just use the ID of the Chat
type returned from the join_chat()
call.
Also, note that [el for el in open("links.txt")]
could contain empty items and hence make failing calls to the Telegram API.
Here’s an improved version of your code that should work:
from pyrogram.errors import FloodWait, RPCError
async def main():
await app.start()
spic = [el.strip() for el in open("links.txt")]
chat_ids = []
for el in spic:
if not el: # Skip empty lines.
continue
try:
if len(chat_ids) == 20: # Archive 20 chats at once to make less calls.
await app.archive_chats(chat_id)
chat_ids = []
except RPCError as e:
print("Failed to archive chats:", e)
try:
chat = await app.join_chat(el)
except FloodWait as e:
await asyncio.sleep(e.value)
except RPCError as e:
print("Failed to join chat:", e)
edit_text_file(str(chat.id))
chat_ids.append(chat.id)
await asyncio.sleep(1.5)
if len(chat_ids) > 0:
await app.archive_chats(chat_ids)
Upvotes: 1