簡體   English   中英

如何在 python Telegram 機器人的主要 function 中獲取 Telegram 用戶的用戶名?

[英]How do I get the username of a Telegram user in the main function of a python Telegram bot?

我正在使用庫python-telegram-bot bot 在 python 中編寫一個 Telegram 機器人程序,但我遇到了一個問題:我需要獲取用戶的用戶名(抱歉是雙關語),但我不知道該怎么做在主要的 function 中。我已經在 inte.net 上搜索過,每個人都使用update.message.from_user.username在 function 中獲取用戶名。 但我需要在主 function 中執行此操作,因為我想將此用戶名和一些文本發送給另一個 Telegram 用戶。 你能幫助我嗎?

我當前的代碼是這樣的:

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

看看這是不是你要找的:

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

一旦用戶點擊/start命令,他/她的用戶名將被發送到您選擇的chat_id

您可以設置處理來自用戶的新更新的中間件並獲取用戶名 throw ctx.from.username

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM