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

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

Related

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.

SlackClient Python RTM not capturing messages

I want to write a simple slack bot, which responds a given string to # mentions, however I am not able to make the official documentation code to work.
I gave all OAuth permission to the bot and have the following code:
from slack import RTMClient
#RTMClient.run_on(event="message")
def gravity_bot(**payload):
data = payload['data']
print(data.get('text'))
try:
rtm_client = RTMClient(
token="my_token_auth_code",
connect_method='rtm.start'
)
print("Bot is up and running!")
rtm_client.start()
except Exception as err:
print(err)
I think the connection is established, as the "Bot is up and running" message appears, however on the slack channel to bot seems to be offline, also I am not able to get any response in the terminal, not for direct messages, not for channel messages even after inviting the bot to given channels.
Sorry couldn't let this one go.. I figured it out and here are the steps:
Create a "Classic" app in Slack (this is the only way to get the appropriate scopes), just click this link: https://api.slack.com/apps?new_classic_app=1
From the "Add features and functionality" tab click on "bots":
Click the "Add Legacy Bot User" button (this will add the "rtm.stream" scope that you need, but that you cannot add manually)
From the basic information page, install your app in a workspace
From the OAuth & Permissions page, copy the "Bot User OAuth Access Token" (the bottom one)
Run the following code (slightly modified version of the code in the docs)
from slack_sdk.rtm import RTMClient
# This event runs when the connection is established and shows some connection info
#RTMClient.run_on(event="open")
def show_start(**payload):
print(payload)
#RTMClient.run_on(event="message")
def say_hello(**payload):
print(payload)
data = payload['data']
web_client = payload['web_client']
if 'Hello' in data['text']:
channel_id = data['channel']
thread_ts = data['ts']
user = data['user']
web_client.chat_postMessage(
channel=channel_id,
text=f"Hi <#{user}>!",
thread_ts=thread_ts
)
if __name__ == "__main__":
slack_token = "<YOUR TOKEN HERE>"
rtm_client = RTMClient(token=slack_token)
rtm_client.start()
Previous answer:
Hmm, this is tricky one... According to the docs this only works for "classic" Slack apps, so that might be the first pointer. It explicitly says that you should not upgrade your app. Furthermore, you'll need to set the right permissions (god knows which ones) by selecting the "bot" scope.
Honestly, I haven't been able to get this running. Looks like Slack is getting rid of this connection method, so you might have more luck looking into the "Events API". I know it's not the ideal solution because its not as real-time, but it looks better documented and it will stay around for a while. Another approach could be polling. Its not sexy but it works...
My guess is that your problem is that there is not a valid connection, but there is no proper error handling in the Slack library. The message is printed before you actually connect, so that doesn't indicate anything.

Telepot - read text of a sent message

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)

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.

Creating Slack Bot to Answer Request

I would like to create a Slack bot to answer some simple question or perform some task on the server. Here is what I have tried
token = "i-put-my-bot-token-here" # found at https://api.slack.com/#auth)
sc = SlackClient(token)
sc.api_call("chat.postMessage", channel="magic", text="Hello World!")
It was posted as the Slackbot and not the bot account that I created?
Also if I were to listen the message, according to the python library it says
if sc.rtm_connect():
while True:
print sc.rtm_read()
time.sleep(1)
else:
print "Connection Failed, invalid token?"
Or should I use incoming webhook instead?
As you can see here this call accepts an argument 'as_user' which can be true. If you set it as true, messages will be posted as the bot you created.
I'm in the middle of creating a bot right now as well. I found that if you specified as_user='true', it would post as you, the authed user. If you want it to be your bot, pass in the name of our bot and other options like emoji's like so:
sc.api_call(
'chat.postMessage',
username='new_slack_bot',
icon_emoji=':ghost:',
as_user='false',
channel='magic',
text='Hello World!'
)
Check emoji cheat sheet for more.
Then, if you want to listen to events, like questions or commands, try intercepting the messages that are sent in. Example found on this post:
while True:
new_evts = sc.rtm_read()
for evt in new_evts:
print(evt)
if "type" in evt:
if evt["type"] == "message" and "text" in evt:
message=evt["text"]
# write operations below to receive commands and respond as you like

Categories