Telethon: check if client instance is logged in - python

I am trying to log the user into the account using the telegram bot API, and I can't find a way to check if the client instance has access to an account...
this is my instance:
client = TelegramClient(client_name, API_ID, API_HASH)
by using client.start() it detects if the user is logged in or not, so i must have access to that too...

You need to use get_me(): it will return the current logged in user or None if there isn't one.
client = TelegramClient(client_name, API_ID, API_HASH)
if (await client.get_me()):
# client has an user logged in
else:
# client hasn't an user logged in
Also, if you take a look at the source code, you'll see that start() is doing the same.

Related

Telethon authorization Python

I have the following problem: I am trying to authorize a telegram client using a session created by telethon. When you run the code in the console, as befits, the phone number associated with the account is requested, followed by the confirmation code received from Telegram. And after entering the confirmation code, nothing happens, although a message about successful authorization should appear. After a few minutes of waiting for the program to work, a message about Incomplete login attempt arrives in the Telegram. Can you tell me what's the matter?
This is my code for making session:
from telethon import TelegramClient, events
api_id = MY_API_ID
api_hash = "MY_API_HASH"
client = TelegramClient('first_session', api_id, api_hash)
#client.on(events.NewMessage(outgoing=True, pattern=None))
async def greeting(event):
chat = await event.get_chat()
await client.send_message(chat, "Hello, World!")
client.start()
client.run_until_disconnected()
And results of launching the program in the terminal in the attached image
Launching in console
Perhaps the problem may be that you are not waiting for the confirmation code request to appear and complete before running the rest of the code. To solve this problem, you need to wrap the run_until_disconnected method in an asynchronous context and use the await keyword to wait for the confirmation code to be requested.
Try the code:
from telethon import TelegramClient, events
api_id = MY_API_ID
api_hash = "MY_API_HASH"
client = TelegramClient('first_session', api_id, api_hash)
#client.on(events.NewMessage(outgoing=True, pattern=None))
async def greeting(event):
chat = await event.get_chat()
await client.send_message(chat, "Hello, World!")
async def main():
await client.start()
await client.run_until_disconnected()
asyncio.run(main())
The question is removed. For full authorization via telethon , you need to enter the method .start() pass the password="12345" parameter, where 12345 is the two-factor authentication password.

How to get telegram chat invite link using telethon?

I'm trying to get the invite link of a public channel and a public group.
I tried using the ExportChatInviteRequest function but it raises a ChatAdminRequiredError.
The thing I don't understand is why can I see and get the invite link of a public channel \ group with the telegram app but can't get it with telethon?
I use version 1.26.1:
from telethon.tl.functions.messages import ExportChatInviteRequest
async def main():
chat = await client.get_entity('https://t.me/bestmemes')
invite = await client(ExportChatInviteRequest(chat))
print(invite)
raises:
telethon.errors.rpcerrorlist.ChatAdminRequiredError: Chat admin privileges are required to do that in the specified chat (for example, to send a message in a channel which is not yours), or invalid permissions used for the channel or group (caused by ExportChatInviteRequest)
can someone help me, please?
I can see the invite of the given channel via the telegram app:
I did this:
Create a private chat with a bot or a friend
Retrieve api_id and api_hash from https://my.telegram.org/auth
Login to your telegram account using your phone number
Click "API Development tools"
Fill in your application details
Click on "Create application" at the end
Copy App api_id and App api_hash
from telethon import TelegramClient
from telethon.tl.functions.messages import ExportChatInviteRequest
session = 'Test' # The first-part name of a sqlite3 database - "Test.session"
# Contains user name and password to your Telegram account
# App ID and hash key to identify your Telegram App
api_id = 12345 # Use your own api_id
api_hash = '1234567890ABCDEFGHIJKLMNOPQRSTUV' # Use your own api_hash
# Create a connection to your telegram account using this app
# You will be asksed phone number, password, which will be stored into
# "Test.session" sqlite3 database
client = TelegramClient(session, api_id, api_hash)
async def main():
# Send a hello message to yourself
await client.send_message('me', 'Hello!')
# Send a hello message to a private chat group
await client.send_message('https://t.me/+xxxxxx', 'Hello!')
# Get a specific chat via its primary link
group = await client.get_entity('https://t.me/+xxxxxx')
# Create additional link
invite = await client(ExportChatInviteRequest(group))
print(invite.link) # Print secondary link
with client:
client.loop.run_until_complete(main())
The ExportChatInviteRequest method you are trying to use creates a private chat link. Obviously you can't do this if you're not an administrator
Here is a small code example that gets links to all open chats
async def get_chat_links():
dump = {}
# get all dialogs
for dialog in await client.get_dialogs():
chat = dialog.entity
# if the dialog does not have a title attribute, then it is not a group
if hasattr(chat, 'username') and hasattr(chat, 'title'):
dump[chat.title] = f'https://t.me/{chat.username}'
# for example, let's save everything to a file
with open('dump.json', 'w', encoding='utf-8') as file:
json.dump(dump, file, indent=4)
with client:
client.loop.run_until_complete(get_chat_links())
I would like to add some explanation about hasattr(chat, 'username'). For some chats you will have https://t.me/None. These are just the same closed chats that do not have an open link to join. But the ExportChatInviteRequest function will not work for these chats either, because it CREATES a link, and does not receive it. And if you are not an administrator in this chat you will get an error

