Telegram Bot check whether the bot is mentioned in Group
Asked Answered
J

2

6

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?

Jew answered 10/12, 2018 at 10:29 Comment(1)
Check if @yourbot is in any message and if yes then reply.Midrib
Q
6

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
Quarters answered 25/4, 2019 at 17:19 Comment(0)
H
1

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

Hoopes answered 17/11, 2023 at 17:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.