python - 在电报机器人库中获取用户 ID
问题描述
我想获取用户 ID 以向用户发送图像。我找到了一个似乎可以做到这一点的代码。
user = Message.from_user
print('You talk with user {} and his user ID: {} '.format(user['username'], user['id']))
我只想获取用户ID。我的代码如下所示。
import logging
import telegram
from telegram import chat
from telegram import message
from telegram.utils.helpers import *
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
from telegram import Bot, message, Chat
from telegram import message, Message
import time
# Enable logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
logger = logging.getLogger(__name__)
# Define a few command handlers. These usually take the two arguments update and
# context. Error handlers also receive the raised TelegramError object in error.
def start(update, context):
"""Send a message when the command /start is issued."""
for i in range(10):
update.message.reply_text('Hi!')
time.sleep(0.5)
# Bot.send_document(chat_id="1853314468:AAHWcod_1sETfH_VM_YQBT2gDa4gif-OoYA", document=open('tests/test.png', 'rb'))
def help(update, context):
"""Send a message when the command /help is issued."""
update.message.reply_text('Help!')
def echo(update, context):
"""Echo the user message."""
update.message.reply_text(update.message.text)
def error(update, context):
"""Log Errors caused by Updates."""
logger.warning('Update "%s" caused error "%s"', update, context.error)
def image(update, context):
"""Send a message when the command /help is issued."""
user = Message.from_user
print('You talk with user {} and his user ID: {} '.format(user['username'], user['id']))
def main():
"""Start the bot."""
# Create the Updater and pass it your bot's token.
# Make sure to set use_context=True to use the new context based callbacks
# Post version 12 this will no longer be necessary
updater = Updater(token="1234567890:ABCDEFGHIJKLMNOPQRSTUVWXYZ", use_context=True)
# Get the dispatcher to register handlers
dp = updater.dispatcher
# on different commands - answer in Telegram
dp.add_handler(CommandHandler("start", start))
dp.add_handler(CommandHandler("help", help))
dp.add_handler(CommandHandler("image", image))
# on noncommand i.e message - echo the message on Telegram
dp.add_handler(MessageHandler(Filters.text, echo))
# log all errors
dp.add_error_handler(error)
# Start the Bot
updater.start_polling()
# Run the bot until you press Ctrl-C or the process receives SIGINT,
# SIGTERM or SIGABRT. This should be used most of the time, since
# start_polling() is non-blocking and will stop the bot gracefully.
updater.idle()
if __name__ == '__main__':
main()
当我运行此代码时,我得到:2021-07-11 22:15:09,993 - main - WARNING - Update "{'update_id': 430649322, 'message': {'delete_chat_photo': False, 'text': '/image ', 'entities': [{'type': 'bot_command', 'offset': 0, 'length': 6}], 'photo': [], 'message_id': 205, 'supergroup_chat_created': False, '聊天':{'用户名':'MYUSR','id':MYID,'first_name':'MYFN','last_name':'MYLN','type':'private'},'new_chat_photo':[], '日期':1626025509,'channel_chat_created':假,'caption_entities':[],'group_chat_created':假,'new_chat_members':[],'来自':{'is_bot':假,'first_name': 'A.', 'username': 'MYUSR', 'last_name': 'MYLN', 'id': MYID, 'language_code': 'en'}}}”导致错误“'member_descriptor'对象是不可下标"
我不知道为什么我会收到这个错误。我正在用 VsCode 和 Python 3.9.1 64Bit 编写我的代码。感谢您的帮助。