pythonpython-telegram-botauthor

how to get username of author using telegram bot?


I am making a telegram bot using python-telegram-bot in python where I had two files one is main.py and another responses.py.in responses.py I want to send the name of the user but I am unable to send it due to the main function. It will always run in my code so I can't pass arguments like update on the main function. So I can't be able to use this

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

My main.py code:-

from telegram import *
from telegram.ext import *
from dotenv import load_dotenv
import responses as R
load_dotenv()
def main():
  updater=Updater(os.getenv("BOT_TOKEN"), use_context=True)
  dp=updater.dispatcher    
  dp.add_handler(MessageHandler(Filters.text,handle_message))
  dp.add_error_handler(error)
  updater.start_polling()
  updater.idle()
main()

My responses.py code:-

def sample_responses(message):
  message=message.lower()
  if message in ("hello", "hi"):
    return "Hey! How's it going?"

  elif message in ("who are you", "who are you?"):
    return "Hi! I am Buddy Bot. Developed by Soham."

I want to print the user name on responses.py on typing hello it will reply "Hey! @user How it going?

Please help me to solve this problem.


Solution

  • Add the function to the handler in main.py. You can define the filter there that triggers the function:

    from telegram import *
    from telegram.ext import *
    from dotenv import load_dotenv
    from responses import *
    
    load_dotenv()
    def main():
      updater=Updater(os.getenv("BOT_TOKEN"), use_context=True)
      dp=updater.dispatcher    
      dp.add_handler(MessageHandler(Filters.regex('^(hello|hi)$'), hello))
      dp.add_handler(MessageHandler(Filters.regex('^(who are you)$'), whoareyou))
      dp.add_error_handler(error)
      updater.start_polling()
      updater.idle()
    main()
    

    And define the functions in responses.py:

    def hello(update: Update, context: CallbackContext) -> None:
        try:
          username = update.message.chat.username
        except:
          username = update.message.chat.first_name
        update.message.reply_text(f'Hey! @{username} How it going?')
    
    def whoareyou(update: Update, context: CallbackContext) -> None:
        update.message.reply_text('Hi! I am Buddy Bot. Developed by Soham.')
    

    Note that not all users set a username, so I included a try-except that uses the first name if no username is set.