コード例 #1
0
    def __init__(self):
        # prompt for a username
        print(
            """\nDevice Connector needs your username to connect to any device
        This will only be prompt once and will be reuse for each device it needs to connect"""
        )
        username = input('Enter username (default = %s) :' % getpass.getuser())

        # setup the user to be use for every device connection during script run
        self._user = User(username=username) if username != '' else User()
        self._user.ask_password()
コード例 #2
0
    def apply(self, game):
        Command.apply(self, game)
        new_user = User(USERS.PLAYER, self.client_id)

        if game.is_server:
            game.add_user(new_user)
            self.player_dict = new_user.to_json()
            self.initial_state = game.serialize()
        else:
            for (key, val) in self.player_dict.items():
                setattr(new_user, key, val)
            game.add_user(new_user, new_user.pos[0], new_user.pos[1])

        gLogger.info("Command {} successfully executed".format(self.__str__()))
        return True
コード例 #3
0
    def getUsers(self, prj_id=None):
        users = []

        if prj_id:
            try:
                data = {"scope.project.id": prj_id}
                response = self.getResource("role_assignments",
                                            "GET",
                                            data=data)
                user_list = {}

                for role in response["role_assignments"]:
                    user_id = role["user"]["id"]

                    if user_id in user_list:
                        continue

                    user = self.getUser(user_id)
                    user.setProjectId(prj_id)

                    user_list[user_id] = user

                users = user_list.values()
            except requests.exceptions.HTTPError as ex:
                response = ex.response.json()
                message = response["error"]["message"]
                raise SynergyError("error on retrieving the project's users "
                                   "(id=%r): %s" % (prj_id, message))
        else:
            try:
                response = self.getResource("/users", "GET")

                for info in response["users"]:
                    user = User()
                    user.setId(info["id"])
                    user.setName(info["name"])
                    user.setProjectId(info["tenantId"])
                    user.setEnabled(info["enabled"])

                    users.append(user)
            except requests.exceptions.HTTPError as ex:
                response = ex.response.json()
                message = response["error"]["message"]
                raise SynergyError("error on retrieving the users list: %s" %
                                   message)

        return users
コード例 #4
0
ファイル: game.py プロジェクト: mrbads/das
 def from_serialized_map(self, _map):
     for i in range(len(_map)):
         for j in range(len(_map[0])):
             if _map[i][j] != 0:
                 user_dict = _map[i][j]
                 user_obj = User(user_dict['type'])
                 for (key, val) in user_dict.items():
                     setattr(user_obj, key, val)
                 self.map[i][j] = user_obj
                 self.users.append(user_obj)
コード例 #5
0
 def init_users(self):
     users = []
     for i in range(self.nb_personne):
         point = self.get_valid_position()
         users.append(
             User(point.X, point.Y,
                  User.POSSIBLE_COLOR[random.randint(0, 3)]))
         if self.draw_is_enable:
             self.drawer.add_user(Point(users[i].X, users[i].Y),
                                  users[i].color)
     return users
コード例 #6
0
    def getUsers(self, prj_id=None):
        users = []

        if prj_id:
            try:
                data = {"scope.project.id": prj_id}
                response = self.getResource("role_assignments",
                                            "GET", data=data)
                user_list = {}

                for role in response["role_assignments"]:
                    user_id = role["user"]["id"]

                    if user_id in user_list:
                        continue

                    user = self.getUser(user_id)
                    user.setProjectId(prj_id)

                    user_list[user_id] = user

                users = user_list.values()
            except requests.exceptions.HTTPError as ex:
                response = ex.response.json()
                message = response["error"]["message"]
                raise SynergyError("error on retrieving the project's users "
                                   "(id=%r): %s" % (prj_id, message))
        else:
            try:
                response = self.getResource("/users", "GET")

                for info in response["users"]:
                    user = User()
                    user.setId(info["id"])
                    user.setName(info["name"])
                    user.setProjectId(info["tenantId"])
                    user.setEnabled(info["enabled"])

                    users.append(user)
            except requests.exceptions.HTTPError as ex:
                response = ex.response.json()
                message = response["error"]["message"]
                raise SynergyError("error on retrieving the users list: %s"
                                   % message)

        return users
