【问题标题】:how to get username of author using telegram bot?如何使用电报机器人获取作者的用户名?
【发布时间】:2021-08-08 06:09:16
【问题描述】:

我正在 python 中使用python-telegram-bot 制作一个电报机器人,其中我有两个文件一个是main.py,另一个是responses.py.in responses.py 我想发送用户的姓名,但我无法发送这是由于main 功能。它将始终在我的代码中运行,因此我无法在 main 函数上传递 update 之类的参数。所以我不能用这个

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

我的 main.py 代码:-

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

我的responses.py代码:-

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."

我想在responses.py上打印用户名,输入hello它会回复“嘿!@user 怎么样?

请帮我解决这个问题。

【问题讨论】:

    标签: python python-telegram-bot author


    【解决方案1】:

    将函数添加到main.py 中的处理程序。您可以在那里定义触发功能的过滤器:

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

    并在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.')
    

    请注意,并非所有用户都设置了用户名,因此我包含了一个 try-except,如果未设置用户名,则使用名字。

    【讨论】:

      猜你喜欢
      • 2022-06-10
      • 2016-08-20
      • 2018-01-12
      • 1970-01-01
      • 2023-01-20
      • 2022-06-10
      • 2018-06-04
      • 2021-10-22
      • 2017-09-24
      相关资源
      最近更新 更多