Bor*_*dan 5 python bots telegram telegram-bot py-telegram-bot-api
我正在使用PyTelegramBotApi 库编写一个Telegram 机器人,我想实现检查用户对某个电报频道的订阅的功能,如果没有,则提供订阅。预先感谢您的回答!
使用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()
Run Code Online (Sandbox Code Playgroud)
结果示例:
如果用户是会员,您会收到用户信息
{'user': {'id': 700..., 'is_bot': False, 'first_name': '', 'username': None, 'last_name': None, ... }
Run Code Online (Sandbox Code Playgroud)
或其他情况下的异常
telebot.apihelper.ApiTelegramException: A request to the Telegram API was unsuccessful. Error code: 400 Description: Bad Request: user not found
Run Code Online (Sandbox Code Playgroud)
有关如何在项目中使用它的示例
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()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11975 次 |
| 最近记录: |