コード例 #7
0
class DeviceNetworkConnector:
    def __init__(self):
        # prompt for a username
        print(
            """\nDevice Connector needs your username to connect to any device
        This will only be prompt once and will be reuse for each device it needs to connect"""
        )
        username = input('Enter username (default = %s) :' % getpass.getuser())

        # setup the user to be use for every device connection during script run
        self._user = User(username=username) if username != '' else User()
        self._user.ask_password()

    def _connect(self, device: Device) -> DeviceConnector:
        return DeviceConnector(device, self._user)

    def run_command_against_device(self, device: Device, cmd: str) -> str:
        conn = self._connect(device)
        command = DeviceCommand(conn, cmd)

        return command.run_command()
 def __init__(self, bot):
     # self.group = group
     self.api_key = api_key
     self.log = Logger()
     self.ycy = YcyReplier()
     self.tuling = Tuling(api_key=TULING_KEY)
     self.user = User()
     self.group = Group()
     self.rsp_game_player_map = {}
     self.bot = bot
     self.draw_lots_game = DrawLots()
     self.user_lots_map = {}
     self.user_lots_read_map = {}
     self.answer = ""
     self.red_bag_num = 0
     '''
     开启每日定时器,每日零时清空抽签内容
     '''
     self.scheduler = BackgroundScheduler()
     self.scheduler.add_job(self.init_lots_map, 'cron', hour='0')
     self.scheduler.start()
コード例 #9
0
    def build_device(self):
        # prompt for a username
        print(
            '\nYou username is needed to collect any device configuration if need be'
        )
        username = input('Enter username (default = %s) :' % getpass.getuser())

        # setup the user to be use for every device connection during script run
        user = User(username=username) if username != '' else User()
        user.ask_password()

        # initiate a connection with the device and retrieve it running configuration
        device_connection = DeviceConnector(ip=self._device_mgmnt_ip,
                                            os=self._device_os,
                                            user=user)
        command = DeviceCommand(device_connection, 'show run')
        device_config = command.run_command()

        self._device = Device(hostname='builded_device',
                              ip=self._device_mgmnt_ip,
                              os=self._device_os,
                              config=device_config)
コード例 #10
0
ファイル: app_view.py プロジェクト: waylonwang/biz-server
    def register_view(self):
        from common.login import RegistrationForm
        form = RegistrationForm(request.form)
        if helpers.validate_form_on_submit(form):
            from common.user import User
            user = User()

            form.populate_obj(user)
            # we hash the users password to avoid saving it as plaintext in the db,
            # remove to use plain text:
            user.password = generate_password_hash(form.password.data)

            db_control.get_db().session.add(user)
            db_control.get_db().session.commit()

            login.login_user(user)
            return redirect(url_for('.index'))
        link = '<p>Already have an account? <a href="' + url_for(
            '.login_view') + '">Click here to log in.</a></p>'
        self._template_args['form'] = form
        self._template_args['link'] = link
        return super(CVAdminIndexView, self).index()
コード例 #11
0
ファイル: engine.py プロジェクト: mrbads/das
    def __init__(self,
                 request_queue,
                 response_queue,
                 meta_request_queue,
                 meta_response_queue,
                 initial_users,
                 vis=False):
        multiprocessing.Process.__init__(self)
        self.request_queue = request_queue
        self.response_queue = response_queue
        self.meta_request_queue = meta_request_queue
        self.meta_response_queue = meta_response_queue
        self.game = game.Game()
        self.game.is_server = True
        self.vis = vis

        for user in initial_users:
            self.game.add_user(User(user['type']), user['r'], user['c'])

        self.T = 500

        logger.info("Engine successfully started.")
コード例 #12
0
    def getUser(self, id):
        try:
            response = self.getResource("users/%s" % id, "GET")
        except requests.exceptions.HTTPError as ex:
            response = ex.response.json()
            raise Exception("error on retrieving the user info (id=%r): %s" %
                            (id, response["error"]["message"]))

        user = None

        if response:
            info = response["user"]

            user = User()
            user.setId(info["id"])
            user.setName(info["name"])
            user.setEnabled(info["enabled"])

            if "default_project_id" in info:
                user.setProjectId(info["default_project_id"])
            elif "tenantId" in info:
                user.setProjectId(info["tenantId"])

        return user
コード例 #13
0
 def __init__(self, user, wss_addr):
     self.user = User()
     self.ws_addr = wss_addr
     self._socket_client = WebSocketClient(wss_addr)
     stomp.Connection11
コード例 #14
0
    file_name = 'gdn_circuit_map_%s.json' % timestamp_to_string()
    with open('../_file_output/%s' % file_name, 'w') as file:
        file.write(json.dumps(results))

    print('\nMap completed\nSee file \'%s\'' % file_name)


