If I have a bot in a group, and I want to make the bot respond only if it was mentioned in the message, is there any way to achieve this?
Telegram Bot check whether the bot is mentioned in Group
Asked Answered
Check if @yourbot is in any message and if yes then reply. –
Midrib
When a message contains a mention by username then the Message object contains a MessageEntity with MessageEntity.type
equals to 'mention'
(since bots always have username).
You can check MessageEntity.offset
to get the position of the entity in the text of the message, then parse the text of the message to check if the username mentioned is you bot's username.
Consider that by default bots run in privacy mode
A bot running in privacy mode will not receive all messages that people send to the group. Instead, it will only receive:
- Messages that start with a slash ‘/’
- Replies to the bot's own messages
- Service messages (people added or removed from the group, etc.)
- Messages from channels where it's a member
Just expanding the answer given by @marcopiii - check code may look, for example, this way:
context.bot.name in [update.message.text[mention.offset:mention.offset + mention.length] for mention in
update.message.entities if mention['type'] == 'mention']
where update
and context
are default message handler arguments
© 2022 - 2024 — McMap. All rights reserved.