我正在为“ Telegram Bot” 类编写方法,方法之一是带有3个可选参数的“ getUpdate” -“ last_message”,“ chat_id”和“文本”。 如果您注意提供的代码,您将看到它包含5 ifs语句。我相信应该有一种减少数量的方法。
Json文件看起来是另一种方式:
{'ok':是,'结果':[{'update_id':xxxxx,'message':{'message_id':2,'from':{'id':xxxxx,'is_bot':False, 'first_name':'Xxxx','last_name':'Xxxx','language_code':'en'},'chat':{'id':xxxxxxx,'first_name':'Xxxx','last_name':'Xxxx ','type':'private'},'date':1560346414,'text':'Hi'}},{'update_id':xxxxxx,'message':{'message_id':3,'from':{ 'id':xxxxx,'is_bot':False,'first_name':'xxxx'},'chat':{'id':xxxx,'first_name':'Zzzz','type':'private'},'日期”:1560346988,“文本”:“ /开始”,“实体”:[{'偏移量:0,'长度':6,'类型':'bot_command'}]}}},{'update_id':xzcdsfsdcd ,'message':{'message_id':4,'from':{'id':xxxx,'is_bot':False,'first_name':'xxxxx','language_code':'ru'},'chat': {'id':xxxx,'first_name':'Zzzz','type':'private'},'date':1560346990,'text':'Hi'}},{'update_id':xxxxxx,'message' :{'message_id':22,'from':{'id':yyyy,'is_bot':False,'first_name':'Xxxx','last_name':'Xxxx','language_code':'en'}, '聊天':{'id':yy yy,'first_name':'Xxxx','last_name':'Xxxx','type':'private'},'date':1560363527,'text':'Hey'}}]}}
def getUpdates(self,last_message=False,chat_id=False,text=False):
getUpdate_object=requests.get(self.base_url+"getUpdates").json()
if last_message==True:
last_message_object=getUpdate_object['result'][len(getUpdate_object['result'])-1]
if chat_id==False and text==False:
return last_message_object
elif chat_id==True and text==False:
return last_message_object['message']['chat']['id']
elif chat_id==False and text==True:
return last_message_object['message']['text']
elif chat_id==True and text==True:
chatid=last_message_object['message']['chat']['id']
last_text=last_message_object['message']['text']
return (chatid,last_text)
else:
return getUpdate_object
答案 0 :(得分:0)
您不必尝试每对True
和False
的组合,您可以根据每个单独的条件逐步构建结果:
def getUpdates(self,last_message=False,chat_id=False,text=False):
getUpdate_object=requests.get(self.base_url+"getUpdates").json()
if last_message==True:
last_message_object=getUpdate_object['result'][len(getUpdate_object['result'])-1]
if not chat_id and not text:
return last_message_object
result = []
if chat_id:
result.append(last_message_object['message']['chat']['id'])
if text:
result.append(last_message_object['message']['text'])
return tuple(result)
else:
return getUpdate_object