def tester():
    update_map_with_manual_data()


if __name__ == "__main__":
    import doctest

    # Global Vars
    device_list, devices, results = gdn_devices.device_list, create_device_config_model(
    ), {}

    # prompt for a username
    print(
        '\nYou username is needed to collect any device configuration if need be'
    )
    username = input('Enter username (default = %s) :' % getpass.getuser())

    # setup the user to be use for every device connection during script run
    user = User(username=username) if username != '' else User()
    user.ask_password()

    doctest.testmod(main())
コード例 #15
0
ファイル: bot.py プロジェクト: waylonwang/biz-server
 def user_query_factory():
     return [r.username for r in User.findall()]
コード例 #16
0
ファイル: login.py プロジェクト: waylonwang/biz-server
 def load_user(username):
     # Return an instance of the User model
     return User.find_by_name(username=username)
コード例 #17
0
ファイル: msg_lib.py プロジェクト: zhangenter/bf_chat
    return parse_name_msg(bytes)

def is_msg_valid(read_bytes):
    if len(read_bytes) < 6:
        return False
    n = unpack('I', read_bytes[0:4])[0]
    if n != len(read_bytes):
        return False

    return True

def parse_msg(read_bytes):
    if not is_msg_valid(read_bytes):
        return None

    msg_id = unpack('H', read_bytes[4:6])[0]

    if msg_id in MsgParse().parser_dic:
        data = MsgParse().parser_dic[msg_id](read_bytes)
        return {'msg_id':msg_id,'data':data}
    else:
        return {'msg_id':msg_id}

if __name__ == '__main__':
    from common.user import User
    user = User()
    user.name = 'test'
    user.nick_name = '测试'
    user.depart_id = 1
    msg = build_login_msg(user)
    print(parse_msg(msg))
