Telegram 机器人:可用命令的目录
Telegram bot: a dirctionary of available commands
如何为 Telegram 机器人组织可用命令的字典?优秀的程序员是如何做到的?我知道写几十个 if
语句是个坏主意,还有一个 switch
语句。
目前使用 switch
:
实现
- 机器人收到命令
- 在
switch
中找到它
- 处理命令
- 向用户发送响应
但是当有几十个命令时,switch
运算符变得难以维护。解决这个问题的常用方法是什么?
我不是 Python 编码员,但看来您的问题应该用 associative array data structure regardless the language you use. The actual name of the structure may vary from language to language: for example, in C++ it is called map
, and in Python it is.. dictionary 来解决!因此,您多次在问题中写下相关关键字(甚至使用原始语言)。
考虑到以上几点,您的程序草图可能如下所示:
#!/usr/bin/python
# Command processing functions:
def func1():
return "Response 1"
def func2():
return "Response 2"
# Commands dictionary:
d = {"cmd1":func1, "cmd2":func2}
# Suppose this command was receiced by the bot:
command_received = "cmd1"
# Processing:
try:
response = d[command_received]()
except KeyError:
response = "Unknown command"
# Sending response:
print response
如何为 Telegram 机器人组织可用命令的字典?优秀的程序员是如何做到的?我知道写几十个 if
语句是个坏主意,还有一个 switch
语句。
目前使用 switch
:
- 机器人收到命令
- 在
switch
中找到它
- 处理命令
- 向用户发送响应
但是当有几十个命令时,switch
运算符变得难以维护。解决这个问题的常用方法是什么?
我不是 Python 编码员,但看来您的问题应该用 associative array data structure regardless the language you use. The actual name of the structure may vary from language to language: for example, in C++ it is called map
, and in Python it is.. dictionary 来解决!因此,您多次在问题中写下相关关键字(甚至使用原始语言)。
考虑到以上几点,您的程序草图可能如下所示:
#!/usr/bin/python
# Command processing functions:
def func1():
return "Response 1"
def func2():
return "Response 2"
# Commands dictionary:
d = {"cmd1":func1, "cmd2":func2}
# Suppose this command was receiced by the bot:
command_received = "cmd1"
# Processing:
try:
response = d[command_received]()
except KeyError:
response = "Unknown command"
# Sending response:
print response