Telegram get message by channel ID

I am subscribed to a private telegram Channel/chat where I am not admin and the username is not public.
I can get the channel id from the url in the form https://web.telegram.org/#/im?p=c1234567890_12345678901234567890
And can read all the messages in my telegram and via my web browser.
The channel outputs data (messages) that I want to grab and format and ultimately automatically append to a csv file or such like via a bot or an app on my mac.
Is it possible to do this?
I am currently trying to do this in Python using the Telethon package.
I have been trying to access or address the channel by ID but get errors like
No user has "c1234567890" as username
Or
No user has "-1001234567890" as username
I am trying to use the telethon client.getmessages() method but looks like it will only accept a username and not a chat or channel ID.
Any help/guidance or pointing in the right direction appreciated - I think my main issue is resolving the channel ID to a username or finding classes/methods where I can get the messages by channel ID.
yes, you can used channel ID for search. use it as a int not as a String
this code will help you to understand.
from telethon import TelegramClient
# Remember to use your own values from my.telegram.org!
api_id = 12345
api_hash = '0123456789abcdef0123456789abcdef'
client = TelegramClient('anon', api_id, api_hash)
async def main():
# You can print the message history of any chat:
# chat id is -1001209767229
async for message in client.iter_messages(-1001209767229):
print(message.sender.username, message.text)
with client:
client.loop.run_until_complete(main())

How to send message to my channel using telethon

I'm trying to make my python script send messages to my private channel but I get this error.
telethon.errors.rpcerrorlist.ChatWriteForbiddenError: You can't write in this chat (caused by SendMessageRequest)
I'm only admin in that channel and here is code what I use for sending messages, when I try to send message to myself it works fine..
from telethon import TelegramClient
from telethon.errors import SessionPasswordNeededError
api_id = 'my api id'
api_hash = 'my api hash'
phone = 'my number'
username = 'my username'
# Create the client and connect
client = TelegramClient(username, api_id, api_hash)
client.start()
print("Client Created")
# Ensure you're authorized
if not client.is_user_authorized():
client.send_code_request(phone)
try:
client.sign_in(phone, input('Enter the code: '))
except SessionPasswordNeededError:
client.sign_in(password=input('Password: '))
async def send_mess(message):
await client.send_message(entity='my channel name', message=message)
while True:
some other code
if last_message != new_message:
with client:
client.loop.run_until_complete(send_mess(message=new_message))
last_message = new_message
Do I need to change something to have admin rights on my script or where is the problem? I'll be glad for every answer. Gimme some good sample code guys :D this is really big problem for me now.
At first test that you can send message to another channel or user. if you can't you must share all the code.
then make sure that account you are using at this case is admin in the channel. it's impossible you getting this error if the account is admin.
also check admin rights and make sure post message is enable.
between, use channel username or channel numeric id instead 'my channel name'. channel numeric id starts with -100 like -1001212229355. you better to use numeric id. to find this just forward one of your channel messages to https://t.me/userinfobot.
await client.send_message(entity='my channel name', message=message)

Discord Bot Leave Server

my_server = client.get_server('server id')
#client.event
async def on_ready():
for server in client.servers:
if server != my_server:
await client.leave_server(server)
#client.event
async def on_server_join(server):
if server != my_server:
await client.leave_server(server)
Finally its working if I add Server ID in ('server id') my bot leaves that server. But for some servers I don't have access so can't get the server ID.
So how do I make my bot leave that server?
client.leave_server(server) takes a Server object.
client.servers returns a list of servers that the client is connected to. So your code should do what you expect.
When your bot is kicked or banned from the server, it should no longer be connected. Is this not the case?
If you're defining a method where the bot automatically leaves the server if it's anything other than your server, then is the actual problem that someone has access to your bot and is using it on their server without your permission? In that case you will need to revoke access to the bot by generating a new token, and/or changing the password to the dev console.

Categories