コード例 #1
0
 def showMeSomeNews():
     # settings to make the request
     get_url = Constants.DADOS_ABERTOS_BASE_API + Constants.PROPOSICOES_ENDPOINT
     headers = {'accept': 'application/json'}
     page_number = 0
     # we will search for new PLs in every page until found one we haven't used yet
     while (True):
         page_number += 1
         parameters = {
             'siglaTipo': 'PL',
             'ordem': 'DESC',
             'ordenarPor': 'id',
             'pagina': page_number
         }
         # this request to the Dados Abertos API returns a list of projects (but they aren't complete)
         pls_list = requests.get(get_url,
                                 params=parameters,
                                 headers=headers).json().get('dados')
         for pl in pls_list:
             if (not MongoDB.verifyIfUsedPL(pl.get('id'))):
                 # so, when we found a project that we haven't used yet, we request a more complete version of it
                 full_pl_infos = requests.get(
                     pl.get('uri'), headers=headers).json().get('dados')
                 if (full_pl_infos
                         and MongoDB.insertNewUsedPL(full_pl_infos)
                         == 'success'):
                     return full_pl_infos
コード例 #2
0
 def scheduled_script(self):
     if (MongoDB.verifyIfTimeToSendMessage()):
         # ------------------------------------------------
         # get a new PL from the Dados Abertos API and turn it to a message
         newPL = ApiDadosAbertos.showMeSomeNews(
         )  # <- Already saves the PL in our database
         message = MessageModels.NEW_PL_MESSAGE_MODEL.format(
             newPL.get('numero'), newPL.get('ano'), newPL.get('ementa'),
             newPL.get('statusProposicao').get('despacho'),
             newPL.get('statusProposicao').get('descricaoTramitacao'),
             newPL.get('statusProposicao').get('descricaoSituacao'),
             newPL.get('justificativa'),
             newPL.get('statusProposicao').get('dataHora'), newPL.get('id'))
         # get all users from Mongo
         users = MongoDB.getAlluserIds()
         # send message
         InterativeBot.sendMessageToMultipleUsers(
             users.get(Constants.BOT1_TOKEN), message)
         SimpleBot.sendMessageToMultipleUsers(
             users.get(Constants.BOT2_TOKEN), message)
         # save in Mongo the sended message (and users involved)
         data = {'message': message, 'sended_to': users}
         MongoDB.insertNewSendedProject(data)
         # response
         return json.dumps(data)
     else:
         print("\nkeep alive\n")
         return json.dumps({'status': 'alive'})
コード例 #3
0
	def handleCallback(message_info):
		# understand the content
		callback_id     = message_info.get("callback_query").get("id")
		callback_type   = message_info.get("callback_query").get("data")
		message_text	= message_info.get("callback_query").get("message").get("text")
		message_id      = message_info.get("callback_query").get("message").get("message_id")
		chat_id         = message_info.get("callback_query").get("message").get("chat").get("id")
		# answer the callback to hide the loading in the button
		requests.get(InterativeBot.base_api + Constants.ANSWER_CALLBACK_ENDPOINT, {'callback_query_id':callback_id})
		# properly handle the callback
		if(callback_type == Constants.CALLBACK_SHOW_PROPOSITION):
			InterativeBot.show_url(chat_id, message_id, message_text)
		elif(callback_type == Constants.CALLBACK_SHOW_AUTHORS):
			InterativeBot.send_project_authors(chat_id, message_id, message_text)
		elif(callback_type == Constants.CALLBACK_SHOW_KEY_WORDS):
			InterativeBot.send_keywords(chat_id, message_id, message_text)
		elif(callback_type == Constants.CALLBACK_SHOW_HISTORY):
			InterativeBot.send_project_history(chat_id, message_id, message_text)
		elif(callback_type == Constants.CALLBACK_DESPACHO):
			InterativeBot.send_despacho(chat_id, message_id, message_text)
		elif(Constants.CALLBACK_AUTHORS_INFO in callback_type):
			InterativeBot.send_authors_info(chat_id, message_id, message_text)
		elif(callback_type == Constants.CALLBACK_SHOW_PROP_EXAMPLE):
			newPL = MongoDB.returnUsedPL()
			message = MessageModels.NEW_PL_MESSAGE_MODEL.format(newPL.get('numero'),
																newPL.get('ano'),
																newPL.get('ementa'),
																newPL.get('statusProposicao').get('despacho'),
																newPL.get('statusProposicao').get('descricaoTramitacao'),
																newPL.get('statusProposicao').get('descricaoSituacao'),
																newPL.get('justificativa'),
																newPL.get('statusProposicao').get('dataHora'),
																newPL.get('id'))
			InterativeBot.sendProjectMessageToOneUser(chat_id, message)
