让 Telegram 机器人回复由命令回复的消息
Posted
技术标签:
【中文标题】让 Telegram 机器人回复由命令回复的消息【英文标题】:Get Telegram bot to reply to message that was replied by a command 【发布时间】:2021-08-16 18:43:48 【问题描述】:我想创建一个机器人来回复使用命令回复的消息。例如: - 答:你好世界! B:(回复A)/command 机器人:(回复 A)你好 A!
如何获取 B 回复的消息的消息 ID?那里有源代码吗?
【问题讨论】:
【参考方案1】:阅读事件驱动编程。
查看此聊天机器人示例:
from datetime import datetime
import time
class EventDrivenChatBot:
def __init__(self):
# accepted_messages maps incoming messages to
# list of callback functions
self.accepted_messages =
# time of instantiation
self.birth_time = datetime.now()
# "registering" all callbacks
self.register_callback("hi",
self.respond_to_greeting)
self.register_callback("bye",
self.respond_to_departure)
self.register_callback("age?",
self.respond_to_age_request)
self.register_callback("age?",
self.respond_to_age_request_detailed)
def register_callback(self, message, callback):
"""
Registers a callback to a message.
"""
if message not in self.accepted_messages:
self.accepted_messages[message] = []
self.accepted_messages[message].append(callback)
def respond_to_greeting(self):
print("Hello!")
def respond_to_departure(self):
print("Nice chatting with you!")
def respond_to_age_request(self):
age = datetime.now() - self.birth_time
print("I am", age.seconds, "seconds old.")
def respond_to_age_request_detailed(self):
age = datetime.now() - self.birth_time
micros = age.microseconds
print("Technically, I'm", age.seconds, "seconds and",
micros, "microseconds old")
def handle_message(self, message):
if message not in self.accepted_messages:
print("sorry, I don't understand", message)
else:
callbacks = self.accepted_messages[message]
for callback in callbacks:
callback()
bot = EventDrivenChatBot()
bot.handle_message("hi")
time.sleep(2.2)
bot.handle_message("age?")
bot.handle_message("unknow message test")
【讨论】:
以上是关于让 Telegram 机器人回复由命令回复的消息的主要内容,如果未能解决你的问题,请参考以下文章