Can't get NewMessage event on SuperGroup (SelfBot) - python

I'm trying to listen to supergroup new messages, but I can't seem to be able to:
from telethon.sync import TelegramClient
from telethon import events, utils
from telethon.tl.types import InputMessagesFilterPhotos
api_id = 98.....
api_hash = 'acbc55199.....'
num = '+921.......'
client = TelegramClient(num, api_id, api_hash)
client.connect()
if not client.is_user_authorized():
client.send_code_request(num)
client.sign_in(num, input('Code: '))
#client.on(events.NewMessage(chats=[-123456789]))
async def handler(event):
print(event.from_id.user_id)
It works on group I created and channels/groups I'm a member in, but it doesn't for supergroups.
Any idea if I'm doing anything wrong?

Related

Telethon New Message Event Handler waits minute

Telethon event handler waits 1 minute before sending out a burst of messages at the same time.
I tried removing functions from other souces as I thought that could be it and it did not work.
code:
`
from telethon import TelegramClient, events
import logging
import time
#from main import add
logging.basicConfig(format='[%(levelname) 5s/%(asctime)s] %(name)s: %(message)s', level=logging.WARNING)
api_id =
api_hash =
client = TelegramClient('anon', api_id, api_hash)
#client.on(events.NewMessage)
async def my_event_handler(event):
print(event.raw_text)
#add(event.raw_text)
client.start()
client.run_until_disconnected()
`
form me work ok and i have testet
python need to run all time
#exit()
import sys
from telethon import TelegramClient, events
import logging
import time
import telethon.tl.functions as _fn
logging.basicConfig(format='[%(levelname) 5s/%(asctime)s] %(name)s: %(message)s', level=logging.WARNING)
api_id = row[2]
api_hash = row[3]
client = TelegramClient(path+str(api_id), api_id, api_hash)
#client.on(events.NewMessage)
async def my_event_handler(event):
print(event.raw_text)
print(event)
#add(event.raw_text)
client.start()
client.run_until_disconnected()
print('Finish...')

How to edit client massage in Telegram using python?

I need to edit last message sent with python. How can I do it?
from telethon import TelegramClient, events, sync
from telethon.tl.functions.messages import EditMessageRequest
# Remember to use your own values from my.telegram.org!
api_id = api_id
api_hash = api_hash
client = TelegramClient('anon', api_id, api_hash)
#client.on(events.NewMessage(chats='j'))
async def my_event_handler(event):
print(event.raw_text)
await client.send_message(event.chat_id,'dd')
event.edit_massge("")
client.start()
client.run_until_disconnected()
When I send a message I want the script to edit it to the text that I will enter.
from telethon import TelegramClient, events, sync
from telethon.tl.functions.messages import EditMessageRequest
# Remember to use your own values from my.telegram.org!
api_id = api_id
api_hash = api_hash
client = TelegramClient('anon', api_id, api_hash)
#client.on(events.NewMessage(chats='j'))
async def my_event_handler(event):
print(event.raw_text)
message = await client.send_message(event.chat_id, "hello") # changed line
await client.edit_message(event.chat_id, message, "hello!") # changed line
client.start()
client.run_until_disconnected()
In addition, you can only edit your own messages (just in case you want to edit a message from someone else)

How to connect to Telegram using telethon without entering your phone (or bot token)?

I have written the following script that listens for new messages on telegram public channels. Problem is that every time the script is used on a new machine telegram is sending a code to the phone number linked to the dev account. You have to enter this code to authorize the new machine. Is there a way to avoid this?
import configparser
from telethon.errors import SessionPasswordNeededError
from telethon import TelegramClient, events, sync
from telethon.tl.functions.messages import (GetHistoryRequest)
from telethon.tl.types import (
PeerChannel
)
api_id = 'xxxxxx'
api_hash = 'xxxxxxxxxxxxxxxxxxxxxxx'
# Here you define the target channel that you want to listen to:
input_channels = ('https://t.me/xxxxxx','https://t.me/xxxx','https://t.me/xxxxxxx')
print(input_channels)
#create a client
client = TelegramClient('anon', api_id, api_hash)
# Listen to messages from target channel
#client.on(events.NewMessage(chats=input_channels))
async def newMessageListener(event):
# Get message text
newMessage = event.message.message
print(newMessage)
with client:
client.run_until_disconnected()