コード例 #4
0
    def handle_updates(self):
        update = bottle_request.json
        print("\n\nNEW UPDATE\n{}\n\n".format(update))  #just for log

        if (update.get("callback_query")):  #handle button click
            requests.get(
                self.api_base_url + "answerCallbackQuery",
                {'callback_query_id': update.get("callback_query").get("id")})
            user_id = update.get("callback_query").get("from").get("id")
            if (update.get("callback_query").get("data") == "google-pressed"):
                self.show_url(
                    update.get("callback_query").get("message").get(
                        "chat").get("id"),
                    update.get("callback_query").get("message").get(
                        "message_id"))
            else:
                self.send_message_to_specific_person(
                    user_id,
                    update.get("callback_query").get("data"))
            return

        user_id = update.get("message").get("from").get("id")
        user = self.users_list.get(user_id)
        if (user):
            MongoDB.newInteractionFromUser(user_id)
            if (not user.greeted):
                self.start_the_chat(user)
                return
            elif (not user.received_inicial_message):
                self.send_initial_message(user)
            else:
                self.send_message_to_specific_person(
                    user_id,
                    "A partir daqui eu ainda nao sei o que fazer hehehe desculpa"
                )
        else:
            # setup users
            MongoDB.insertNewUser(update.get("message").get("from"))
            first_name = update.get("message").get("from").get("first_name")
            last_name = update.get("message").get("from").get("last_name")
            username = update.get("message").get("from").get("username")
            user = User(user_id, first_name, last_name, username)
            self.users_list[user_id] = user
            # greet user
            self.start_the_chat(user)

        return {"status": "up"}
コード例 #5
0
 def send_message_to_all_users(self):
     users = MongoDB.getAlluserIds()
     for userid in users:
         print("messaging user {0}".format(userid))
         self.send_message_to_specific_person(
             userid, "messaging everybody. I AM ALIVE!")
     response.headers['Content-Type'] = 'application/json'
     return {"Status": "Ok", "users_messaged": list(users)}
コード例 #6
0
 def handle_chatbot1_updates(self):
     this_bot_token = Constants.BOT1_TOKEN
     # get the data
     new_message = bottle_request.json
     print()
     print('RECEIVED MESSAGE IN CHATBOT 1')
     print(new_message)
     print()
     # verify type of message
     if (new_message.get("callback_query")):
         InterativeBot.handleCallback(new_message)
     if (new_message.get("message")):
         user_id = new_message.get("message").get("from").get("id")
         if (not MongoDB.checkIfUserExistsInBot(user_id, this_bot_token)):
             InterativeBot.greetNewUser(new_message)
             MongoDB.insertNewUser(
                 new_message.get("message").get("from"), this_bot_token)
         else:
             InterativeBot.handleTextMessage(new_message)
     MongoDB.insertNewReceivedMessage(new_message, this_bot_token)
コード例 #7
0
	def send_despacho(chat_id, message_id, message_text):
		# get the PL url
		pl_id = InterativeBot.getProjectIdFromMessage(message_text)
		keywords = MongoDB.getDespachoFromPL(pl_id)
		# building the message
		if(keywords and keywords.get('statusProposicao').get('despacho')):
			message = MessageModels.PL_DESPACHO_MESSAGE.format( keywords.get('numero'),
																keywords.get('ano'),
																keywords.get('statusProposicao').get('despacho'))
		else:
			message = MessageModels.PL_DESPACHO_ERROR_MESSAGE
		# setup
		endpoint = InterativeBot.base_api + Constants.SEND_MESSAGE_ENDPOINT
		params   = {'chat_id': chat_id,
				    'text': message,
				    'reply_to_message_id': message_id}
		# send the message
		InterativeBot.send(endpoint, params)
