Login telethon automatically - python

I am creating a app for create a telethon session with python.
[part one]-i want to first get the phone number form user with POST method in django and create a primary key for this order and create key.session and wait for code.
[part two]-then get the code and key with POST method in django and log in to key.session .
async def main():
client = TelegramClient('enter the key', api_id, api_hash)
assert await client.connect()
if not client.is_user_authorized():
await client.send_code_request(phone_number)
me = await client.sign_in(phone_number, input('Enter code: '))

Related

Send message from bot to self with telethon

I'm trying to send a message to myself using a Telegram bot I have created, and I got the values from https://my.telegram.org as well as the BotFather.
import telebot
from telethon.sync import TelegramClient
def telegram_setup():
api_id = 12345678
api_hash = 'X'
token = 'X'
phone = '+111'
client = TelegramClient('session', 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: '))
return client
def send_message(client, message):
try:
entity = client.get_entity('username')
client.send_message(entity, message, parse_mode='html')
except Exception as e:
print(e)
client.disconnect()
if __name__ == "__main__":
client = telegram_setup()
message = "test"
send_message(client, message)
The first time I ran this, it sent me a message asking for a code which I supplied. Running it again caused "test" to appear under "Saved Messages" in Telegram, rather than coming from my bot.
Any idea what's causing this or how to resolve it?
Thanks.
EDIT: I realised I'm not using token anywhere, but I'm not sure where it goes.
The bot token is required in client.start() as bot_token (bot_token="token"), if what you do is a bot, your phone is not needed.
Edit: You made a userbot, not a bot.

How to do a telethon login using GUI

I'm new to telethon, and I'm trying to make a GUI for my application using python.
The problem is when I run this code:
from telethon import TelegramClient
id = ******
hash = *******
client = TelegramClient("test",id,hash)
client.start()
it automatically runs a terminal login, so I can't actually use that in a GUI.
I also saw :
client.start(phone=your_phone_callback,password=your_password_callback,code_callback=your_code_callback)
I don't really understand how to get the confirmation code at the first place.
How to do a telethon login using GUI?
Don't use client.start()
use
client = TelegramClient(f"session", api_id, api_hash)
await client.connect()
#phone = <User phone number>
# This will send the code to the user. You have to get it using the front end
phone_code = await client.send_code_request(phone)
phone_code_hash = phone_code.phone_code_hash
#code = <Code from the user>
await client.sign_in(phone, code=code, phone_code_hash=phone_code_hash)
this will log you in without using the terminal.

Get telegram subscriber username via telegram admin bot

I have my own telegram channel and a telegram bot which is also a channel administrator.
How can I get the username of all my subscribers using python(telebot)?
And is it possible to find out by which link the subscriber subscribed to the channel using python(telebot)?
I did not find how to do it with a telebot, but with a pyrogram
from pyrogram import Client
TARGET = -100....
api_id = 91...
api_hash = "2f01....."
link = 'https://t.me/+PP.........'
app = Client("my_account", api_id, api_hash)
async def main():
async with app:
async for event in app.get_chat_invite_link_joiners(chat_id=TARGET, invite_link=link):

How to get the Chat or Group name of Incoming Telegram message using Telethon?

I have this code
from telethon.sync import TelegramClient, events
with TelegramClient('name', api_id, api_hash) as client:
#client.on(events.NewMessage(pattern=pattern))
async def handler(event):
await event.reply("Here should be the Chat or Group name")
How to implement this?
if we are talking only about groups/channels
chat_from = event.chat if event.chat else (await event.get_chat()) # telegram MAY not send the chat enity
chat_title = chat_from.title
Else (If we want to get the full name of chat entities, including Users):
from telethon import utils
chat_from = event.chat if event.chat else (await event.get_chat()) # telegram MAY not send the chat enity
chat_title = utils.get_display_name(chat_from)
get_display_name() actually gets a name that you would see. Works for types User, Channel, Chat
That method shall not have await

Telegram get chat messages /posts - python Telethon

I am using Telethon and Python 3.6xx
Been able to retreive message from groups, no problem but when it comes to channels I am stuck.
dialogs = client(get_dialogs)
for chat in dialogs.chats:
getmessage = client.get_messages(chat.id, limit=400)
for message in getmessage:
print(message.message)
I've searched the telethon documentation but most answers were in response to the old get_message_history.
When I'm trying with the following chat.id = 1097988869 (news.bitcoin.com) I'm getting an error below (for groups the chat.id works fine):
PeerIdInvalidError: An invalid Peer was used. Make sure to pass the right peer type
The accepted answer is good, but recent versions of Telethon let you achieve the same more easily. This will iterate over all messages in chat (for this example we use telethon.sync to avoid typing out async):
from telethon.sync import TelegramClient
with TelegramClient(name, api_id, api_hash) as client:
for message in client.iter_messages(chat):
print(message.sender_id, ':', message.text)
Where the variables should be obvious, for example (note these API values won't work, you need your own):
name = 'anon'
api_id = 123
api_hash = 'abcdefgh'
chat = 'me'
More examples using async are available in client.iter_messages documentation.
update :
in the new version of Telethon, #Lonami answer is best and use it.
############################################################
you can use this code for get messages :
client = TelegramClient('session_name',
api_id,
api_hash,
update_workers=1,
spawn_read_thread=False)
assert client.connect()
if not client.is_user_authorized():
client.send_code_request(phone_number)
me = client.sign_in(phone_number, input('Enter code: '))
channel_username='tehrandb' # your channel
channel_entity=client.get_entity(channel_username)
posts = client(GetHistoryRequest(
peer=channel_entity,
limit=100,
offset_date=None,
offset_id=0,
max_id=0,
min_id=0,
add_offset=0,
hash=0))
# messages stored in `posts.messages`
that work for me!
api_hash from https://my.telegram.org, under API Development.
from telethon import TelegramClient, events, sync
api_id = 'your api_id'
api_hash = 'your api_hash'
client = TelegramClient('session_name', api_id, api_hash)
client.start()
channel_username = 'username'# your channel
for message in client.get_messages(channel_username, limit=10):
print(message.message)

Categories

Resources