Esempio n. 1
0
def do_show_mind(player, bot, gamedata, pdb):
    with pdb.connect() as conn:
        player.update_lore(gamedata)
        update_player(player, conn)
        text = u"{}\nЗнание Мира: {}\nСырое ЗМ: {}".format(
            player.get_name(), player._lore, player._raw_lore)
        if player._raw_lore > 0:
            text += u", время обработки: {}\n".format(
                format_time(player._raw_lore * 1. / player.get_cpu() * 60))
        else:
            text += u"\n"
        text += u"""Использование памяти: {} / {}\nЗагрузка CPU: {} / {}\n""".format(
            player.get_used_ram(gamedata), player.get_ram(),
            player.get_used_cpu(gamedata), player.get_cpu())
        text += u"Запущенных программ: {}\n".format(len(player._running_soft))
        text += u"Скомпилированных программ: {}\n".format(
            len(player._installed_soft))
        text += u"Новых программ: {} /software".format(len(gamedata._programs))
        if player._compiling_soft != []:
            program = gamedata._programs[player._compiling_soft[0]]
            cpu, start_time = player._compiling_soft[1:3]
            ts = time.time()
            progress = (ts - start_time) / (program._compile_time / cpu *
                                            TICK_DURATION)
            progress = int(progress * 100)
            text += u"\nКомпиляция {} выполнена на {}%".format(
                program._name, progress)
        send_message(player, conn, bot, text)
Esempio n. 2
0
File: app.py Progetto: hmac/msg
def messages():
    (success, msg) = authenticate_message(request.form)
    if success:
        db.send_message(msg)
        return "Success"
    else:
        abort(401)
Esempio n. 3
0
 def post(self):
     room_id = self.get_argument('room', default='')
     if room_id not in db.rooms:
         self.write({
             'result': False,
             'msg': 'Invalid room id',
             })
         return
     if 'file' not in self.request.files:
         self.write({
             'result': False,
             'msg': 'File not provided',
             })
         return
     upload_file = self.request.files['file'][0]
     hsh = db.add_file(upload_file['filename'], upload_file['body'])
     msg = '<a href="%s/getfile?file=%s">%s</a>' % (
             'http://index.lv6.tw:8888',
             hsh,
             upload_file['filename'],
         )
     db.send_message(room_id, self.get_user(), msg)
     self.write({
         'result': True,
         'msg': 'Send file success',
         })
Esempio n. 4
0
def resolve_event(player, bot, gamedata, pdb, event_id, lore_gained):
    if event_id not in gamedata._texts:
        logging.warning(
            u"no data for event: {}".format(event_id).encode("utf8"))
        with pdb.connect() as conn:
            send_message(player, conn, bot,
                         u"no data for event: {}".format(event_id),
                         get_show_venues_keyboard(player, gamedata))
        return

    text_id = random.choice(gamedata._texts[event_id].keys())
    descr, options = gamedata._texts[event_id][text_id]
    if len(options) == 1:
        do_get_outcome(player, bot, gamedata, pdb, event_id, text_id,
                       options.keys()[0], True, lore_gained)
        return

    message = descr
    keyboard = list()
    for option_text, outcomes in options.iteritems():
        action = ("GETOUTCOME", event_id, text_id, option_text, False,
                  lore_gained)
        keyboard.append([(action, option_text)])

    with pdb.connect() as conn:
        send_message(player, conn, bot, message, keyboard)
Esempio n. 5
0
 def post(self):
     room_id = self.get_argument('room', default='')
     if room_id not in db.rooms:
         self.write({
             'result': False,
             'msg': 'Invalid room id',
         })
         return
     if 'file' not in self.request.files:
         self.write({
             'result': False,
             'msg': 'File not provided',
         })
         return
     upload_file = self.request.files['file'][0]
     hsh = db.add_file(upload_file['filename'], upload_file['body'])
     msg = '<a href="%s/getfile?file=%s">%s</a>' % (
         'http://index.lv6.tw:8888',
         hsh,
         upload_file['filename'],
     )
     db.send_message(room_id, self.get_user(), msg)
     self.write({
         'result': True,
         'msg': 'Send file success',
     })
Esempio n. 6
0
def do_venue_action(player, bot, gamedata, pdb, venue_option, venue_message):
    with pdb.connect() as conn:
        send_message(player, conn, bot, venue_message, [])

    loc = gamedata._map[player._location_id]
    outcomes = loc._venue_option2events[venue_option]
    event_id = choose_outcome(outcomes)
    resolve_event(player, bot, gamedata, pdb, event_id, 0)
Esempio n. 7
0
def do_show_venues(player, bot, gamedata, pdb):
    loc = gamedata._map[player._location_id]
    text = player._location_id + u" " + loc._descr
    text = text + u"\nИсследовано {}%".format(
        player._research_percent[player._location_id])
    keyboard = get_show_venues_keyboard(player, gamedata)
    with pdb.connect() as conn:
        send_message(player, conn, bot, text, keyboard)