コード例 #8
0
	def show_url(chat_id, message_id, message_text):
		# get the PL url
		pl_id = eval(message_text.split('ID da PL na API de Dados Abertos: ')[-1])
		url = MongoDB.getUrlFromPL(pl_id)
		# setup
		endpoint = SimpleBot.base_api + Constants.EDIT_MESSAGE_ENDPOINT
		if(url):
			url = "https://docs.google.com/viewer?url=" + url # para abrir o pdf no drive e a pessoa nao precisar baixar
			keyboard = {"inline_keyboard": [[
	                        { "text": "CLIQUE: link para proposta na íntegra",
	                          "url":url}]]}
			params = {'chat_id': chat_id,
	                  'message_id': message_id,
	                  'text': message_text,
	                  'reply_markup': json.dumps(keyboard)}
		else:
			params = {'chat_id': chat_id,
	                  'message_id': message_id,
	                  'text': message_text + '\n\nESSA PL NÃO POSSUI LINK PARA PROPOSTA NA ÍNTEGRA'}
		# request
		SimpleBot.send(endpoint, params)
コード例 #9
0
	def show_url(chat_id, message_id, message_text):
		# get the PL url
		pl_id = InterativeBot.getProjectIdFromMessage(message_text)
		url = MongoDB.getUrlFromPL(pl_id)
		# setup
		endpoint = InterativeBot.base_api + Constants.EDIT_MESSAGE_ENDPOINT
		if(url):
			url = "https://docs.google.com/viewer?url=" + url # para abrir o pdf no drive e a pessoa nao precisar baixar
			keyboard = {"inline_keyboard": [
						[{ "text": "CLIQUE: link para proposta na íntegra",
							"url":url}],
						[{ "text": "autores",
						   "callback_data": Constants.CALLBACK_SHOW_AUTHORS},
						 { "text": "palavras-chave",
						   "callback_data": Constants.CALLBACK_SHOW_KEY_WORDS}],
						[{ "text": "histórico",
						   "callback_data": Constants.CALLBACK_SHOW_HISTORY},
						   { "text": "despacho",
						   "callback_data": Constants.CALLBACK_DESPACHO}]]}
			params = {'chat_id': chat_id,
	                  'message_id': message_id,
	                  'text': message_text,
	                  'reply_markup': json.dumps(keyboard)}
		else:
			keyboard = {"inline_keyboard": [
						[{ "text": "autores",
						   "callback_data": Constants.CALLBACK_SHOW_AUTHORS},
						 { "text": "palavras-chave",
						   "callback_data": Constants.CALLBACK_SHOW_KEY_WORDS}],
						[{ "text": "histórico",
						   "callback_data": Constants.CALLBACK_SHOW_HISTORY},
						   { "text": "despacho",
						   "callback_data": Constants.CALLBACK_DESPACHO}]]}
			params = {'chat_id': chat_id,
	                  'message_id': message_id,
	                  'text': 'ESSA PL NÃO POSSUI LINK PARA PROPOSTA NA ÍNTEGRA \n\n' + message_textc}
		# request
		InterativeBot.send(endpoint, params)
コード例 #10
0
	def handleCallback(message_info):
		# understand the content
		callback_id     = message_info.get("callback_query").get("id")
		callback_type   = message_info.get("callback_query").get("data")
		message_content = message_info.get("callback_query").get("message").get("text")
		message_id      = message_info.get("callback_query").get("message").get("message_id")
		chat_id         = message_info.get("callback_query").get("message").get("chat").get("id")
		# answer the callback to hide the loading in the button
		requests.get(SimpleBot.base_api + Constants.ANSWER_CALLBACK_ENDPOINT, {'callback_query_id':callback_id})
		# properly handle the callback
		if(callback_type == Constants.CALLBACK_SHOW_PROPOSITION):
			SimpleBot.show_url(chat_id, message_id, message_content)
		elif(callback_type == Constants.CALLBACK_SHOW_PROP_EXAMPLE):
			newPL = MongoDB.returnUsedPL()
			message = MessageModels.NEW_PL_MESSAGE_MODEL.format(newPL.get('numero'),
																newPL.get('ano'),
																newPL.get('ementa'),
																newPL.get('statusProposicao').get('despacho'),
																newPL.get('statusProposicao').get('descricaoTramitacao'),
																newPL.get('statusProposicao').get('descricaoSituacao'),
																newPL.get('justificativa'),
																newPL.get('statusProposicao').get('dataHora'),
																newPL.get('id'))
			SimpleBot.sendProjectMessageToOneUser(chat_id, message)
コード例 #11
0
	def send(endpoint, params):
		# save to mongo
		MongoDB.insertNewSendedMessage(params, Constants.BOT1_TOKEN)
		# request
		resp = requests.get(endpoint, params)
		return resp
コード例 #12
0
 def return_database(self):
     resp = MongoDB.getAllData()
     response.headers['Content-Type'] = 'application/json'
     return json.dumps(resp)