Python Telegram Bot Chat.ban_member() 问题

Python Telegram Bot Chat.ban_member() issues

我正在使用 Python Telegram Bot https://python-telegram-bot.readthedocs.io/en/stable/telegram.chat.html 并尝试在 Telegram 上构建我的第一个机器人。

我已经按照示例 https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples/chatmemberbot.py 作为模板

我想添加一个功能,如果用户不在列表中,机器人应该把他踢出去,但我在实现这个功能时遇到了一些问题。我的代码如下:

#!/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()

在那种情况下我收到以下错误:

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

如果我将函数 checkUsers() 函数更改为如下所示:

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)
   

那么错误就是:

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

如果我没有向 Chat.ban_member() 传递任何参数,那么缺少的参数如下所示:

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

我会很感激任何帮助,我相信这将是我所缺少的任何基础知识,我会诚实地告诉你我几天前才开始使用 Python,所以请保持友善!!

谢谢!

处理程序回调必须恰好有两个位置参数 - 这就是 python-telegram-bot 的设计方式。这就是为什么您的第一种方法不起作用的原因。

此外,Chat.ban_member是一个有界方法,而不是class/static方法。 Chat 是一个 class,不是那个 class 的一个实例,所以 Chat.ban_member(user_id) 也不能工作。您需要 Chat class 的一个实例来调用该方法。在你的情况下可能 update.chat_member.chatupdate.effective_chat (后者是前者的快捷方式)。


免责声明:我目前是 python-telegram-bot.

的维护者