python-botogram/botogram

Get User's username in a chat with Telegram Bot

abhi3700 opened this issue · 4 comments

I am using this in a callback

import botogram

@bot.command("sendinfo")
def sendinfo_command(chat, message, args):
    """User has to click a button for giving information - Username, Datetime, Location"""
    btns = botogram.Buttons()
    btns[0].callback("Username", "username")     # button - Username
    btns[1].callback("Location", "location")     # button - Location
    chat.send("Please, select one of the buttons popping below.", attach= btns)

@bot.callback("username")
def username_callback(query, chat, message):
    user = botogram.User()
    chat.send(user.username)    # test 
    query.notify("<username> saved.")

if __name__ == "__main__":
    bot.run()

When I am pressing username button, then there is no message (i.e. username) sent from Bot in the chat.

telegram

Hi @abhi3700, thanks for your issue!
In username_callback, you don't need to initialize a new botogram.User(), you need the user that sent the query. You can access its botogram.User instance in query.sender; so, the code will be:

@bot.callback("username")
def username_callback(query, chat, message):
    user = query.sender
    chat.send(user.username)
    query.notify("{username} saved.".format(username=user.username)

Thanks @MarcoBuster. I can't thank you enough for your reply.
It worked.

what if user have not username? (:

what if user have not username? (:

We can have user.id field. It's mandatory in telegram.
I would recommend using this repo instead, as there is no activity since 2020.