コード例 #18
0
class Replier(object):
    """消息回复"""

    level_map = {
        1: "隔壁村的幼稚鬼",
        2: "村子里的弟中弟",
        3: "村民中的初学者",
        4: "村子里的高中生",
        5: "合格的成年村民",
    }

    q_a_list = {
        "生日": ["杨超越的生日是什么时候 a)7月31 b)7月29 c)7月28", "a"],
        "演艺": ["杨超越获得了哪年的演艺人物奖?a)2017 b)2018 c)2019", "b"],
        "主食": ["杨超越最新欢的主食是?a)土豆 b)米饭 c)燕麦片", "b"]
    }

    jokes = [
        '''美国外交代表团到苏联访问,苏修接待官员陪他们参观“建设的伟大成就”,并且得意的说:“到了下一个五年计划,每个苏联家庭都可以拥有一架私人飞机!”\n美国人惊讶的问:“ 他们要飞机干什么呢?”\n苏修官员说:“当然有用啊……譬如你在莫斯科听说列宁格勒开始供应面包了,你可以马上开飞机赶去排队啊。''',
        '''斯大林、赫鲁晓夫和勃列日涅夫乘坐火车出门。开着开着,火车突然停了。\n斯大林把头伸出车窗外,怒吼道:“枪毙火车司机!”可是车还是没有动。\n接着赫鲁晓夫说:“给火车司机恢复名誉!”车仍然没有动。\n勃列日涅夫说:“同志们,不如拉上窗帘,坐在座位上自己摇动身体,做出列车还在前进的样子……”''',
        '''美术馆里有一幅描写亚当和夏娃的画。\n一个英国人看了,说:“他们一定是英国人,男士有好吃的东西就和女士分享。\n一个法国人看了,说:“他们一定是法国人,情侣裸体散步。\n一个苏联人看了,说:“他们一定是苏联人,他们没有衣服,吃得很少,却还以为自己在天堂!''',
        '''杨村制度的优越性在哪里?\n成功克服了其他制度里不存在的问题。''',
        '''黑子:哈哈哈,杨超越这么重要的场合居然口误?\n路人:什么场合?\n黑子:不知道?\n路人:那你看了这么久的视频在看什么?\n黑子:在看杨超越!'''
    ]

    def __init__(self, bot):
        # self.group = group
        self.api_key = api_key
        self.log = Logger()
        self.ycy = YcyReplier()
        self.tuling = Tuling(api_key=TULING_KEY)
        self.user = User()
        self.group = Group()
        self.rsp_game_player_map = {}
        self.bot = bot
        self.draw_lots_game = DrawLots()
        self.real_estate = RealEstate()
        self.user_lots_map = {}
        self.user_lots_read_map = {}
        self.answer = ""
        self.red_bag_num = 0
        '''
        开启每日定时器,每日零时清空抽签内容
        '''
        self.scheduler = BackgroundScheduler()
        self.scheduler.add_job(self.init_lots_map, 'cron', hour='0')
        self.scheduler.start()

    def init_lots_map(self):
        """
        清空抽签内容,可以重新开始抽签
        """
        self.user_lots_map = {}
        self.user_lots_read_map = {}
        self.log.info("=== Init Lots ===")

    def random_img(self, msg) -> tuple:
        """
        随机获取图片
        :return:
        """
        print("===天降超越===")
        print(msg.text)

        if "天降超越" in msg.text or "天将超越" in msg.text:  # todo 待增加
            list_dir = os.listdir(os.path.join('resources', 'pics'))
            path = choice(list_dir)
            self.log.info('choose:-->{}'.format(path))
            self.log.debug(os.path.join('resources', 'pics', path))
            return 'img', os.path.join('resources', 'pics', path), ''
        return empty_result

    def robot_init(self, msg) -> tuple:
        """
        机器人初始化
        :param msg:
        :return:
        """
        real_msg = msg.text.split()
        if msg.member.puid == self.group.admin_puid and len(
                real_msg) != 1:  # 如果是管理员
            if real_msg[len(real_msg) - 1] == "初始化":
                self.log.info(msg.sender)
                # self.group.update_group(msg.sender, self.api_key)
                self.user.update_users(msg.sender, self.api_key)
                self.log.info("初始化完成!")
                return 'text', "初始化完成!", ''
            elif real_msg[1] == "口令红包":
                self.log.info("设置口令红包!")
                print("===口令红包信息===")
                print(real_msg[2])
                print(real_msg[3])
                try:
                    self.red_bag_num = int(real_msg[2])
                except:
                    self.red_bag_num = 0
                if real_msg[3] in self.q_a_list:
                    item = self.q_a_list[real_msg[3]]
                    self.answer = item[1]
                    return 'text', item[0], ''
                else:
                    self.answer = real_msg[3]
                    return 'text', "口令红包设置完成!", ''
            else:
                return empty_result
        return empty_result

    def update_user_info(self, msg):
        self.log.info("更新用户信息中……")
        self.user.update_users(msg.sender, self.api_key)
        self.log.info("用户信息更新完毕……")

    def chaoyue_ana(self, msg) -> tuple:
        """
        超越语录
        :return:
        """
        real_msg = msg.text.split()
        respond_msg = self.ycy.reply_text(real_msg[len(real_msg) -
                                                   1])  # 超越语录无需要@
        if respond_msg:
            return 'text', '@' + msg.member.name + ' ' + respond_msg, ''
        return empty_result

    def set_group(self, puid):
        self.group.set_group(puid)

    def handle_leave_message(self, msg) -> tuple:
        """
        处理留言
        :param msg:
        :return:
        """
        if "村头留言板" in msg.text:
            return "text", "@我并回复:「留言:你想说的话」,则可在村头留言板上留下你的留言内容哦", ""
        is_leave_message = re.search(r'(留言:|留言:)(.*)', msg.text)
        if is_leave_message:
            content = is_leave_message.group(2).strip()  # 获取第二组内容并去除前后空格
            self.log.info('留言内容:{}'.format(content))
            status = create_messages(
                name=msg.member.name,
                content=content,
                fans_id=msg.member.puid,
            )
            if status == "ok":
                return 'text', '@' + msg.member.name + ' ' + "留言成功!点击 {} 可查看你的留言".format(
                    'http://ahasmarter.com/', ), ''
            else:
                return 'text', '@' + msg.member.name + ' ' + "留言失败!稍后再尝试吧", ''
        return empty_result

    def get_group_introduction(self, msg) -> tuple:
        """
        获取群介绍
        :param msg:
        :return:
        """
        real_msg = msg.text.split()
        if real_msg[len(real_msg) - 1] == "群信息" or real_msg[len(real_msg) -
                                                            1] == "群简介":
            return 'text', self.group.intro, ''
        return empty_result

    def finger_guessing_game(self, msg) -> tuple:
        """
        猜拳游戏
        :param msg:
        :return:
        """
        group_id = msg.member.group.puid  # 群组唯一id
        name = msg.member.name  # 玩家名
        user_id = msg.member.puid  # 玩家id
        real_msg = msg.text.split()
        if real_msg[len(real_msg) - 1] == "石头剪刀布" or real_msg[len(real_msg) - 1] == "剪刀石头布" \
                or real_msg[len(real_msg) - 1] == "猜拳":
            self.log.debug('---init猜拳----')
            # { 群组id : {玩家id: [游戏对象 , 开始游戏的时间, 玩家名]}}
            self.rsp_game_player_map.update(
                {
                    group_id: [user_id,
                               RspGame(1),
                               now_to_datetime4(), name],
                }, )
            self.rsp_game_player_map[group_id][1].start(name)  # 开始游戏
            return 'text', '@' + msg.member.name + \
                   " 石头剪刀布开始,你先出吧,赢了我有奖励哦(1局定胜)", ''
        return empty_result

    def play_game(self, msg) -> tuple:
        """
        游戏
        :param msg:
        :return:
        """
        if "超越猜拳" in msg.text:
            return "text", "@我并回复你的出招(比如「剪刀」)就能跟我玩猜拳游戏,赢了我会奖励3积分,输了扣除3积分,如果积分不够则不会进行奖惩", ""
        real_msg = msg.text.split()
        if "石头" in real_msg[len(real_msg) - 1]  or  "剪刀" in real_msg[len(real_msg) - 1]  \
                or "布" in real_msg[len(real_msg) - 1]:
            game = RspGame(1)
            game.start(msg.member.name)
            cancel, result, pic = game.play(msg)
            return 'both', pic, result
        else:
            return empty_result
        """
        group_id = msg.member.group.puid
        user_id = msg.member.puid
        player_map = self.rsp_game_player_map
        self.log.info(player_map)
        # 如果字典中包含群组id并且 玩家id在字典中
        if player_map.get(group_id):
            is_overtime = now_to_datetime4() > two_minutes_later(player_map[group_id][2])
            self.log.info('游戏是否超时:%s' % is_overtime)
            if is_overtime:
                msg = '@' + str(player_map[group_id][3]) + ' 游戏已经超时自动终止了呀!'
                msg.chat.send_msg(msg)
                player_map.pop(group_id)  # 超时删除群组id对应的字典
        if player_map.get(group_id):  # 超时可能会pop掉该key,需要重新判断
            if user_id not in player_map.get(group_id, []):  # 不是玩家的消息,不进行回应
                return 'text', '@' + msg.member.name + " 先等等哦,我正在跟@" + \
                       player_map[group_id][3] + " 玩石头剪刀布", ''
            else:
                cancel, result, pic = player_map[group_id][1].play(msg)  # 玩游戏
                self.log.debug('game result:{} pic:{}'.format(result, pic))
                if cancel == 1:
                    player_map.pop(group_id)  # 如果游戏结束, 删除群组id对应的字典
                return 'both', pic, result
        typ, content1, content2 = self.finger_guessing_game(msg)  # 猜拳游戏
        if typ == 'text':
            return typ, content1, content2
        return empty_result"""

    def red_bag(self, msg) -> tuple:
        if "口令红包" in msg.text:
            return "text", "管理员会在某些时间在群里发出超越百科抢答红包,回答正确会得到超越积分,多多留意~", ""
        real_msg = msg.text.split()
        if self.red_bag_num == 0:  #如果红包剩余数量为 0
            self.answer = ""  # answer清零
        else:
            print(self.answer)
            if self.answer == real_msg[1] and msg.is_at:
                user_puid = msg.member.puid
                bot_id = self.bot.self.puid
                result = self.user.transfer(bot_id, user_puid, self.group.puid,
                                            3, self.api_key)
                self.red_bag_num -= 1
                if result["status"] == "success":
                    return 'text', " 口令正确!奖励给" + msg.member.name + " 3 个超越积分!", ''
                else:
                    return 'text', '红包领完啦!', ''
        return empty_result

    def draw_lots(self, msg) -> tuple:
        if "超越抽签" in msg.text:
            return "text", "每日0点过后,@我并回复「抽签」,可以抽出你当日的运势签,@我并回复「解签」会解释抽签内容~", ""
        real_msg = msg.text.split()
        user_id = msg.member.puid
        if real_msg[len(real_msg) - 1] == "抽签":
            if user_id in self.user_lots_map:
                return 'text', '@' + msg.member.name + ' 今日你的运势签: ' + self.user_lots_map[
                    user_id], ''
            else:
                msg1, msg2 = self.draw_lots_game.play()
                self.user_lots_map[user_id] = msg1
                self.user_lots_read_map[user_id] = msg2
                return 'text', '@' + msg.member.name + ' 今日你的运势签: ' + msg1, ''
        elif real_msg[len(real_msg) - 1] == "解签":
            if user_id in self.user_lots_read_map:
                return 'text', '@' + msg.member.name + ' 解签: ' + self.user_lots_read_map[
                    user_id], ''
            else:
                return 'text', '@' + msg.member.name + ' 今日还未进行抽签哦,请@我回复抽签', ''
        else:
            return empty_result

    def reward(self, msg) -> tuple:
        """
        打赏
        :param msg:
        :return:
        """
        if str.find(msg.text, "打赏") != -1:
            str_after_dashang = msg.text[str.find(msg.text, "打赏") + 3:].split()
            to = self.user.find_user_by_name(msg.sender, str_after_dashang[0])
            from_puid = msg.member.puid
            self.log.info(from_puid)
            self.log.info(to.puid)
            result = self.user.transfer(
                from_puid,
                to.puid,
                self.group.puid,
                int(str_after_dashang[1], ),
                self.api_key,
            )
            if result["status"] == "success":
                payload = '打赏成功!' + msg.member.name + " 打赏给 " + \
                          to.name + " " + str_after_dashang[1] + "个超越积分!"
                return 'text', payload, ''
            else:
                return 'text', '打赏失败!', ''
        return empty_result

    def integral(self, msg) -> tuple:
        """
        积分相关
        :return:
        """
        real_msg = msg.text.split()
        if real_msg[len(real_msg) - 1] == "超越积分":
            msg = "超越积分可以用来干很多好玩的事情,后续推出虚拟房产和虚拟商店,可作为购买力进行交易哦,还支持个人打赏,@我并回复「余额」来查看你的积分总额。"
            return 'text', msg, ''
        if real_msg[len(real_msg) - 1] in ["余额", "积分"]:
            user_puid = msg.member.puid
            print("想拿余额的puid:")
            print(user_puid)
            balance = self.user.get_balance_by_puid(user_puid, self.group.puid)
            msg = "你有" + str(balance) + "超越积分"
            return 'text', msg, ''
        if real_msg[len(real_msg) - 1] == "等级":
            user_puid = msg.member.puid
            level = self.user.get_level_by_puid(user_puid, self.group.puid)
            msg = "你现在是" + str(level) + "级: " + self.level_map[int(level)]
            return 'text', msg, ''
        return empty_result

    def houses(self, msg) -> tuple:
        """
        房产相关
        :return:
        """
        real_msg = msg.text.split()
        try:
            if "超越买房" in msg.text:
                return "text", "超越买房是实验性功能,@我并回复「看房」查看目前「超越大陆」上的房产所有者\n\n"+\
                    "@我并回复「买房 房产名 价格」可以进行房产购买,例如「@全村的希望 买房 火炉堡 30」\n"+\
                        "注意!!!你出的价格至少要比当前的价格大 1,才能买房成功 \n" +\
                        "如果你是房产所有者,@我并回复「房产名 签名:「你要签名的内容」」可进行签名,例如「@全村的希望 火炉堡 签名:靓仔」", ""
            if real_msg[len(real_msg) - 1] == "看房":
                print("=== 看房ing ===")
                msg = self.real_estate.look()
                return 'text', msg, ''
            elif re.search(r'(签名:|签名:)(.*)', msg.text):
                print("=== 签名ing ===")
                house_name = real_msg[1]
                print(msg.text)
                signature = msg.text[msg.text.find("签名") + 3:]
                print(house_name)
                print(self.api_key)
                print(msg.member.puid)
                print(self.group.puid)
                print(signature)
                res = self.real_estate.leave_sig(msg.member.puid,
                                                 self.group.puid, signature,
                                                 house_name, self.api_key)
                print(res)
                if res["result"] == "success":
                    payload = "你在" + house_name + "上留下了你的签名:" + signature
                    return 'text', payload, ''
                else:
                    payload = "签名失败!"
                    return 'text', payload, ''
            elif real_msg[1] == "买房":
                print("=== 买房ing ===")
                house_name = real_msg[2]
                amount = int(real_msg[3])
                print(house_name)
                print(amount)
                res = self.real_estate.buy_house(msg.member.puid,
                                                 self.group.puid, house_name,
                                                 amount, self.api_key)
                if res["result"] == "success":
                    payload = "买房成功!\n你现在是 " + house_name + " 的领主!"
                    return 'text', payload, ''
                else:
                    payload = "买房失败!"
                    return 'text', payload, ''

            return empty_result
        except:
            return empty_result

    def extra(self, msg) -> tuple:
        """
        额外添加
        :param msg:
        :return:
        """
        real_msg = msg.text.split()
        if real_msg[len(real_msg) - 1] in ["致谢", "鸣谢"]:
            return 'text', "感谢「心理医生聪」与「禹sen」,提供超越语录的支持!", ''
        if real_msg[len(real_msg) - 1] in ["帮助", "?", "?"]:
            payload = "本 AI 目前支持以下功能: \n" + \
                        "- 超越积分\n" + \
                        "- 天降超越\n" + \
                        "- 超越猜拳\n" + \
                        "- 村头留言板\n" + \
                        "- 超越抽签\n" + \
                        "- 超越接龙\n" + \
                        "- 口令红包(管理员功能)\n" + \
                        "- 超越买房"

            return 'text', payload, ''
        if real_msg[len(real_msg) - 1] == "投票":
            payload = "https://ke.qq.com/cates/ccyy/index.html?act_id=1&work_id=29&mmticket= ⬅ 欢迎猛戳链接投票"
            return 'text', payload, ''
        if real_msg[len(real_msg) - 1].find("笑话") != -1:
            payload = choice(self.jokes)
            return 'text', payload, ''
        return empty_result

    def handle_solo_msg(self, msg):
        """
        处理私聊回复
        :param msg:
        :return:
        """
        friend = msg.sender
        # 向新的好友发送消息
        friend.send('你好呀,我是全村的希望!')
        friend.send('参与内测看我朋友圈的图片,扫二维码加群')
        # friend.send_image('group.jpeg')

    def handle_group_msg(self, msg) -> tuple:
        """
        处理群组回复消息
        :param msg:
        :return:
        """
        self.log.info('receive: %s' % msg.text)

        typ, content1, content2 = self.reward(msg)  # 打赏可能被@ 也可能不被@
        if typ:
            self.log.info(content1)
            return typ, content1, content2

        typ, content1, content2 = self.robot_init(msg)  # 紧急情况下的初始化 以及口令红包的初始化
        if typ:
            self.log.info(content1)
            return typ, content1, content2
        typ, content1, content2 = self.red_bag(msg)  # 口令红包
        if typ:
            self.log.info(content1)
            return typ, content1, content2

        typ, content1, content2 = self.random_img(msg)  # 天降超越
        if typ:
            self.log.info(content1)
            return typ, content1, content2

        typ, content1, content2 = self.chaoyue_ana(msg)  # 超越语录
        if typ:
            self.log.info(content1)
            return typ, content1, content2

        if msg.is_at:  # 如果@到机器人,才进行的回应
            typ, content1, content2 = self.play_game(
                msg)  # 玩游戏,高优先级,内部存在拦截其他回复
            if typ:
                self.log.info(content1)
                user_puid = msg.member.puid
                bot_id = self.bot.self.puid
                user_balance = self.user.get_balance_by_puid(
                    user_puid, msg.member.group.puid)
                bot_balance = self.user.get_balance_by_puid(
                    bot_id, msg.member.group.puid)
                if user_balance < 3:
                    payload = " 由于你余额不足 3 积分,所以本次游戏没有奖惩哦~"
                elif bot_balance < 3:
                    payload = " 超越宝宝的钱包瘪了,所以本次游戏没有奖惩哦~"
                else:
                    if "游戏结束,恭喜你赢了" in content2:
                        from_puid = bot_id
                        print(from_puid)
                        to_puid = user_puid
                        result = self.user.transfer(from_puid, to_puid,
                                                    self.group.puid, 3,
                                                    self.api_key)
                        if result["status"] == "success":
                            payload = " 奖励给 " + msg.member.name + " 3 个超越积分!"
                        else:
                            payload = " 但是我没钱啦~"
                    elif "你输了" in content2:
                        from_puid = user_puid
                        to_puid = bot_id
                        result = self.user.transfer(from_puid, to_puid,
                                                    self.group.puid, 3,
                                                    self.api_key)
                        if result["status"] == "success":
                            payload = " 扣除 " + msg.member.name + " 3 个超越积分!"
                        else:
                            payload = " 你钱不够,接下来的游戏会没有奖励哦~"
                    else:
                        payload = ""
                return typ, content1, content2 + payload
            typ, content1, content2 = self.draw_lots(msg)  # 抽签
            if typ:
                self.log.info(content1)
                return typ, content1, content2
            typ, content1, content2 = self.handle_leave_message(msg)  # 处理留言请求
            if typ:
                self.log.info(content1)
                return typ, content1, content2
            typ, content1, content2 = self.get_group_introduction(msg)  # 群简介
            if typ:
                self.log.info(content1)
                return typ, content1, content2
            typ, content1, content2 = self.integral(msg)  # 积分相关
            if typ:
                self.log.info(content1)
                return typ, content1, content2

            typ, content1, content2 = self.houses(msg)  # 积分相关
            if typ:
                self.log.info(content1)
                return typ, content1, content2

            typ, content1, content2 = self.extra(msg)  # 额外信息
            if typ:
                self.log.info(content1)
                return typ, content1, content2
            tuling_reply = self.tuling.reply_text(msg).replace(
                "图灵机器人", "超越宝宝").replace("清华大学硕士杨超?",
                                         "杨超越最美不允许反驳").replace("你接错了", "我不会接")
            self.log.info(tuling_reply)
            return 'text', tuling_reply, ''

        return empty_result
