【问题标题】:How to check if a user is subscribed to a specific Telegram channel (Python / PyTelegramBotApi)?如何检查用户是否订阅了特定的电报频道(Python / PyTelegramBotApi)?
【发布时间】:2021-02-01 11:18:06
【问题描述】:

我正在使用PyTelegramBotApi库编写一个Telegram bot,我想实现检查用户订阅某个电报的功能频道,如果没有,请提供订阅。提前感谢您的回答!

【问题讨论】:

    标签: python bots telegram telegram-bot py-telegram-bot-api


    【解决方案1】:

    使用getChatMember 方法检查用户是否为频道成员。

    getChatMember

    使用此方法获取有关成员的信息 聊天。成功时返回 ChatMember 对象。

    import telebot
    
    bot = telebot.TeleBot("TOKEN")
    
    CHAT_ID = -1001...
    USER_ID = 700...
    
    result = bot.get_chat_member(CHAT_ID, USER_ID)
    print(result)
    
    bot.polling()
    

    示例结果:

    如果用户是会员,您会收到用户信息

    {'user': {'id': 700..., 'is_bot': False, 'first_name': '', 'username': None, 'last_name': None, ... }
    

    否则为异常

    telebot.apihelper.ApiTelegramException: A request to the Telegram API was unsuccessful. Error code: 400 Description: Bad Request: user not found
    

    如何在项目中使用它的示例

    import telebot
    from telebot.apihelper import ApiTelegramException
    
    bot = telebot.TeleBot("BOT_TOKEN")
    
    CHAT_ID = -1001...
    USER_ID = 700...
    
    def is_subscribed(chat_id, user_id):
        try:
            bot.get_chat_member(chat_id, user_id)
            return True
        except ApiTelegramException as e:
            if e.result_json['description'] == 'Bad Request: user not found':
                return False
    
    if not is_subscribed(CHAT_ID, USER_ID):
        # user is not subscribed. send message to the user
        bot.send_message(CHAT_ID, 'Please subscribe to the channel')
    else:
        # user is subscribed. continue with the rest of the logic
        # ...
    
    bot.polling()
    

    【讨论】:

    • 但是如何更容易解析 接收到的数据,并制定一个条件,如果一个人是sub,bot将继续工作,或者如果未签名, 请求订阅?
    • @BortsovBogdan 我添加了一些示例,说明如何将其用作 if-else 逻辑并发送消息
    猜你喜欢
    • 2016-09-16
    • 1970-01-01
    • 2013-09-29
    • 1970-01-01
    • 2019-02-27
    • 2014-05-15
    • 2020-04-21
    • 2019-01-18
    • 2020-11-26
    相关资源
    最近更新 更多