Esempio n. 8
0
 def __call__(self, bot, update):
     user_id = update.message.from_user.id
     player = fetch_player(user_id, self._players)
     if player is None:
         return
     player = Player(user_id, update.message.chat_id)
     text = "User {} is welcome in chat {}".format(user_id, update.message.chat_id)
     keyboard = [[("CONTINUE", u"Продолжить")]]
     with self._players.connect() as conn:
         update_player(player, conn)
         send_message(player, conn, bot, text, keyboard)
     logging.info("NEW_USER\t{}".format(user_id))
Esempio n. 9
0
def do_show_venue(player, bot, gamedata, pdb, venue_id):
    loc = gamedata._map[player._location_id]
    keyboard = [[SUPERMIND, LAB, AVATAR, (("SHOWMAP", ), u"🔄")]]
    text = ""
    for vid, venue_descr, _ in loc._venues:
        if vid == venue_id:
            text = venue_descr
            for option in gamedata._venues[venue_id]._options:
                keyboard.append([(("VENUEACTION", option[0], option[1]),
                                  option[0])])
    keyboard.append([(("SHOWVENUES", ), u"Назад")])
    with pdb.connect() as conn:
        send_message(player, conn, bot, text, keyboard)
Esempio n. 10
0
def do_show_map(player, bot, gamedata, pdb):
    loc = gamedata._map[player._location_id]
    text = player._location_id + u" " + loc._descr
    text = text + u"\nИсследовано {}%".format(
        player._research_percent[player._location_id])
    adj = loc._adjacent

    keyboard = [[SUPERMIND] + get_map_keyboard(["NW", "N", "NE"], adj),
                [
                    LAB,
                    get_map_keyboard_item("W", adj), (("SHOWVENUES", ), u"🔄"),
                    get_map_keyboard_item("E", adj)
                ], [AVATAR] + get_map_keyboard(["SW", "S", "SE"], adj)]
    with pdb.connect() as conn:
        send_message(player, conn, bot, text, keyboard)
Esempio n. 11
0
def do_compile_program(player, bot, gamedata, pdb, program_id):
    with pdb.connect() as conn:
        player.update_lore(gamedata)
        update_player(player, conn)
        if player._compiling_soft != []:
            bot.send_message(player._chat_id,
                             u"Другая программа ещё компилируется")
        else:
            if player.compile_program(program_id, gamedata):
                update_player(player, conn)
                send_message(
                    player, conn, bot, u"Компилирую {}".format(
                        gamedata._programs[program_id]._name))
            else:
                bot.send_message(player._chat_id,
                                 u"Недостаточно ЦП для начала компиляции")
Esempio n. 12
0
def do_get_outcome(player, bot, gamedata, pdb, event_id, text_id, option_text,
                   show_descr, lore_gained):
    descr, options = gamedata._texts[event_id][text_id]
    outcome = choose_outcome(options[option_text])
    message_parts = list()
    if show_descr:
        message_parts.append(descr)
    if outcome._message:
        message_parts.append(outcome._message)
    message = u" ".join(message_parts) + u"\n"
    outcome_id = outcome._outcome_id
    if outcome_id is not None:
        if outcome_id.startswith("i_"):
            if outcome_id not in gamedata._items:
                bot.send_message(player._chat_id,
                                 u"Unknown item: {}".format(outcome_id))
            else:
                item = gamedata._items[outcome_id]
                message += u"...\nНаходка! {} ({}) /view_{}".format(
                    item._name, outcome._cnt, outcome_id)
                backpack = player._avatar._backpack
                free_weight = backpack._max_weight - backpack.get_weight(
                    gamedata)
                taken_count = int(min(free_weight / item._weight,
                                      outcome._cnt))
                if taken_count > 0:
                    backpack.insert_item(outcome_id, taken_count)
                    message += u"\n{} ({}) помещён(-а) в рюкзак".format(
                        item._name, taken_count)
                if taken_count < outcome._cnt:
                    message += u"\n{} {} не поместился(-ась) в рюкзак".format(
                        outcome._cnt - taken_count, item._name)
                lore_for_new_item = player.get_lore_for_new_entity(
                    outcome_id, gamedata)
                if lore_for_new_item > 0:
                    message += u"\nПолучено {} ЗМ за находку".format(
                        lore_for_new_item)
        else:
            message += outcome_id
    if lore_gained > 0:
        message += u"\nПолучено {} ЗМ за исследование".format(lore_gained)
    keyboard = get_show_venues_keyboard(player, gamedata)
    with pdb.connect() as conn:
        update_player(player, conn)
        send_message(player, conn, bot, message, keyboard)
Esempio n. 13
0
 def post(self):
     room_id = self.get_argument('room', default='')
     msg = self.get_argument('msg', default='')
     if room_id not in db.rooms:
         self.write({
             'result': False,
             'msg': 'Invalid room id',
             })
         return
     if not msg:
         self.write({
             'result': False,
             'msg': 'Empty message',
             })
         return
     db.send_message(room_id, self.get_user(), msg)
     self.write({
         'result': True,
         'msg': 'Send message success',
         })
