首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何检查用户是否订阅了特定的电报频道(Python / PyTelegramBotApi)?

如何检查用户是否订阅了特定的电报频道(Python / PyTelegramBotApi)?
EN

Stack Overflow用户
提问于 2020-10-18 14:31:19
回答 1查看 6.4K关注 0票数 3

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-10-18 14:42:31

使用getChatMember方法检查用户是否是通道中的成员。

getChatMember

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

代码语言:javascript
运行
复制
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()

样本结果:

如果用户是成员,则接收用户信息。

代码语言:javascript
运行
复制
{'user': {'id': 700..., 'is_bot': False, 'first_name': '', 'username': None, 'last_name': None, ... }

或例外情况

代码语言:javascript
运行
复制
telebot.apihelper.ApiTelegramException: A request to the Telegram API was unsuccessful. Error code: 400 Description: Bad Request: user not found

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

代码语言:javascript
运行
复制
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()
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64414486

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档