Telepot - read text of a sent message - python

I use telepot python library with my bot, in python 3.5. I want to read the text of a message that is already in a chat, knowing the id of the telegram chat and the id of the message. How can I do?

The telepot library is a wrapper around the Telegram Bot HTTP API and unfortunately the API doesn't have such method available at the moment. (see here for full list of all available methods). Additionally, telepot is no longer actively maintained.
Nonetheless, you can directly make requests to the telegram servers (skipping the intermediary HTTP API) by using mtproto protocol based libraries (such as Telethon, Pyrogram, MadelineProto, etc..) instead.
Here is an example using Telethon to give you an idea:
from telethon import TelegramClient
API_ID = ...
API_HASH = ' ... '
BOT_TOKEN = ' ... '
client = TelegramClient('bot_session', API_ID, API_HASH).start(bot_token = BOT_TOKEN)
async def main():
message = await client.get_messages(
-10000000000, # channel ID
ids=3 # message ID
)
print("MESSAGE:\n---\n")
print(message.text)
client.start()
client.loop.run_until_complete(main())
[user#pc ~]$ python main.py
MESSAGE:
---
test message
You can get values for API_ID and API_HASH by creating an application over my.telegram.org (see this page for more detailed instruction)

Related

Requests doesn't work when sending message to discord

I am trying to send a message with python to discord using requests.. Why doesn't this work? Did I do something wrong?
import requests
id = 935325134879850517
r = requests.post(f'http://discord.com/api/v9/channels/{id}/messages', json={'content':'message'}, headers={'authorization': 'token'})
Consider using Discord webhooks, I had problem with API too, but webhooks works very simple -- without auth.

Error messages clogging Telethon resulting in security error: Server sent a very new message xxxxx was ignored

I am really at a loss here, recently migrated to new machine and telethon has just broken down it seems. I've checked with others, so its probably just me, but I can't figure out how to solve this problem as it appears to be server side/telethon, but as it seems to be on my end it doesn't seem so obvious.
Whenever launching telethon from an existing session I receive two error messages:
Server sent a very new message with ID xxxxxxxxxxxxxxxxxxx, ignoring
Server sent a very new message with ID xxxxxxxxxxxxxxxxxxx, ignoring
And thereafter it gets clogged with the follow error messages, preventing any execution:
[WARNING/2022-09-07] telethon.network.mtprotosender: Security error while unpacking a received message: Too many messages had to be ignored consecutively
I've attached some standard code which reproduce this error for me. Could someone please give me a heads-up on whats causing this? And what to do about it? Running 3.10 Python and latest Telethon from pip.
from telethon import TelegramClient, events
from telethon.sessions import StringSession
api_id = 1xxxxxxxxxx
api_hash = '2xxxxxxxxxxxxx'
ph = '+1xxxxxxxxxxxxxxxx'
key = 'xxxxxx...'
#client = TelegramClient('session', api_id, api_hash).start(phone = ph)
client = TelegramClient(StringSession(key), api_id, api_hash).start(phone = ph)
channelId = 'xxxxxxx'
#client.on(events.NewMessage(chats = [channelId]))
async def main(event):
try:
me = client.get_me()
print(me.stringify())
print(event.stringify())
except Exception as e:
print(e)
client.run_until_disconnected()
I had the same problem in version 1.25.2. Solution, in Windows time settings, enable automatic setting of time and time zone
Each time you run the script, a new .session file is created in the current directory. Deleting these files allows you to reuse the same session name. This should fix the issue.

Python Telegram Chat Bot

I got a problem in writing code for my telegram customer service chat. Apparently, let me confess my little knowledge in the field. Can I get open source code for telegram chatbot which automatically forwards the messages sent to it to a specific id (my-id)? Thank you...I'm badly in need of this.
Install pytelegrambotapi (pip install pytelegrambotapi) and then you'll be able to use somthing like that:
import telebot
token = "hd9ouhs98h928w982982"
your_id = "321321321321"
bot = telebot.TeleBot(token)
#bot.message_handler(content_types=["text"])
def repeat_all_messages(message):
bot.send_message(your_id, message.text)
if __name__ == '__main__':
bot.infinity_polling()

Is it possible to check if a session has been created?

I was trying to check if a new session has been created using the telethon library.
My first idea was to get the warning message from Telegram (New access: [...]), so when I get that kind of message, I know that another device has connected to my account.
I couldn't get that message, so I tried to get it another way:
chat = client.get_entity(777000) # Telegram chat id
print(chat)
for message in client.iter_messages(chat):
print(message.text)
(This is not the full code.)
The only message I was able to retrieve was the confirmation code, but only with that I can't do anything.
Another idea was to continuously receive the list of active sessions (using GetAuthorizationsRequest()) and, if that list changed, it means that a new device has connected to my account. But is it convenient to continuously send requests to Telegram servers?
I searched everywhere but couldn't find a good solution to my problem.
Any help is appreciated.
With the help of Lonami, I was able to solve my problem.
With client.iter_messages(chat), I could only view messages, while the "message" I was looking for was an UpdateServiceNotification, so I used events.Raw to get all types of updates.
Here is the code:
from telethon.sync import TelegramClient, events
from telethon.tl.types import UpdateServiceNotification
api_id = 123456
api_hash = "42132142c132145ej"
with TelegramClient('anon', api_id, api_hash) as client:
#client.on(events.Raw(func = lambda e: type(e) == UpdateServiceNotification))
async def handler(event):
print("New Login!")
client.run_until_disconnected()

Receiving service messages in a group chat using Telegram Bot

I am trying to create a bot in my group to help me track the group users who have invited other users into the group.
I have disabled the privacy mode so the bot can receive all messages in a group chat. However, it seems to be that update.message only gets messages supplied by other users but not service messages like Alice has added Bob into the group
Is there any way that I can get these service messages as well?
Thanks for helping!
I suppose you are using python-telegram-bot library.
You can add a handler with a specific filter to listen to service messages:
from telegram.ext import MessageHandler, Filters
def callback_func(bot, update):
# here you receive a list of new members (User Objects) in a single service message
new_members = update.message.new_chat_members
# do your stuff here:
for member in new_members:
print(member.username)
def main():
...
dispatcher.add_handler(MessageHandler(Filters.status_update.new_chat_members, callback_func)
There are several more service message types your bot may receive using the Filters module, check them out here.

Categories