コード例 #19
0
    def getUser(self, id):
        try:
            response = self.getResource("users/%s" % id, "GET")
        except requests.exceptions.HTTPError as ex:
            response = ex.response.json()
            raise SynergyError("error on retrieving the user info (id=%r): %s"
                               % (id, response["error"]["message"]))

        user = None

        if response:
            info = response["user"]

            user = User()
            user.setId(info["id"])
            user.setName(info["name"])
            user.setEnabled(info["enabled"])

            if "default_project_id" in info:
                user.setProjectId(info["default_project_id"])
            elif "tenantId" in info:
                user.setProjectId(info["tenantId"])

        return user
コード例 #20
0
ファイル: msg_lib.py プロジェクト: zhangenter/bf_chat
def parse_online_msg(bytes):
    user_dic = parse_json_msg(bytes)
    return User.parse_from_dic(user_dic)
コード例 #21
0
ファイル: msg_lib.py プロジェクト: zhangenter/bf_chat
def parse_all_user_info_msg(bytes):
    user_dic_arr = parse_json_msg(bytes)
    users = []
    for user_dic in user_dic_arr:
        users.append(User.parse_from_dic(user_dic))
    return users
コード例 #22
0
ファイル: msg_lib.py プロジェクト: zhangenter/bf_chat
def parse_userinfo_msg(bytes):
    user_dic = parse_json_msg(bytes)
    return User.parse_from_dic(user_dic)
