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

12

我正在使用Python-Telegram-Bot创建一个Telegram机器人。

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

我在Telegram的文档中找到了这个,但我不知道如何使用它(我尝试过bot.getChat(update.message.chat_id)但没有结果)。

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']))

我想添加一件事。有时,如果机器人流程允许用户通过按下一些InlineButtons来导航,用户可能不会发送消息。因此,为了了解用户信息,也可以使用update.callback_query.from_user方法。根据交互的性质,可能需要不同的方法。 - Mesut Yılmaz

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版本 ==> python --version 如果您使用Pycharm作为IDE,则执行以下操作:

  1. 在终端上使用此命令安装Telegram API ==>pip3 install pyTelegramBotAPI
  2. 然后,您可以导入telebot
  3. 接下来,在终端上运行以下命令
  4. 通过终端安装pip install telegram
  5. 通过终端安装pip install python-telegram-bot
  6. 现在从telegram.ext中导入*

然后使用以下代码获取聊天中的用户信息:

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是相同的。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接