如何使用 Python-Telegram-Bot 获取 Telegram 用户的用户名、名字或姓氏?

问题描述 投票:0回答:4

我正在使用 Python-Telegram-Bot

创建一个 Telegram 机器人

我知道

update.message.chat_id
返回用户的聊天ID,但我需要知道如何获取用户的用户名或名字和/或姓氏。

我在 Telegram 的文档中找到了 This 但我不知道如何使用它(我尝试过

bot.getChat(update.message.chat_id)
但没有结果)

python telegram telegram-bot python-telegram-bot
4个回答
30
投票

有关用户的所有信息(如用户名、ID、名字/姓氏和个人资料照片)可从 telegram.User 对象获得。您可以使用 telegram.Message

轻松获取它
user = update.message.from_user
print('You talk with user {} and his user ID: {} '.format(user['username'], user['id']))

11
投票

您可以使用json文件并访问用户名、ID等信息。您可以自己打印此文件以获取有关json文件的信息。请参阅下面的示例。

# pip install python-telegram-bot==12.0.0
from telegram.ext import Updater
from telegram.ext import CommandHandler
updater = Updater('token')

def start(bot, update):
    # print('json file update : ' ,update)
    # print("json file bot : ', bot)
    chat_id = update.message.chat_id
    first_name = update.message.chat.first_name
    last_name = update.message.chat.last_name
    username = update.message.chat.username
    print("chat_id : {} and firstname : {} lastname : {}  username {}". format(chat_id, first_name, last_name , username))
    bot.sendMessage(chat_id, 'text')

start_command = CommandHandler('start',start)
updater.dispatcher.add_handler(start_command)
updater.start_polling()
updater.idle()

1
投票

在终端或 cmd 上输入 ==> python --version 检查你的 python 版本 如果您使用 Pycharm 作为 IDE,请执行以下操作:

  1. 在终端上使用此命令安装 Telegram API ==>pip3 install pyTelegramBotAPI
  2. 之后,您可以导入远程机器人
  3. 然后在终端上运行以下命令
  4. 通过终端安装pip install telegram
  5. 通过终端安装
  6. pip install python-telegram-bot 现在从 telegram.ext import * 导入 *
  7. 然后使用下面的代码从聊天中获取用户信息:

import telebot from telegram.ext import * from creds import API_KEY shopflipper = telebot.TeleBot(API_KEY, parse_mode=None) @shopflipper.message_handler(commands=["help", "hello"]) def send_help_message(msg): #print(msg) --> this prints out all the information related to the chat print(msg.from_user.username) username = str(msg.from_user.username) #print(username) shopflipper.reply_to(msg, "Hello") shopflipper.polling()



0
投票
update.effective_user.id

这在任何情况下都对我有用,无论是来自内联的回调还是简单的 MessageHandler,用户 id 都是相同的。

© www.soinside.com 2019 - 2024. All rights reserved.