我正在使用 Python-Telegram-Bot
创建一个 Telegram 机器人我知道
update.message.chat_id
返回用户的聊天ID,但我需要知道如何获取用户的用户名或名字和/或姓氏。
我在 Telegram 的文档中找到了 This 但我不知道如何使用它(我尝试过
bot.getChat(update.message.chat_id)
但没有结果)
有关用户的所有信息(如用户名、ID、名字/姓氏和个人资料照片)可从 telegram.User 对象获得。您可以使用 telegram.Message
轻松获取它user = update.message.from_user
print('You talk with user {} and his user ID: {} '.format(user['username'], user['id']))
您可以使用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()
在终端或 cmd 上输入 ==> python --version 检查你的 python 版本 如果您使用 Pycharm 作为 IDE,请执行以下操作:
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()
update.effective_user.id
这在任何情况下都对我有用,无论是来自内联的回调还是简单的 MessageHandler,用户 id 都是相同的。