How to do a telethon login using GUI - python

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.

Related

Telegram Bot not Connecting to API

I have been using the Telegram API for a while to listen for messages in specific channels on one account. The code below works ok. I tried to use the same code to create another listener for a different account but it doesn't work. I don't get any errors.
When I look on the official Telegram app the listener is not listed under "Devices" which suggests it is not connecting to the API correctly.
Before testing I created a new API ID and hash at my.telegram.org. I've triple checked that the ID, hash and channel ID are all correct.
Can anyone think what the issue might be?
Thanks
from telethon import TelegramClient, events, sync
api_id = 'xxxxxxxxxx'
api_hash = 'xxxxxxxxxxxxxxxxxx'
client = TelegramClient('anon', api_id, api_hash)
chat_id = xxxxxxxx
#client.on(events.NewMessage(chats=chat_id))
async def newMessageListener(event):
new_message = event.message.message
chat_id = event.chat_id
print(chat_id)
print(new_message)
print()
screenshot = "new_image.jpg"
if event.message.photo:
await event.download_media(screenshot)
print("New image received")
#client.on(events.NewMessage(chats=[chat_id]))
chats=[] - here must be a python list,
like chats=[-123456789]

Creating or using a telegram bot that forward messages received from a bot to another account

I'm new to telegram bot (especially programming one).
Is there a bot that can forward a message from another bot to a second account?
Where the second account is not the admin of the bot writing.
Alternatevely, is there a way to create one?
I'm pretty skilled in Python but I get a little bit lost on using a Python script to make a bot work.
I'm working on a Windows 11 environment
Install Telethon
python3 -m pip install --upgrade pip
python3 -m pip install --upgrade telethon
Obtain your API_ID and API_TOKEN from Telegram
And then replace your values and run the code:
from telethon import TelegramClient, events
import asyncio
import logging
logging.basicConfig(level=logging.WARNING)
api_id = # don't forget to fill this
api_hash = '' # don't forget to fill this
client = TelegramClient("forwarder", api_id, api_hash)
client.start()
from_chat_id = # don't forget to fill this
to_chat_id = "me"
async def get_chat_id(title):
async for dialog in client.iter_dialogs():
if dialog.title == title:
return dialog.id
#client.on(events.NewMessage)
async def my_event_handler(event):
chat = await event.get_chat()
if chat.id == from_chat_id:
await client.forward_messages(to_chat_id, event.message)
# asyncio.get_event_loop().run_until_complete(get_chat_id("YOUR CHAT TITLE"))
asyncio.get_event_loop().run_forever()
from_chat_id will be the chat id of the bot you want to forward message from.
to_chat_id will be the destination chat id. using 'me' would forward the message to your saved messages.
Another thing to note is this code:
asyncio.get_event_loop().run_until_complete(get_chat_id("YOUR CHAT TITLE"))
if you want to get the id of a chat you can uncomment this line and pass your chat title.

How to have a bot reply to another bot's message with inline keyboard?

I have a scenario where my bot starts a conversation with another bot to receive one reply with inline keyboard. How can my bot reply using the inline keyboard?
from pyrogram import Client
api_id = 12345
api_hash = "hash123"
with Client("my_account", api_id, api_hash) as app:
app.send_message("otherbot", "Hello") # This message is received by otherbot, which then triggers a reply that contains an inline keyboard
# Here I need to reply to otherbot's message
What you're looking for is a Conversation Handler.
A conversation-like feature is not available yet in Pyrogram. One way to do that is saving states into a dictionary using user IDs as keys. Check the dictionary before taking actions so that you know in which step your users are and update it once they successfully go past one action.
https://t.me/pyrogramchat/213488
(copy-pasted from another answer of mine.)
As stated by #ColinShark, pyrogram does not support Conversation Handler. So, this simple workaround worked for my use case:
from pyrogram import Client
api_id = 12345
api_hash = "hash123"
bot_name = "otherbot"
with Client("my_account", api_id, api_hash) as app:
response = app.send_message(bot_name, "Hello")
bot_reply_msg_id = int(response["message_id"]) + 1
response = app.get_messages(bot_name, bot_reply_msg_id)
try:
response.click(2, timeout=1) # to click on the third button/option. Index start at 0.
except TimeoutError:
pass

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