Problems with Python Telegram Bot Chat.ban_member ()

Ferran Casals

I'm using the Python TelegramBot https://python-telegram-bot.readthedocs.io/en/stable/telegram.chat.html and I'm trying to build my first bot in Telegram.

I followed the example of https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples/chatmemberbot.py as a template

If the user isn't on the list, I'd like to add the ability for the bot to kick the user out, but I'm having trouble implementing this feature. My code is below.

#!/usr/bin/env python
# pylint: disable=C0116,W0613
# This program is dedicated to the public domain under the CC0 license.

"""
Simple Bot to handle '(my_)chat_member' updates.
Greets new users & keeps track of which chats the bot is in.
Usage:
Press Ctrl-C on the command line or send a signal to the process to stop the
bot.
"""

import logging
from typing import Tuple, Optional

from telegram import Update, Chat, ChatMember, ParseMode, ChatMemberUpdated
from telegram.ext import (
    Updater,
    CommandHandler,
    CallbackContext,
    ChatMemberHandler,
)

# Enable logging
logging.basicConfig(
    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
)

logger = logging.getLogger(__name__)

def checkUsers(update: Update, context: CallbackContext, chat: Chat) -> None:
    """Greets new users in chats and announces when someone leaves"""

    cause_name = update.chat_member.from_user.mention_html()
    member_name = update.chat_member.new_chat_member.user.mention_html()
    
    member = update.chat_member.new_chat_member.user.username
    userId = update.chat_member.new_chat_member.user.id
    print(userId)
    
    approvedMembers = ["Jack", "shaamsCat"]
    
    if member in approvedMembers :
        update.effective_chat.send_message(
            f"{member_name} was added by {cause_name}. Welcome!",
            parse_mode=ParseMode.HTML,
        )
    elif member not in approvedMembers : 
        update.effective_chat.send_message(
            f"{member_name} is not on the list!",
            parse_mode=ParseMode.HTML,
        ),
                
    chat.ban_member(userId)
       

def main() -> None:
    """Start the bot."""
    # Create the Updater and pass it your bot's token.
    updater = Updater("TOKEN")

    # Get the dispatcher to register handlers
    dispatcher = updater.dispatcher

    # Handle members joining/leaving chats.
    dispatcher.add_handler(ChatMemberHandler(checkUsers, ChatMemberHandler.CHAT_MEMBER))

    # Start the Bot
    # We pass 'allowed_updates' handle *all* updates including `chat_member` updates
    # To reset this, simply pass `allowed_updates=[]`
    updater.start_polling(allowed_updates=Update.ALL_TYPES)

    # Run the bot until you press Ctrl-C or the process receives SIGINT,
    # SIGTERM or SIGABRT. This should be used most of the time, since
    # start_polling() is non-blocking and will stop the bot gracefully.
    updater.idle()


if __name__ == "__main__":
    main()

In that case, you will get the following error:

TypeError: checkUsers() missing 1 required positional argument: 'chat'

If you change the function checkUsers () function to look like this:

def checkUsers(update: Update, context: CallbackContext) -> None:
"""Greets new users in chats and announces when someone leaves"""

cause_name = update.chat_member.from_user.mention_html()
member_name = update.chat_member.new_chat_member.user.mention_html()

member = update.chat_member.new_chat_member.user.username
userId = update.chat_member.new_chat_member.user.id
print(userId)

approvedMembers = ["Jack", "shaamsCat"]

if member in approvedMembers :
    update.effective_chat.send_message(
        f"{member_name} was added by {cause_name}. Welcome!",
        parse_mode=ParseMode.HTML,
    )
elif member not in approvedMembers : 
    update.effective_chat.send_message(
        f"{member_name} is not on the list!",
        parse_mode=ParseMode.HTML,
    ),
            
Chat.ban_member(userId)
   

Then the error is:

TypeError: ban_member() missing 1 required positional argument: 'user_id'

Also, if you don't pass any arguments to Chat.ban_member (), the missing arguments will be:

TypeError: ban_member() missing 2 required positional arguments: 'self' and 'user_id'

I would appreciate your help. I'm sure it will be the basic knowledge I'm missing. To be honest, I just started using Python a few days ago, so thank you.

thank you!

CallMeStag

The handler callback requires exactly two positional arguments. This python-telegram-botis the design method. Therefore, the first approach does not work.

Moreover, Chat.ban_memberthis is a restricted method, not a class / static method. Neither works because Chatis a class and not an instance of that class . You need an instance of the class to call that method . Probably in your case or (the latter is a shortcut for the former).Chat.ban_member(user_id)Chatupdate.chat_member.chatupdate.effective_chat


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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324233204&siteId=291194637