Search code examples
pythontelegramtelegram-botpython-telegram-bot

Telegram Bot Checks Rather Mentions Is User Or Group Chat


I'm trying to code a python anti-advertising telegram bot and basically want to check when a user mentions another user in their message it will check rather the mentioned @ is a user or a group.

I want the members to still be able to mention other usernames like ex: @username, but when they mention a group @testinggroup, it will be flagged and removed, here's all I have right now.

from telegram import *
from telegram.ext import * 
from requests import *
import re

updater = Updater(token="bot_token", use_context=True)
dispatcher = updater.dispatcher

username = re.compile(r'^@[A-Za-z][A-Za-z0-9_]{4,30}$', re.IGNORECASE)

def messageHandler(update: Update, context: CallbackContext):

    #chat_member = context.bot.get_chat_member(update.effective_chat.id, update.message.from_user.id)
    #if chat_member.status == 'creator' or chat_member.status == 'administrator' or chat_member.user.is_bot:
    #    return
 
    if username.search(update.message.text):
        return #NEED HELP HERE

dispatcher.add_handler(MessageHandler(Filters.text, messageHandler))

updater.start_polling()
updater.idle()

I've tried everything, tried removing messages with @ in them, but I want users to still be able to mention each other. tried using regex to detect usernames, but once again want users to be able to mention each other.


Solution

  • Checking if a message contains a mention

    Note that you can use Filters.entity("mention") to filter for messages that contain a mention in the form @username - that way you don't have to rely on regex.

    Moreover, you can retrieve the usernames via update.effective_message.parse_entities(["mention"]). Note that MessageEntity.user is not available for entities of type "mention".

    Checking if a username links to a private chat or something else

    As implied by Lorenzo, you can use get_chat for this. Note that get_chat should return the Chat object in case the username links to a public group or channel. However, for private chats, get_chat only works with the user id and not the username, so get_chat("@privateusername") will raise a "Chat not found" exception rather than returning a Chat object.


    Note: The links point to the PTB v13.15 docs. The current stable version is v20.0, which contains significant breaking changes compared to v13.x.


    Disclaimer: I'm currently the maintainer of python-telegram-bot.