我想用 Python 制作一个 Telegram 机器人,并且希望它能够不断读取来自不同私人聊天的消息。我想找到一种方法让机器人接收我在给定聊天中收到的所有消息。我的困难是将消息从私人聊天重定向到与机器人的聊天。有可能做到吗?如果可以的话,该怎么办呢?
我尝试用谷歌搜索这个主题,但没有找到任何令人满意的答案。
检查这个包裹: https://python-telegram-bot.org/ 您只需向您的机器人实例添加一个消息处理程序即可。
您必须与 telegram BotFather 交谈才能获得令牌。然后,您必须在代码中创建机器人实例并订阅新消息
from telegram.ext import Update, MessageHandler, Filters
# Define a function to handle the messages that the bot receives
def message_handler(update, context):
# Get the message from the update
message = update.message
# Print the message to the console
print(message.text)
# Create the Updater and pass it the bot's token
updater = Updater("TOKEN", use_context=True)
# Get the dispatcher to register handlers
dp = updater.dispatcher
# Add a message handler that will be called for any message
dp.add_handler(MessageHandler(Filters.text, message_handler))
# 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()