Telethon changes the name to the current time

I want my application to change my name in the telegram to the current time every minute. I have already tried to do something, but to no avail
from telethon import TelegramClient
from telethon.tl.functions.account import UpdateProfileRequest
import asyncio
import datetime
today = datetime.datetime.today()
time= today.strftime("%H.%M")
api_id = 123456
api_hash = 'ххх'
client = TelegramClient('session_name', api_id, api_hash)
client.start()
async def main():
while True:
await client(UpdateProfileRequest(first_name=time))
await asyncio.sleep(1)
client.loop.run_forever()
from telethon import TelegramClient
from telethon.tl.functions.account import UpdateProfileRequest
import asyncio
import datetime
api_id = 123456
api_hash = 'ххх'
client = TelegramClient('session_name', api_id, api_hash)
client.start()
async def main():
while True:
time = datetime.datetime.today().strftime("%H.%M")
async with client:
await client(UpdateProfileRequest(first_name=time))
await asyncio.sleep(60)
asyncio.get_event_loop().run_until_complete(main())
first stuff don't use while loop , it may use too memory and disable handle updates from telethon
second stuff 1 second its too fast and telegram may ban you account for spam
I prefer to use aiocron
Install aiocron using the following command
pip3 install aiocron
Code:
import asyncio, aiocron, datetime
from telethon import TelegramClient, events, sync, functions, types
from telethon.tl.functions.account import UpdateProfileRequest
api_id = 123456
api_hash = "ххх"
client = TelegramClient("session_name", api_id, api_hash)
client.start()
#aiocron.crontab("*/1 * * * *")
async def set_clock():
time = datetime.datetime.today().strftime("%H.%M")
async with client:
await client(UpdateProfileRequest(first_name=time))
#client.on(events.NewMessage)
async def e(event):
if event.raw_text == "ping":
await event.reply("pong")
client.run_until_disconnected()

Want to extract pinned messages from the groups/channels on Telegram i am part of using Telethon

I'm using Telethon API
Want to extract pinned messages of all the channels i am member.
Please guide me with the procedure.
Thank you.
As of Telethon 1.2, the code is a lot simpler:
from telethon import TelegramClient, types, sync
with TelegramClient('name', api_id, api_hash) as client:
message = client.get_messages('TelethonChat', ids=types.InputMessagePinned())
This won't work for private chats, however (e.g. to fetch the pinned message with yourself). For that, as the currently accepted answer hints, we have to fetch the Full object. For the case of the private chat, this is UserFull by using GetFullUserRequest:
chat = 'me'
full = client(functions.users.GetFullUserRequest(chat))
message = client.get_messages(chat, ids=full.pinned_msg_id)
You can use GetFullChannelRequest and GetHistoryRequest methods to extract pinned message from one channel
from telethon import TelegramClient
from telethon.tl.functions.channels import GetFullChannelRequest
from telethon.tl.functions.messages import GetHistoryRequest
from telethon.tl.types import PeerChannel
api_id = XXXXX
api_hash = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
phone_number = '+98XXXXXXXX'
################################################
client = TelegramClient('session_name',
api_id,
api_hash
)
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_entity = client.get_entity(PeerChannel(channel_id))
channel_info = client(GetFullChannelRequest(channel_entity))
pinned_msg_id = channel_info.full_chat.pinned_msg_id
if pinned_msg_id is not None:
posts = client(GetHistoryRequest(
channel_entity,
limit=1,
offset_date=None,
offset_id=pinned_msg_id + 1,
max_id=0,
min_id=0,
add_offset=0,
hash=0
))
print(posts.messages[0].to_dict())
I used Telethon V0.19, but the previous versions are pretty much the same
To get all pinned messages from channel using Telethon 1.19.5 (sync version) and above you can
from telethon.tl.types import InputMessagesFilterPinned
from telethon import TelegramClient, sync # noqa: F401
channel_id = -1009999999999
with TelegramClient("name", api_id, api_hash) as client:
# we need to set limit
# because otherwise it will return only first pinned message
pinned_messages = client.get_messages(
channel_id,
filter=InputMessagesFilterPinned,
limit=1000,
)
for message in pinned_messages:
print(message.message)

Categories

Resources