def get_message(sock, settings, state): """ Read a message from the IRC connection, simulaneously making sure to keep the connection alive and handling the IRC statey business. Returns the message, perhaps with convenience information attached. """ raw_message = network.read(sock) if raw_message: message = from_raw(raw_message) response = manage(message, settings, state) if response: send_message(sock, response) elif message.command == 'PRIVMSG': return message return None if settings.channel != state.joined: if state.joined: send_message(sock, Message.part(state.joined)) send_message(sock, Message.join(settings.channel)) return None
def test_maxClusterSize(self): self.assertEqual(1, self.crowd.maxClusterSize) message2 = Message(4, 'sdf', 'A project to cluster high-dimensional streams.', test_time) message2.vector=Vector({2:4}) stream2 = Stream(4, message2) self.cluster.addDocument(stream2) self.assertEqual(2, self.crowd.maxClusterSize)
def show_start_wave(user_info, surface): global WAVE_TIME, START_WAVE, CREATE_WAVE start_wave = Message(surface, (0, 10), ('Start Wave ' + str(user_info.wave + 1) + '/' + str(user_info.waves)), font=pg.font.SysFont('comicsansms', 24, True), bg_color=BROWN) start_wave.rect.right = 48*TILE_SIZE - 10 start_wave.blit() user_info.start_wave = start_wave
def manage(message, settings, state): """ Takes a message and determines if it requires some administrative connection management, such as responding to a PING, or changing nicks, or joining channels or whatever. Returns a message to be sent to the server with the action taken. If None is returned, no action needs to be taken by the server. """ if message.command == 'PING': return Message.pong(*message.arguments) elif message.command == '403': # Channel doesn't exist, stop trying to join settings.channel = None elif message.command == '433': def generate_nick(nick): truncated = nick[:min(len(nick), 6)] alphabet = string.ascii_lowercase + string.digits random_chars = ''.join(random.choice(alphabet) for _ in range(2)) return '{}_{}'.format(truncated, random_chars) logger.warning('Nick %s is already in use', state.nick) state.nick = generate_nick(settings.nick) return Message.nick(state.nick) elif message.command == '001': state.nick = message.arguments[0] elif message.command == 'JOIN': if getattr(message, 'origin', None) == state.nick: state.joined = message.arguments[0]
def convertTweetJSONToMessage(tweet, **twitter_stream_settings): tweetTime = getDateTimeObjectFromTweetTimestamp(tweet['created_at']) message = Message(tweet['user']['screen_name'], tweet['id'], tweet['text'], tweetTime) message.vector = Vector() for phrase in getPhrases(getWordsFromRawEnglishMessage(tweet['text']), twitter_stream_settings['min_phrase_length'], twitter_stream_settings['max_phrase_length']): if phrase not in message.vector: message.vector[phrase]=0 message.vector[phrase]+=1 return message
def test_maxClusterSize(self): self.assertEqual(1, self.crowd.maxClusterSize) message2 = Message(4, 'sdf', 'A project to cluster high-dimensional streams.', test_time) message2.vector = Vector({2: 4}) stream2 = Stream(4, message2) self.cluster.addDocument(stream2) self.assertEqual(2, self.crowd.maxClusterSize)
def setUp(self): self.m1 = Message(1, 'sdf', 'A project to cluster high-dimensional streams.', test_time - timedelta(seconds=60)) self.m1.vector = Vector({1: 1., 2: 3.}) self.stream = Stream(1, self.m1) self.m2 = Message(1, 'sdf', 'A project to cluster high-dimensional streams.', test_time) self.m2.vector = Vector({2: 3.})
def convertTweetJSONToMessage(tweet, **twitter_stream_settings): tweetTime = getDateTimeObjectFromTweetTimestamp(tweet['created_at']) message = Message(tweet['user']['screen_name'], tweet['id'], tweet['text'], tweetTime) message.vector = Vector() for phrase in getPhrases(getWordsFromRawEnglishMessage(tweet['text']), twitter_stream_settings['min_phrase_length'], twitter_stream_settings['max_phrase_length']): if phrase not in message.vector: message.vector[phrase] = 0 message.vector[phrase] += 1 return message
def getClusterFromMapFormat(clusterMap): dummyMessage = Message(1, '', '', datetime.now()) dummyMessage.vector=Vector({}) dummyStream=Stream(1, dummyMessage) cluster = StreamCluster(dummyStream) cluster.clusterId = clusterMap['clusterId'] cluster.lastStreamAddedTime = getDateTimeObjectFromTweetTimestamp(clusterMap['lastStreamAddedTime']) cluster.mergedClustersList = clusterMap['mergedClustersList'] cluster.documentsInCluster = clusterMap['streams'] for k,v in clusterMap['dimensions'].iteritems(): cluster[k]=v return cluster
def getClusterFromMapFormat(clusterMap): dummyMessage = Message(1, '', '', datetime.now()) dummyMessage.vector = Vector({}) dummyStream = Stream(1, dummyMessage) cluster = StreamCluster(dummyStream) cluster.clusterId = clusterMap['clusterId'] cluster.lastStreamAddedTime = getDateTimeObjectFromTweetTimestamp( clusterMap['lastStreamAddedTime']) cluster.mergedClustersList = clusterMap['mergedClustersList'] cluster.documentsInCluster = clusterMap['streams'] for k, v in clusterMap['dimensions'].iteritems(): cluster[k] = v return cluster
def from_raw(raw_message): """ Deserialises an inbound message, returning a Message object. """ user, command, args, last_arg = basic_parse(raw_message) if last_arg: args.append(last_arg) message = Message(command, arguments=args) message.user = user return message
def getMessage(): error = False id = request.json['id'] new = Message() try: new.get(id) except (Exception) as err: error = True return handleError(err) finally: if not (error): result = new.json() return jsonify({'result': 'success', 'data': result})
def hello(sock, settings, state): """ Sends the basic identy information to the IRC server and sets some initial state required by the rest of the irc module procedures. """ send_message(sock, Message.nick(settings.nick)) send_message(sock, Message.user(settings.nick, 'Bot {}'.format(settings.nick))) state.nick = settings.nick state.joined = ''
def addMessage(): error = False msg = request.json['msg'] id_user = request.json['id_user'] id_chat = request.json['id_chat'] read = request.json['read'] new = Message(msg, None, id_user, id_chat, read) try: new.add() except (Exception) as err: error = True return handleError(err) finally: if not (error): return jsonify({'result': 'success'})
def cmd_help(args): if len(args) == 0: msg =\ """ For additional help, run `!help <command name>` e.g. `!help !roll` Available commands: """ for cmd in commands.list: msg += "`{cmd}`: {desc}\n".format(cmd=cmd.name, desc=cmd.desc) else: msg = "" for name in args: if name in commands.map.keys(): cmd = commands.map[name] if type(cmd.help) is str: msg += cmd.help elif cmd.help is None: msg += "Usage: `{cmd}`\n{desc}".format(cmd=cmd.name, desc=cmd.desc) else: msg += cmd.help(args[1:]).content else: msg += "`{name}` is not a valid command".format(name=name) msg += '\n' return Message(content=msg)
def setUp(self): self.message = Message( 1, 'sdf', 'A project to cluster high-dimensional streams.', datetime.now()) self.message.vector = Vector({1: 2., 2: 3.}) self.s1 = Stream(1, self.message) self.v1 = Vector({1: 2., 3: 3.})
def send(self, user_id, message: Message): if isinstance(message, str): message = Message(content=message) assert (isinstance(message, Message)) payload = { "recipient": { "id": user_id }, "message": dict(), "notification_type": message.notification_type.value, "messaging_type": message.message_type.value } if message.content: payload["message"]["text"] = message.content if message.quick_replies: payload["message"]["quick_replies"] = [ x.to_dict() for x in message.quick_replies ] if message.metadata: payload["message"]["metadata"] = message.metadata if message.tag: payload["tag"] = message.tag self.send_raw(payload)
def handler_custom_email(self, req: MessagingEntry): req.sender.send( Message(content="Thanks for signing up! You just got $250!")) self.balances[req.sender.id] = 250.0 self.emails[req.sender.id] = req.message req.sender.set_state("Home") req.continue_processing = True
def createMockData(): connection = sqlite3.connect(DATABASE_URI) c = connection.cursor() c.execute("DELETE FROM users") c.execute("DELETE FROM messages") connection.commit() connection.close() user = User("*****@*****.**", hash("abcde"),"John","Smith","Decidedly male","Kansas City","Murica") user2 = User("*****@*****.**", hash("abcdef"),"John","Wick","Surely male","Missouri","Murica") message = Message(user.email, user.email, "Hello World!") message2 = Message(user.email, user2.email, "Hej World!") addUser(user) addUser(user2) addMessage(message) addMessage(message2)
def settings_changed(old_settings, new_settings): """ What do we need to take care of when settings are reloaded? """ yield Message.nick(new_settings.nick)
def gg(surface): global RETRY_COUNTER draw_tint(RED, surface) gg1 = Message(surface, (480, 223), ' You Lost All ', font=pg.font.SysFont('comicsansms', 56, True), bg_color=BROWN) gg2 = Message(surface, (480, 300), ' Your Lives...', font=pg.font.SysFont('comicsansms', 56, True), bg_color=BROWN) gg1.blit() gg2.blit() RETRY_COUNTER += DT if RETRY_COUNTER >= 2: user.try_again = Message(surface, (565, 420), 'Try Again?', font=pg.font.SysFont('comicsansms', 58, True), bg_color=GREEN) user.try_again.blit()
def congrats(surface): global RETRY_COUNTER draw_tint(GREEN, surface) c1 = Message(surface, (480, 220), 'You Completed ', font=pg.font.SysFont('comicsansms', 60, True), bg_color=BROWN) c2 = Message(surface, (480, 300), 'All the Waves! ', font=pg.font.SysFont('comicsansms', 60, True), bg_color=BROWN) c1.blit() c2.blit() RETRY_COUNTER += DT if RETRY_COUNTER >= 2: user.try_again = Message(surface, (560, 420), 'Play Again?', font=pg.font.SysFont('comicsansms', 58, True), bg_color=GREEN) user.try_again.blit()
def send_signup(self, user): user.send( Message(content="Welcome to PayBot! What's your email?", quick_replies=[ QuickReply("", action=ExecuteFunction(self.save_email), content_type=ContentType.email) ])) user.set_state("WaitingEmail")
def help_stats(args): msg =\ """ Usage: `!stats <subcommand>` Subcommands: """ msg += commands_stats.help_commands(args) return Message(msg)
def send_home_options(self, user: User): user.send( Message(content="What do you want to do?", quick_replies=[ QuickReply("Pay", ExecuteFunction(self.prompt_pay)), QuickReply("Get balance", ExecuteFunction(self.send_balance)), QuickReply("Something else", SetState("Advanced")) ]))
def _command(message, arguments, state): match = re.fullmatch( r'^(.+) (in|on|at) (.+) with "(.+)"', arguments ) if match: if not state.subscriptions: state.subscriptions = Heap() who = match.group(1) if who == 'me': who = message.origin preposition = match.group(2) when = match.group(3) try: if preposition == 'in': when = when.split(':') when = datetime.now() + timedelta(hours=int(when[0]), minutes=int(when[1])) elif preposition == 'on': when = datetime.strptime('%Y-%m-%d', when) elif preposition == 'at': now = datetime.now() when = when.split(':') now.hour = int(when[0]) now.minute = int(when[0]) when = now except Exception as e: logger.exception(e) yield Message.privmsg(message.recipient, message.origin + ': Come again?') return what = match.group(4) state.subscriptions.push((when, who, preposition, what)) yield Message.privmsg(message.recipient, message.origin + ': You betcha')
def test_parse_message(): # (message "{channel}" "{text}") got = lisp.parse('(message "#chan" "toxt")') want = Message("#chan", "toxt") assert got == want, f"{got} == {want}" assert_throw(lambda: lisp.parse('(message "chan", "toxt")')) assert_throw(lambda: lisp.parse('(message "#oreqizer")')) assert_throw(lambda: lisp.parse('(message "#oreqizer" "oreqizer" asd)')) print("test_parse_message OK")
def setUp(self): self.m1 = Message(1, 'sdf', 'A project to cluster high-dimensional streams.', test_time - timedelta(seconds=60)) self.m1.vector = Vector({1: 2, 2: 4}) self.stream1 = Stream(1, self.m1) self.m2 = Message(2, 'sdf', 'A project to cluster high-dimensional streams.', test_time) self.m2.vector = Vector({2: 4}) self.stream2 = Stream(2, self.m2) self.m3 = Message(3, 'sdf', 'A project to cluster high-dimensional streams.', test_time + timedelta(seconds=60)) self.m3.vector = Vector({2: 4}) self.stream3 = Stream(3, self.m3) self.cluster1 = StreamCluster(self.stream1) self.cluster2 = StreamCluster(self.stream2) self.cluster3 = StreamCluster(self.stream3)
def run(message, state): if message.text.endswith('++'): thing = message.text.rstrip('+') if thing in state: modattr(state, thing, succ) else: setattr(state, thing, 1) response = 'The value of {} is now {}'.format(thing, getattr(state, thing)) yield Message.privmsg(message.recipient, response)
def execute(self, args): if len(args) == 0: return Message( content="Please provide a subcommand\nSubcommands:\n{}".format( self.help_commands(args))) subcommand = args[0] try: if len(args) > 1 and args[1] == 'help': help_data = self.map[subcommand].help if type(help_data) is str: return Message(help_data) elif help_data is None: return Message("Usage: `{name}`".format(name=subcommand)) else: return self.map[subcommand].help(args[1:]) else: return self.map[subcommand].func(args[1:]) except KeyError: return Message( content="{name} is not a valid subcommand".format(subcommand))
def cmd_about(args): msg = \ """ **Great Names Bot** v{ver} This bot assists in performing die rolls and success calculation in the Great Names system by Adam Franti. Bot maintainer: Brandon Nguyen """.format(ver=VERSION_STRING) return Message(msg)
def handle(message, settings, state): try: to, text = split_text(message.text) except TypeError: pass else: if to == state.nick and text == 'hello': yield Message.privmsg(message.recipient, 'hello to you too, {}!'.format(message.origin)) yield from run_plugins(message, settings.behaviour.command_prefix, settings.plugins, state.plugins)
def handler_advanced(self, req: MessagingEntry): req.sender.send( Message(content="Your options are:", quick_replies=[ QuickReply("Delete my account", action=ExecuteFunction( self.delete_account)), QuickReply("Send my location", payload="", content_type=ContentType.location), QuickReply("Go back", SetState("Home")) ]))
def test_addDocument(self): message1 = Message(3, 'sdf', 'A project to cluster high-dimensional streams.', test_time) message1.vector = Vector({3: 4}) stream1 = Stream(3, message1) message2 = Message(4, 'sdf', 'A project to cluster high-dimensional streams.', test_time) message2.vector = Vector({2: 4}) stream2 = Stream(4, message2) self.assertNotEqual(test_time, self.cluster1.lastStreamAddedTime) self.cluster1.addDocument(stream1) self.assertEqual(test_time, self.cluster1.lastStreamAddedTime) # Test if cluster id is set. self.assertEqual(self.cluster1.clusterId, stream1.clusterId) # Test that cluster mean is updated. self.assertEqual({1: 2 / 2., 2: 2., 3: 2.}, self.cluster1) # Test that cluster aggrefate is updated. self.assertEqual({1: 2, 2: 4, 3: 4}, self.cluster1.aggregateVector) # Test that document is added to cluster documents. self.assertEqual(stream1, self.cluster1.documentsInCluster[stream1.docId]) self.cluster1.addDocument(stream2) self.assertEqual(3, self.cluster1.vectorWeights) self.assertEqual({1: 2 / 3., 2: 8 / 3., 3: 4 / 3.}, self.cluster1) self.assertEqual({1: 2, 2: 8, 3: 4}, self.cluster1.aggregateVector)
def test_addDocument(self): message1 = Message(3, 'sdf', 'A project to cluster high-dimensional streams.', test_time) message1.vector=Vector({3:4}) stream1 = Stream(3, message1) message2 = Message(4, 'sdf', 'A project to cluster high-dimensional streams.', test_time) message2.vector=Vector({2:4}) stream2 = Stream(4, message2) self.assertNotEqual(test_time, self.cluster1.lastStreamAddedTime) self.cluster1.addDocument(stream1) self.assertEqual(test_time, self.cluster1.lastStreamAddedTime) # Test if cluster id is set. self.assertEqual(self.cluster1.clusterId, stream1.clusterId) # Test that cluster mean is updated. self.assertEqual({1:2/2.,2:2.,3:2.}, self.cluster1) # Test that cluster aggrefate is updated. self.assertEqual({1:2,2:4,3:4}, self.cluster1.aggregateVector) # Test that document is added to cluster documents. self.assertEqual(stream1, self.cluster1.documentsInCluster[stream1.docId]) self.cluster1.addDocument(stream2) self.assertEqual(3, self.cluster1.vectorWeights) self.assertEqual({1:2/3.,2:8/3.,3:4/3.}, self.cluster1) self.assertEqual({1:2,2:8,3:4}, self.cluster1.aggregateVector)
def cmd_stats_sim_success_histogram(args): if len(args) < 2: return Message("Expected at least 2 arguments, found {}".format( len(args))) msg_parse = "" try: sample_size = int(args[0]) except ValueError: msg_parse += "`{}` is not a valid integer for sample size".format( args[0]) if sample_size > MAXIMUM_SAMPLE_SIZE: return Message( "`{num}` exceeds the number of maximum sample size (`{max}`)". format(num=sample_size, max=MAXIMUM_SAMPLE_SIZE)) attr = 0 try: attr = int(args[1]) except ValueError: msg_parse += "`{}` is not a valid integer for sample size".format( args[1]) n = attr if len(args) > 2: try: if args[2][0] == '+': n = attr + int(args[2][1:]) else: n = int(args[2]) except ValueError: msg_parse += "`{}` is not a valid integer for sample size".format( args[1]) if n <= 0: return Message("Number of dice to be rolled must be greater than 0") if len(msg_parse) > 0: return Message(msg_parse) path = stats.success_histogram(sample_size, attr, n) return Message("Simulation results", file_path=path)
def setUp(self): self.tweet = {'user':{'screen_name': 'abc'}, 'id':10, 'text':'A project to cluster high-dimensional streams.', 'created_at': 'Tue Mar 01 05:59:59 +0000 2011'} m1 = Message(1, '', '', datetime.now()) m1.vector=Vector({'#tcot':2,'dsf':4}) self.cluster1 = StreamCluster(Stream(1, m1)) m2 = Message(2, '', '', datetime.now()) m2.vector=Vector({'#tcot':4}) self.cluster2 = StreamCluster(Stream(2, m2)) m3 = Message(3, '', '', datetime.now()) m3.vector=Vector(Vector({'#tcot':2})) m4 = Message(4, '', '', datetime.now()) m4.vector=Vector(Vector({'#tcot':2})) self.doc1 = Stream(1, m3) self.doc2 = Stream(2, m4) self.meanVectorForAllDocuments = Vector.getMeanVector([self.cluster1, self.cluster2, self.doc1, self.doc2]) self.cluster1.addDocument(self.doc1) self.cluster2.addDocument(self.doc2)
def run(message, state): if state.subscriptions: try: when, who, preposition, what = state.subscriptions.pop() except IndexError: logger.debug("Didn't remind anybody") return else: if when <= datetime.now(): yield Message.privmsg(message.recipient, '{}: Reminder: {}'.format(who, what)) else: state.subscriptions.push((when, who, preposition, what)) else: logger.debug("Didn't remind anybody")
def send_message(): data = request.args if not (('sender' in data) and ('receiver' in data) and ('text' in data)): return 'Message not correct. Try again.' now = datetime.now() dt_string = now.strftime("%d-%m-%Y %H:%M:%S") message = Message(data['sender'], data['receiver'], data['text'], dt_string) response = db_i.send_message(message) return jsonify(response)
def parse(command): tokens = command.split() cmd = tokens[0] args = tokens[1:] # run the command try: func = commands.map[cmd].func log('Running command \'{cmd}\' with args {args}'.format(cmd=cmd, args=args)) return func(args) except KeyError: # nothing to do if command not found pass except Exception as e: log('Ran into exception!') log(str(e)) return Message("I ran into an error on my end, sorry :cry:") return None
def run(message, state): last_message = state.last_message.get(message.origin) log.debug('Last message from %s: %s', message.origin, last_message) if last_message: subst_re = re.compile(r'^s/(.+)/(.+)/(\w)?$') match = subst_re.match(message.text) if match: del state['last_message'][message.origin] corrected = re.sub(match.group(1), match.group(2), last_message) log.debug('Corrected message: %s', corrected) yield Message.privmsg( message.recipient, 'Corrected message: <{}> {}'.format(message.origin, corrected) ) else: log.debug('New last message for %s: %s', message.origin, message.text) state.last_message[message.origin] = message.text
def parse_message(root): # (message "{channel}" "{text}") if len(root) != 3: raise Exception( f"invalid number of argumetns. want 3, got {len(root)}") channel = root[1] if type(channel) is not String: raise Exception( f"invalid argument #1. want {String}, got {type(channel)}") channel_value = repr(channel) if not is_channel(channel_value): raise Exception( f"invalid channel format. want #<alphanum>, got {channel_value}") text = root[2] if type(text) is not String: raise Exception( f"invalid argument #2. want {String}, got {type(text)}") return Message(channel_value, text.value)
def new_message(data): u_name = data["nickname"] u_channel = int(data["channel"]) u_name = u_name.encode("raw_unicode_escape").decode("utf-8") user = User(u_name, u_channel) print(u_name, u_channel) if user in users: join_room(u_channel) text = data["message"] text = text.encode("raw_unicode_escape").decode("utf-8") msg = Message(user, text) channels[u_channel].add_message(msg) print("收到消息:", text, "from", u_name) emit("write_message", { "nickname": u_name, "message": text }, room=u_channel) nickname_array = json.dumps(channels[session["channel"]].users) emit("current_client_list", {"users": nickname_array}, room=session["channel"]) else: print('未登录!')
def cmd_roll(args): if len(args) == 0: return "Please provide an attribute score\n" + help_roll try: attr = int(args[0]) args = args[1:] except ValueError: return "`{num}` is not a valid integer".format(num=args[0]) bonus = 0 if len(args) > 0: try: bonus = int(args[0]) args = args[1:] except ValueError: return "`{num}` is not a valid integer".format(num=args[0]) n = attr if len(args) > 0: try: if args[0][0] == '+': # relative add n = attr + int(args[0][1:]) else: # absolute count n = int(args[0]) args = args[1:] except ValueError: return "`{num}` is not a valid integer".format(num=args[0]) if n <= 0: return Message("Number of dice to be rolled must be greater than 0") if n > MAXIMUM_DICE: return "`{num}` exceeds the number of dice that can be rolled ({max_dice})".format( num=n, max_dice=MAXIMUM_DICE) result = roller.roll(attr, bonus, n) # print rolls msg = "" for roll in result.rolls[0:-1]: if roll <= attr: fmt = '**' elif roll == 10: fmt = '~~' else: fmt = '' msg += "{fmt}{val}{fmt}, ".format(fmt=fmt, val=str(roll)) if len(result.rolls) > 0: roll = result.rolls[-1] if roll <= attr: fmt = '**' elif roll == 10: fmt = '~~' else: fmt = '' msg += "{fmt}{val}{fmt}".format(fmt=fmt, val=str(roll)) # print explanation msg +=\ """ Rolled {n} {n_noun} with an attribute score of {attr} and {bonus} bonus successes. {successes} rolled {rs_noun}, {bonus} bonus {bs_noun}, and {negations} {neg_noun} **Total successes: {total} {emoji}** """.format(n=n, n_noun=('die' if n==1 else 'dice'), attr=attr, bonus=result.bonus, successes=result.successes, negations=result.negations, total=result.total, rs_noun='success' if result.successes == 1 else 'successes', bs_noun='success' if result.bonus == 1 else 'successes', neg_noun='negation' if result.negations == 1 else 'negations', emoji=emoji_scale_absolute(result.total)) return Message(content=msg)
def cmd_red(args): black = np.random.randint(1, high=11) red = np.random.randint(1, high=11) msg = "Black: {black}\nRed: {red}".format(black=black, red=red) return Message(msg)
def run(message, arguments, state): if 'called' in state: yield Message.privmsg(message.recipient, 'You have already tested') else: state.called = True yield Message.privmsg(message.recipient, 'Testing first time!')