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.
Related
I need a way to constantly check for the message 'kill' in discord.py. I have many while loops in my code so I need to create a new thread with the threading module. How can I send a message to a channel with that thread without the events.
You can use asyncio.get_event_loop().create_task(channel.send("example message")). Use it like this:
import asyncio
client = discord.Client()
def funct():
channel = client.get_channel(channel_id)
asyncio.get_event_loop().create_task(channel.send("example message"))
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"
I have set up a script to download messages from thousands of Telegram supergroups (named chatlist). This works fine when I use a few groups, however, allowing 1000< groups seems to break it and no messages are collected at all. Is this the correct way to approach it, or is there a more efficient way? I don't think it's a network issue my end as I have GB internet
from telethon import TelegramClient, events, sync
client = TelegramClient('test', api_id, api_hash)
#client.on(events.NewMessage(chats=chatlist))
async def my_event_handler(event):
message = event.message.to_dict()
print(message['message'])
await client.start()
await client.run_until_disconnected()
A simple workaround is to remove the NewMessage event filter i.e.:
#client.on(events.NewMessage())
and filter messages inside the method yourself:
async def my_event_handler(event):
message = event.message.to_dict()
input_chat = await event.get_input_chat()
if input_chat in chatlist:
print(message['message'])
You didn't mention what's inside chatlist, so I assumed it's a list of InputChat objects.
Note that if your chat list is a list of #username strings, you'll soon reach Telegram username resolve limits. Always have InputChat or long ids in the chatlist.
So I'm able to send all the chats of specified group to another group with the help of telethon's telegramclient and events below is my code.
from telethon import TelegramClient, events
api_id = YOUR_ID
api_hash = YOUR_HASH
client = TelegramClient('anon', api_id, api_hash)
#client.on(events.NewMessage(chats=CHAT_ID_A))
async def handle_new_message(event):
await client.send_message(CHAT_ID_B, event.raw_text)
Help me to refactor this code in such a way that I can send messages of only selected users from telegram group A to telegram group B
After a bit of searching adding the following inside event definition will to the trick
sender_chat_id = event.sender_id
if sender_chat_id == SELECTED_ID:
await client.send_message(CHAT_ID_B, event.raw_text)
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())