コード例 #23
0
def run_cmd(cmd, device):
    # connection to device and run the received command
    device_connection = DeviceConnector(device, user)
    command = DeviceCommand(device_connection, cmd)
    output = command.run_command()

    return output
    # return json.dumps(output)


# Entry point
if __name__ == "__main__":
    print('Script started')

    # setup user for a device connections
    user = User()
    user._password = '******'
    # print('Password for %s is needed to connect on devices' % user.get_user())
    # user.ask_password()

    for host_key, host_detail in deviceList:
        device = Device(hostname=host_key,
                        ip=host_detail.get('ip'),
                        os=host_detail.get('os'))

        result = run_cmd('show vlan', device)

        # write the JSON to the HTML template
        # with open(r'../_file_output/cmd_output.txt', 'w') as f:
        #     f.write(result)
コード例 #24
0
from common.user import User

users = [
    # {
    #     'id': 1,
    #     'username': '******',
    #     'password': '******'
    # }
    User(1, 'bob', 'asdf'),
]

username_mapping = {
    # 'bob': {
    #     'id': 1,
    #     'username': '******',
    #     'password': '******'
    # }
    u.username: u
    for u in users
}

userid_mapping = {
    # 1: {
    #     'id': 1,
    #     'username': '******',
    #     'password': '******'
    # }
    u.id: u
    for u in users
}
コード例 #25
0
ファイル: odyssey.py プロジェクト: dsoskey/spotiCLI
def getUniqueTracks(username):
    trackDict = {}
    user = User(username)
    for playlist in user.playlists().values():
        trackDict = {** trackDict, **{track.uri: track for track in playlist.tracks()}}
    return trackDict