Receiving service messages in a group chat using Telegram Bot - python

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.

Related

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

How can a telegram bot receive photo which are attached to commands in telegram group chats without privacy mode?

I want to make a telegram bot, that receives commands to which photos are attached. It should also work in groups. And if possible it would work with privacy-mode enabled. If possible it should work as a single message (e.g. not a separate message for the command and for the photo)
For example, when I send a photo to the bot with the command /my_command my_string_parameter, it would look like this:
Here is an example code, except that in this example the method is only called, when the command is used WITHOUT a photo attached. How would I have to modify this example so it the method my_command is also called when a photo is sent?
from telegram import Update
from telegram.ext import CallbackContext, CommandHandler, Updater
def my_command(update: Update, _: CallbackContext) -> None:
# This is only called, when /my_command is used WITHOUT a photo attached
update.message.reply_text("photo received?")
updater = Updater(secret.telegram_token)
dispatcher = updater.dispatcher
dispatcher.add_handler(CommandHandler("my_command", my_command))
updater.start_polling()
updater.idle()
Note: I am not restricted to the module python-telegram-bot, but I am restricted to python3.
You can use MessageHandler with caption filter, which will contains your command, instead of CommandHandler.
Example:
from telegram.ext.filters import Filters
dispatcher.add_handler(MessageHandler(Filters.caption(update=['my_command']), my_command))

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)

Python Telegram Bot. Get message to which given message replies

I want to develop a Telegram bot, that acts as a bookmarking system. It should process commands that reply to other messages. The instance:
I use python-telegram-bot for development and it seems that there is no way to see that message to which /important replies. I found the Update.message.reply_to_message object, which works only when a user replies to a message from the bot itself.
def important_handler(update: Update, context: CallbackContext):
reply_to_message = update.message.reply_to_message
if reply_to_message is None:
logger.error('reply_to_message is None. But it shouldn\'t.')
update.message.reply_text('There is no message attached. Try again.')
return
# ... business logic
Is there any way to get reply_to_message attribute (or an alternative) for all the replies? Thanks in advice;)
I had the same problem. It only worked when a user replied to the bot. My issue was that the bot had Privacy Mode enabled. Once I disabled it with Botfather via /setprivacy and then it worked.

How to use python-slackclient RTM using multiple token (bot-user)

Hi I have an issue integrating slack custom bot-user into my slack app, based on python-slackclient documentation python-slackclient
to use the RTM
import time
from slackclient import SlackClient
token = "xoxp-xxxxxxxxx"# found at https://api.slack.com/web#authentication
sc = SlackClient(token)
if sc.rtm_connect():
while True:
print sc.rtm_read()
time.sleep(1)
else:
print "Connection Failed, invalid token?"
that code is working for bot-user token, but since I use oauth, I need to connect RTM using the bot_access_token everytime user install my app to act on behalf my app to the added team
any solution or example how to do it?
Cheers,
Your question is had to understand. You wrote:
since I use oauth, I need to connect RTM using the bot_access_token everytime user install my app to act on behalf my app to the added team
The access token you're using here...
token = "xoxp-xxxxxxxxx"# found at https://api.slack.com/web#authentication
...should be the same as the access token that is associated with your bot. (You should not make your bot use your own personal access token!) You can get an access token for your bot at https://my.slack.com/services/new/bot (assuming you're logged into Slack in the browser with which you follow that link).
If you participate in multiple Slack "teams" (a Slack "team" being basically a company), you'll need to set up a separate bot for each "team". Each bot will have a different access token. To pass the correct access token in to your bot, you could add a command-line parameter, or read the token from an environment variable, or read it from disk, among other options.
You can loop over tokens for connecting if you are planning to setup bot
for multiple teams, then your code can be converted to :-
clients = [SlackClient(token) for t in tokens]
for client in clients:
client.rtm_connect()
while True:
for client in clients:
print client.rtm_read()
time.sleep(1)

Categories