Esempio n. 14
0
 def post(self):
     room_id = self.get_argument('room', default='')
     msg = self.get_argument('msg', default='')
     if room_id not in db.rooms:
         self.write({
             'result': False,
             'msg': 'Invalid room id',
         })
         return
     if not msg:
         self.write({
             'result': False,
             'msg': 'Empty message',
         })
         return
     db.send_message(room_id, self.get_user(), msg)
     self.write({
         'result': True,
         'msg': 'Send message success',
     })
Esempio n. 15
0
    def run(self, args, conn):
        if args[0] is None:
            # display all messages
            msgs = yield db.get_messages_all(conn.user.id_)
            if not msgs:
                conn.write(_('You have no messages.\n'))
            else:
                conn.write(_('Messages:\n'))
                for msg in msgs:
                    conn.write(_('%d. ') % (msg['num']))
                    self._write_msg(msg, conn.user)
                yield db.set_messages_read_all(conn.user.id_)
        elif args[0] == 'u':
            if args[1] is not None:
                raise BadCommandError
            msgs = yield db.get_messages_unread(conn.user.id_)
            if not msgs:
                conn.write(_('You have no unread messages.\n'))
            else:
                conn.write(_('Unread messages:\n'))
                for msg in msgs:
                    conn.write(_('%d. ') % (msg['num']))
                    self._write_msg(msg, conn.user)
                yield db.set_messages_read_all(conn.user.id_)
        elif args[1] is None:
            # display some messages
            try:
                i = int(args[0])
                msgs = yield db.get_messages_range(conn.user.id_, i, i)
                if not msgs:
                    conn.write(_('There is no such message.\n'))
                    return
            except ValueError:
                m = self.range_re.match(args[0])
                if m:
                    (start, end) = (int(m.group(1)), int(m.group(2)))
                    # sanity checks
                    if start < 1 or start > end or end > 9999:
                        conn.write(_('Invalid message range.\n'))
                        return
                    msgs = yield db.get_messages_range(conn.user.id_, start,
                                                       end)
                else:
                    u2 = yield find_user.by_prefix_for_user(args[0], conn)
                    if not u2:
                        return
                    if u2.is_guest:
                        conn.write(
                            _('Only registered players can have messages.\n'))
                        return
                    msgs = yield db.get_messages_from_to(conn.user.id_, u2.id_)
                    if not msgs:
                        conn.write(
                            _('You have no messages to %s.\n') % u2.name)
                    else:
                        conn.write(_('Messages to %s:\n') % u2.name)
                        for msg in msgs:
                            self._write_msg(msg, conn.user)
                    conn.write('\n')

                    msgs = yield db.get_messages_from_to(u2.id_, conn.user.id_)
                    if not msgs:
                        conn.write(
                            _('You have no messages from %s.\n') % u2.name)
                        return
                    else:
                        conn.write(_('Messages from %s:\n') % u2.name)

            for msg in msgs:
                conn.write(_('%d. ') % (msg['num']))
                self._write_msg(msg, conn.user)
                if msg['unread']:
                    yield db.set_message_read(msg['message_id'])
        else:
            """ Send a message.  Note that the message may be localized
            differently for the sender and receiver. """
            to = yield find_user.by_prefix_for_user(args[0], conn)
            if to:
                if conn.user.is_muted:
                    conn.write(_('You are muted.\n'))
                    return
                if to.is_guest:
                    conn.write(
                        _('Only registered players can have messages.\n'))
                    return
                tocensor = yield to.get_censor()
                if conn.user.name in tocensor and not conn.user.is_admin():
                    conn.write(_('%s is censoring you.\n') % to.name)
                    return
                message_id = yield db.send_message(conn.user.id_, to.id_,
                                                   args[1])
                msg = yield db.get_message(message_id)
                msg_str_to = self._format_msg(msg,
                                              to)  # localized for receiver

                if to.vars_['mailmess']:
                    email.send_mail(conn.user, to, msg_str_to)
                    conn.write(
                        _('The following message was sent and emailed to %s:\n'
                          ) % to.name)
                else:
                    conn.write(
                        _('The following message was sent to %s:\n') % to.name)
                self._write_msg(msg, conn.user)

                if to.is_online:
                    to.write_('The following message was received:\n')
                    to.write(msg_str_to)
Esempio n. 16
0
def handle_send_message_event(data):
    if allowed():
        data['created_at'] = datetime.now().strftime("%d %b, %H:%M")
        send_message(data['conv_id'], session['profile']['user_id'],
                     data['message'])
        socketio.emit('receive_message', data)
Esempio n. 17
0
def test_send_message():
    db.send_message(100, 101, "Test Message.")

    msg = db.get_messages(100, 1)[0]
    assert msg[0] == 101 and msg[2] == "Test Message."