记录一个TG机器人获取用户ID脚本
1、安装依赖库
# 安装 python-telegram-bot 库
pip install python-telegram-bot
# 如果上面命令不行,尝试:
pip3 install python-telegram-bot
# 或者使用清华源加速安装
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple python-telegram-bot
2、python获取ID的脚本
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import Application, CommandHandler, ContextTypes, CallbackQueryHandler
import logging
logging.basicConfig(level=logging.INFO)
TOKEN = '机器人TOKEN'
async def myid(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""处理 /myid 命令"""
user = update.effective_user
chat_id = update.effective_chat.id
keyboard = [
[InlineKeyboardButton("👤 显示用户ID", callback_data="show_user_id")],
[InlineKeyboardButton("💬 显示聊天ID", callback_data="show_chat_id")],
[InlineKeyboardButton("🔄 重新显示", callback_data="show_all")]
]
reply_markup = InlineKeyboardMarkup(keyboard)
await update.message.reply_text(
f'👋 Hello {user.first_name}!\n\n'
f'🆔 <b>Your User ID:</b> <code>{user.id}</code>\n'
f'💬 <b>Chat ID:</b> <code>{chat_id}</code>\n\n'
'💡 <i>点击上方代码区域即可复制</i>\n'
'或使用下方按钮快速查看:',
reply_markup=reply_markup,
parse_mode='HTML'
)
async def button_handler(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""处理按钮点击"""
query = update.callback_query
user = query.from_user
chat_id = query.message.chat_id
if query.data == "show_user_id":
await query.edit_message_text(
f"👤 <b>你的用户ID:</b>\n"
f"<code>{user.id}</code>\n\n"
"💡 点击上面的代码即可复制",
parse_mode='HTML'
)
elif query.data == "show_chat_id":
await query.edit_message_text(
f"💬 <b>当前聊天ID:</b>\n"
f"<code>{chat_id}</code>\n\n"
"💡 点击上面的代码即可复制",
parse_mode='HTML'
)
elif query.data == "show_all":
keyboard = [
[InlineKeyboardButton("👤 显示用户ID", callback_data="show_user_id")],
[InlineKeyboardButton("💬 显示聊天ID", callback_data="show_chat_id")],
[InlineKeyboardButton("🔄 重新显示", callback_data="show_all")]
]
reply_markup = InlineKeyboardMarkup(keyboard)
await query.edit_message_text(
f'👋 Hello {user.first_name}!\n\n'
f'🆔 <b>Your User ID:</b> <code>{user.id}</code>\n'
f'💬 <b>Chat ID:</b> <code>{chat_id}</code>\n\n'
'💡 <i>点击上方代码区域即可复制</i>\n'
'或使用下方按钮快速查看:',
reply_markup=reply_markup,
parse_mode='HTML'
)
await query.answer()
def main():
application = Application.builder().token(TOKEN).build()
application.add_handler(CommandHandler("myid", myid))
application.add_handler(CallbackQueryHandler(button_handler))
print("Bot is running...")
application.run_polling()
if __name__ == '__main__':
main()
3、python bot.py运行脚本
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END











暂无评论内容