python - 如何检查用户是否订阅了特定的 Telegram channel (Python/PyTelegramBotApi)?

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

我正在使用PyTelegramBotApi 库 编写一个Telegram bot,我希望实现检查用户订阅某个 Telegram 的功能channel,如果没有,则提供订阅。预先感谢您的回答!

最佳答案

使用getChatMember检查用户是否是 channel 成员的方法。

getChatMember

Use this method to get information about a member of a chat. Returns a ChatMember object on success.

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()

示例结果:

如果用户是成员(member),您会收到用户信息

{'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()

关于python - 如何检查用户是否订阅了特定的 Telegram channel (Python/PyTelegramBotApi)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64414486/

相关文章:

python - pandas 过滤/组合相似的字符串值

bots - 如何从reaction_ added 事件中获取线程回复的内容?

node.js - 通过node.js控制和获取应用程序客户端的数据

php - 如何通过单击 Telegram 内联键盘将一些数据插入数据库?

python - 如何在 telebot(pytelegramBotAPI)中获取 chat_id 和 message_id 以更新 Telegram bot(Python)中最后发送的消息

geolocation - Telegram 地理定位

python - 使用欧拉法求解 4D 耦合系统

python - 在 Python 中,如何将列表列表中的字符串转换为其他类型,例如整数、 float 、 bool 值等?

python - 强制 timeit 自动选择语句执行的次数

bots - 如何结束机器人对话并让真人处理 Dialogflow 中的响应?