Telegram get message by channel ID - python

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())

Related

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

Error when sending a message to telegram chat using Python Telethon

from telethon import TelegramClient
client = TelegramClient('anon', api_id, api_hash)
async def main():
await client.send_message(chat_id, 'Hello')
with client:
client.loop.run_until_complete(main())
When I try to run the code I get an error:
telethon.errors.rpcerrorlist.ChatIdInvalidError: Invalid object ID for
a chat. Make sure to pass the right types, for instance making sure
that the request is designed for chats (not channels/megagroups) or
otherwise look for a different one more suited\nAn example working
with a megagroup and AddChatUserRequest, it will fail because
megagroups are channels. Use InviteToChannelRequest instead (caused by
SendMessageRequest)
Chat's ID is correct, I checked. What could be the problem?
yes you have to confirm from your chat id and make sure you passed the correct id of your chat. you can use "#_Chat_ID" or use "htttp//t.me/Chat_link"

Send message to telegram channel with telethon and get mobile notification

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)

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)

How to get a message from Telegram groups by API?

I was looking for some way to listen and catch new messages provided by telegram groups.
I have not found libraries or API in order to do this in Python.
Someone having any suggestion?
Using Telethon
Replace channel_name with your telegram channel.
from telethon import TelegramClient, events, sync
# Remember to use your own values from my.telegram.org!
api_id = ...
api_hash = '...'
client = TelegramClient('anon', api_id, api_hash)
#client.on(events.NewMessage(chats='channel_name'))
async def my_event_handler(event):
print(event.raw_text)
client.start()
client.run_until_disconnected()
There are two ways to achieve your goal:
Method 1:
My suggested library for python: python-telegram-bot
Create a bot.
Add the bot to the desired group as administrator.
Listen to messages as you normally listen in bots.
Method 2:
My suggested library for python: Telethon
Join the desired group as a user (not a bot).
Create a simple client that listens to new messages.

Categories