def handle_message(event): print("*****Input Message In handle_message*****") print(event) inputMessage = event.message.text ms = Message(inputMessage) replyMessage = ms.getOutput() message = TextSendMessage(text=replyMessage) line_bot_api.reply_message(event.reply_token, message)
def test_mail_wrong_password(capsys): Message.set_config_files('credentials_example.cfg', 'config.cfg') with pytest.raises(Exception) as excinfo: Mail.send() assert 'Username and Password not accepted.' in str(excinfo.value) cp = capsys.readouterr() assert not cp.out assert not cp.err
def test_whatsapp_wrong_token(capsys): Message.set_config_files('tests/credentials_wrong.cfg', 'config.cfg') with pytest.raises(Exception) as excinfo: WhatsApp.send() assert 'HTTP 401 error: Unable to create record: Authenticate' in str( excinfo.value) cp = capsys.readouterr() assert not cp.out assert not cp.err
def test_whatsapp_wrong_SID(capsys): Message.set_config_files('credentials_example.cfg', 'config.cfg') with pytest.raises(Exception) as excinfo: WhatsApp.send() assert 'Unable to create record: The requested resource /2010-04-01/Accounts/PLACE_HERE_YOUR_SID/Messages.json was not found' in str( excinfo.value) cp = capsys.readouterr() assert not cp.out assert not cp.err
def test_slack_wrong_password(capsys): Message.set_config_files('credentials_example.cfg', 'config.cfg') with pytest.raises(Exception) as excinfo: Slack.send() assert 'The server responded with: {\'ok\': False, \'error\': \'invalid_auth\'}' in str( excinfo.value) cp = capsys.readouterr() assert not cp.out assert not cp.err
def test_whatsapp_wrong_sender(capsys): Message.set_config_files('credentials.cfg', 'tests/config_wrong_sender.cfg') with pytest.raises(Exception) as excinfo: WhatsApp.send() assert 'Unable to create record: Twilio could not find a Channel with the specified From address' in str( excinfo.value) cp = capsys.readouterr() assert not cp.out assert not cp.err
def _send_private_message(self, _=None): message = self.input_box.get('0.0', END) # TODO encapsulate self.input_box.delete('0.0', END) message = message.rstrip(u'\n') if message == '': return message = Message(MessageType.PRIVATE, message) message.addressee = self.nickname self.client.send_message(message)
def test_slack_wrong_channel(capsys): Message.set_config_files('credentials.cfg', 'tests/config_wrong_channel.cfg') with pytest.raises(Exception) as excinfo: Slack.send() assert 'The server responded with: {\'ok\': False, \'error\': \'channel_not_found\'}' in str( excinfo.value) cp = capsys.readouterr() assert not cp.out assert not cp.err
def test_mail_wrong_smtp(capsys): Message.set_config_files('credentials.cfg', 'tests/config_wrong_smtp.cfg') with pytest.raises(Exception) as excinfo: Mail.send() assert 'service not known' in str( excinfo.value) or '[Errno 11001] getaddrinfo failed' in str( excinfo.value) cp = capsys.readouterr() assert not cp.out assert not cp.err
def test_insert_unknown(self): unknown_msg = Message(category=UNKNOWN_MSG, message="Something else") old_tree = MessageTree(None) new_tree = old_tree.insert(tree=old_tree, log_message=unknown_msg) self.assertEqual(new_tree.get_root(), None)
def home(): errors = [] results = {} if request.method == 'POST': try: if 'text-to-encode' in request.form: encoding = Message(request.form['text-to-encode']).encode() results.update({ 'encoded-text': encoding.text, 'key': encoding.key }) except: errors.append("[ERROR]: Could not encode text.") try: if ('text-to-decode' in request.form) and \ ('decode-key' in request.form): results.update({ 'decoded-text': EncodedMessage( request.form['text-to-decode'], int(request.form['decode-key']) ).decode().text }) except: errors.append("[ERROR]: Could not decode text.") return render_template('index.html', errors=errors, results=results)
def test_exercise(): message = Message("Grace", "Hello there!") service = MessagingService() service.add(message) assert service.get_messages() == ["Grace: Hello there!"]
def hello_world(event=None, context=None): """ Reads a parameter from Parameter Store, makes a HTTPS request to a [fake online REST API](https://jsonplaceholder.typicode.com/), and, depending on the environment variables, writes part of the response from the fake REST API to a csv file or Postgres, hosted either locally or on AWS. The csv file is either in a local directory: `<aws-terraform-bootstrap-dir>/data/<timestamp>_message.csv>` or an AWS bucket: `hello-world-<hello_world_bucket_name_suffix>/<timestamp>_message.csv` The Postgres database is either a local Postgres instance: `$ psql --dbname=hello_world --user=hellorole --host=localhost` or a Postgres instance hosted on a RDS host: Args: event: AWS e context: Returns: dict: contains message (str): title of message fetched from jsonplaceholder.typicode.com secret (str): secret fetched from SSM or dummy secret """ if Properties.use_aws: secret = get_parameter('secret') print('fetched secret from SSM Parameter Store', secret) else: secret = dummy_secret response = requests.get(fake_json_endpoint).json() print('fetched message from the internet', response['title']) if Properties.storage_type == 'csv': print("storage_type is 'csv'") message_data = [[ datetime.datetime.utcnow().timestamp(), response['title'] ]] write_result(Properties.use_aws, Properties.s3_bucket, message_data) elif Properties.storage_type == 'postgres': print("storage_type is 'postgres'") engine = SqlAlchemyEngine.engine() Base.metadata.create_all(engine.db_client) session = engine.scoped_session_maker() message_dao = MessageDao() print('writing to database') message_dao.save(session=session, commit=True, popo=Message(message=response['title'])) else: raise Exception('storage_type must be either "postgres" or "csv".') response = {'message': response['title'], 'secret': secret} print('hello_world response: ', response) return response
def test_spongebob_mock(): """Test returns string with every second letter capitalized.""" c = ChatBot() c.stimulus = Message(text='this is a test message') assert type(c.spongebob_mock()) is Message assert c.spongebob_mock().text \ == "tHiS iS a TeSt MeSsAgE"
def test_mad_lib(): """Test func returns correct string.""" c = ChatBot() c.stimulus = Message(sender="TestSender") assert type(c.mad_lib()) is Message assert '@tag_member' not in c.mad_lib().text assert '@noun' not in c.mad_lib().text assert '@adjective' not in c.mad_lib().text
def get_messages(self): history = {} self.cursor.execute("SELECT * FROM Messages") result = self.cursor.fetchall() for r in result: if r[1] not in history.keys(): history[r[1]] = [] history[r[1]].append(Message(r[2], r[3], r[4])) return history
def get_log_message(tokens: List[str]) -> Message: message_type = get_message_type(tokens=tokens) time_stamp, msg = (int(tokens[2]), " ".join( tokens[3:])) if "Error" in message_type else (int(tokens[1]), " ".join(tokens[2:])) return Message(category=LOG_MSG, message_type=message_type, time_stamp=time_stamp, message=msg.strip())
def send(self, _=None): beginning = '0.0' message = self.message_input_box.get(beginning, END) # TODO encapsulate self.message_input_box.delete(beginning, END) message = message.rstrip(u'\n') if message == '': return message = Message(MessageType.SHARED, message) self.client.send_message(message)
def test_insert_node(self): old_tree = MessageTree(None) log_message = Message(category=LOG_MSG, message="Test", message_type=INFO, time_stamp=1000) new_tree = MessageTree.insert(tree=old_tree, log_message=log_message) self.assertNotEqual(id(old_tree), id(new_tree)) self.assertEqual(str(new_tree.get_root().log_message), "LogMessage Info 1000 Test")
def test_build_tree(self): message_1 = Message(category=LOG_MSG, message="msg 1", message_type=INFO, time_stamp=100) message_2 = Message(category=LOG_MSG, message="msg 2", message_type=ERROR.format(err_code=20), time_stamp=20) message_3 = Message(category=LOG_MSG, message="msg 3", message_type=WARNING, time_stamp=50) messages = [message_1, message_2, message_3] tree = build_tree(log_messages=messages) tree_root = tree.get_root() self.assertEqual(tree_root.log_message, message_1) self.assertEqual(tree_root.left.log_message, message_2) self.assertEqual(tree_root.left.right.log_message, message_3)
def test_what_went_wrong(self): message_1 = Message(category=LOG_MSG, message="msg 1", message_type=ERROR.format(err_code=100), time_stamp=100) message_2 = Message(category=LOG_MSG, message="msg 2", message_type=ERROR.format(err_code=60), time_stamp=20) message_3 = Message(category=LOG_MSG, message="msg 3", message_type=ERROR.format(err_code=70), time_stamp=50) message_4 = Message(category=LOG_MSG, message="msg 4", message_type=ERROR.format(err_code=17), time_stamp=18) message_5 = Message(category=LOG_MSG, message="msg 5", message_type=INFO, time_stamp=50) message_6 = Message(category=LOG_MSG, message="msg 6", message_type=WARNING, time_stamp=30) log_messages = [ message_1, message_2, message_3, message_4, message_5, message_6 ] error_messages = what_went_wrong(messages=log_messages) self.assertEqual(len(error_messages), 3) self.assertEqual(error_messages[0], "msg 2") self.assertEqual(error_messages[1], "msg 3") self.assertEqual(error_messages[2], "msg 1")
def test_in_order(self): message_1 = Message(category=LOG_MSG, message="msg 1", message_type=INFO, time_stamp=100) message_2 = Message(category=LOG_MSG, message="msg 2", message_type=ERROR.format(err_code=20), time_stamp=20) message_3 = Message(category=LOG_MSG, message="msg 3", message_type=WARNING, time_stamp=50) messages = [message_1, message_2, message_3] tree = build_tree(log_messages=messages) sorted_messages = in_order_traversal(tree=tree) self.assertEqual(len(sorted_messages), 3) self.assertEqual(sorted_messages[0].time_stamp, 20) self.assertEqual(sorted_messages[1].time_stamp, 50) self.assertEqual(sorted_messages[2].time_stamp, 100)
def on_received_message(self, blocking_channel, deliver, properties, message): result = message.decode('utf-8') blocking_channel.confirm_delivery() try: envelope = Message(result) self.add_message(envelope) self.fun_call_update() blocking_channel.stop_consuming() except Exception as e: print(e) print("wrong data format") finally: blocking_channel.stop_consuming()
def get_message(self, message: Message): nickname_start, nickname_end = message.get_nick_position() message = str(message) + '\n' self.messages_box.config(state=NORMAL) need_to_scroll = False if self.messages_box.yview()[1] > 0.9: need_to_scroll = True cur_line, cur_column = map(int, self.messages_box.index(END).split('.')) cur_line -= 1 self.messages_box.insert(END, message) self.messages_box.tag_add('nickname', '{}.{}'.format(cur_line, nickname_start), '{}.{}'.format(cur_line, nickname_end)) self.messages_box.tag_config('nickname', foreground='blue') self.messages_box.config(state=DISABLED) if need_to_scroll: self.messages_box.see(END)
def get_messages(self): messages = [] for msg_line in self.msg_lines: msg_type = self.parser.get_type(msg_line) sender = self.parser.get_sender(msg_line) if msg_type == 'user': self.participants.add(sender) timestamp = self.parser.get_timestamp(msg_line) content = self.parser.get_content(msg_line) messages.append(Message(sender, timestamp, content, msg_type)) self.system_messages = [ msg for msg in messages if msg.msg_type == 'system' ] self.admin_messages = [ msg for msg in messages if msg.msg_type == 'admin' ] self.user_messages = [ msg for msg in messages if msg.msg_type == 'user' ]
def add_new_message(message): try: app_id = message['application_id'] session_id = message['session_id'] message_id = message['message_id'] participants = message['participants'] content = message['content'] except: raise Exception("data not correct") new_message = Message(app_id, session_id, message_id, participants, content) conn = message_db.create_connection(DATABASE) with conn: try: message = (new_message.application_id, new_message.session_id, new_message.message_id, ",".join( new_message.participants), new_message.content) message_db.insert_message(conn, message) except: raise Exception("message_id is alredy exist")
async def send_notifications(self, guild=None): if guild is None: db_players = self.uow.player_repo.get_players() Logger.log("task", f"Sending notifications for {len(db_players)} players") else: db_guild = self.uow.guild_repo.get_guild_by_discord_id(guild.id) db_players = db_guild.players Logger.log(db_guild, f"Sending notifications for {len(db_players)} players") for db_player in db_players: for db_guild in db_player.guilds: if db_guild.recent_scores_channel_id is None: Logger.log(db_guild, f"Missing recent scores channel, skipping!") return channel = self.uow.client.get_channel(db_guild.recent_scores_channel_id) db_scores = self.uow.score_repo.get_unsent_scores(db_player, db_guild) Logger.log(db_guild, f"{db_player} has {len(db_scores)} scores to notify") for db_score in db_scores: embed = Message.get_score_embed(db_player, db_score, db_score.song) await channel.send(embed=embed) self.uow.score_repo.mark_score_sent(db_score, db_guild)
def _in_order(self, node: Node, accumulator: Message): if node: self._in_order(node=node.left, accumulator=accumulator) accumulator.append(node.log_message) self._in_order(node=node.right, accumulator=accumulator)
def test_slack(capsys): Message.set_config_files('credentials.cfg', 'config.cfg') Slack.send() cp = capsys.readouterr() assert not cp.out assert not cp.err
def test_whatsapp(capsys): Message.set_config_files('credentials.cfg', 'config.cfg') WhatsApp.send() cp = capsys.readouterr() assert not cp.out assert not cp.err