如何解决如何检查用户是否订阅了特定的电报频道Python / PyTelegramBotApi?
我正在使用 PyTelegramBotApi库编写 Telegram机器人,我希望 实现检查用户对特定电报的订阅的功能频道 ,如果没有,则提供订阅。预先感谢您的回答!
解决方法
使用getChatMember
方法检查用户是否为频道成员。
getChatMember
使用此方法获取有关a的成员的信息 聊天。成功返回一个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()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。