Send message to telegram channel with telethon and get mobile notification - python

I want to use telethon to send messages to my own private channel, and receive mobile push notifications when the python script posts a message. With the below code I'm able to send the messages, but I do not receive any mobile push notifications. I've turned on all notification settings in the mobile app. I have been googling around for 'telethon push notifications', without any luck.
from telethon import TelegramClient
api_id = 'api_id'
api_hash = 'api_hash'
username = 'username'
channel_invite_link = 'channel invite link'
async def func():
entity = await client.get_entity(channel_invite_link)
await client.send_message(entity=entity, message="Hi")
with TelegramClient(username, api_id, api_hash) as client:
client.loop.run_until_complete(func())

Just use the silent argument, i.e.:
await client.send_message(entity=entity, message="Hi", silent=False)

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

Telethon event handler stuck looping

I've been trying to send my client's incoming messages via my bot back to the client. The event handler get stuck in a loop doing so. I'm still new to asynchronous programming and telethon, any feedback or specific reference is highly appreciated. :-)
from telethon import TelegramClient, client, events
api_id = xxx
api_hash = 'xxx'
telegram_bot_token = 'xxx'
telegram_chat_id = 'xxx'
bot = TelegramClient('xxx', api_id, api_hash).start(bot_token='xxx')
client = TelegramClient('xxx', api_id, api_hash)
#client.on(events.NewMessage)
async def messaged_by_bot(event):
await bot.send_message('xxx', event.message.text)
client.start()
client.run_until_disconnected()

Telegram's websocket

I want to connect to the telegram's WebSocket or other protocol, to receive every message. I was inspecting the network tab in dev tools, but I could not find any WebSocket protocol, however, when I entered console, I can see [SW] on message {type: "ping", localNotifications: true, lang: {…}, settings: {…}} Which convince me, that it is sent to maintain connection with the WebSocket. I tried a telethon library for python, but it allows me only to show all messages in the chat.
from telethon import TelegramClient
import asyncio
client = TelegramClient(name, api_id, api_hash)
client.start()
for i in client.iter_dialogs():
if i.name == 'test':
chj = i
async def main():
channel = await client.get_entity(chj)
messages = await client.get_messages(channel, limit= None) #pass your own args
#then if you want to get all the messages text
for x in messages:
print(x) #return message.text
"""for i in client.iter_dialogs():
print(i)"""
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
I want to be getting messages like in WebSocket whenever on the desired chat someone's types something
I have found an answer. This can be achieved using events from telethon library
from telethon import TelegramClient, events
name = 'test'
api_id = 1234
api_hash = 'hash'
client = TelegramClient(name, api_id, api_hash)
#client.on(events.NewMessage())
async def newMessageListener(event):
newMessage = event.message.message
print(newMessage)
with client:
client.run_until_disconnected()

How to send message to Telegram channel in Telethon

Am trying to send a message to a Telegram channel after a new message event is invoked in another. The code i have below utilizes the channel name as the entity but it doesn't work all the time. Any ideas how i would go about it in better and effecient way.
#client.on(events.NewMessage(chats=channel))
async def my_event_handler(event):
values = formatter(event.raw_text)
await client.send_message('destination', template.format(coin=values[0], buy=values[1]))
client.start()
client.run_until_disconnected()
This is the Documentation :
So i've send a message that said "Hello python" with the username "abdx".
client = TelegramClient('session_name',
api_id,
api_hash,
)
client.start()
destination_user_username='abdx'
entity=client.get_entity(destination_user_username)
client.send_message(entity=entity,message="Hello python")
By Alihossein shahabi.

Categories