skip to Main Content

I’m programming a Telegram bot in python using the library python-telegram-bot, but I have a problem: I need to get the username of the user (sorry for the pun), but I don’t know how to do it in the main function. I have already searched on the internet, and everyone get the username in a function, using update.message.from_user.username. But I need to do it in the main function, because I want to send this username and some text to another Telegram user. Can you help me?

My current code is this:

import telegram
import logging
from telegram.ext import CommandHandler, CallbackQueryHandler, Updater
from functions import start, button

bot = telegram.Bot(token='')
updater = Updater(token='')
dispatcher = updater.dispatcher
logging.basicConfig(format='%(asctime)s - %(name)s'
                    ' - %(levelname)s - %(message)s', level=logging.INFO)
start_handler = CommandHandler('start', start)
dispatcher.add_handler(start_handler)
updater.dispatcher.add_handler(CallbackQueryHandler(button))
updater.start_polling()
updater.idle()
updater.stop()

2

Answers


  1. See if this is what you’re looking for:

    def start (update, context):
    
        #this will retrieve the user's username, as you already know
        user = update.message.from_user
    
        #this will send the information to some Telegram user
        context.bot.send_message(chat_id = some_user_chat_id,
                                 text = f'User {user} just hit start command!')
    

    Once the user hit /start command, his/her username will be sent to the chat_id of your choice.

    Login or Signup to reply.
  2. You can set middleware which handle new update from user and get username throw ctx.from.username

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search