Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To Obtain Username, First Name Or Last Name Of A Telegram User With Python-Telegram-Bot?

I'm Creating A Telegram Bot Using Python-Telegram-Bot

I Know That update.message.chat_id Returns The User's Chat ID, But I Need To Know How To Get User's Username Or First Name And/Or Last Name.

I've Found This On Telegram's Documentation But I Don't Know How To Use It ( I Tried bot.getChat(update.message.chat_id) But No Result)

like image 717
Sadegh Alirezaie Avatar asked Dec 06 '16 02:12

Sadegh Alirezaie


2 Answers

All infomation about user (as username, id, first/last name and profile photos) available from telegram.User object. You can easily get it using telegram.Message

user = update.message.from_user
print('You talk with user {} and his user ID: {} '.format(user['username'], user['id']))
like image 184
Dudnikof Avatar answered Sep 30 '22 02:09

Dudnikof


You can use the json file and access information such as username, ID, etc. You can print this file yourself for information about the json file. See the example below.

# 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()
like image 24
saeed sahoor Avatar answered Sep 30 '22 01:09

saeed sahoor