示例#1
0
 def Done(self, done=True):
     if self.room.phase != RoomPhase.guessing:
         self.SendText("It's not time yet")
         return CommandResult.Failed()
     with self.lock:
         if self.pendingScore:
             self.SendText("You have done-ed")
         else:
             with self.room.lock:
                 if len(self.room.losers) <= 1:
                     self.SendText("You're the last one")
                 elif self.pendingScore:
                     self.SendText("You have done-ed")
                 else:
                     self.pendingScore = max(
                         0,
                         round(
                             (self.room.end - time()) * self.room.winPoint))
                     if not self.pendingScore:
                         self.SendText("Time's up")
                     else:
                         if self in self.room.losers:
                             self.room.losers.remove(self)
                         if self not in self.room.winners:
                             self.room.winners.append(self)
                             self.room.winners.sort(key=lambda x: x.score,
                                                    reverse=True)
                         self.room.SendText("%s says he knows the answer." %
                                            self.name)
                         if len(self.room.losers) <= 1:
                             with self.room.cond:
                                 self.room.cond.notifyAll()
                         return CommandResult.Done()
     return CommandResult.Failed()
示例#2
0
def HandleExactReply(message,
                     options='',
                     text='',
                     continuous=CommandContinuousCallType.notContinuous,
                     on='',
                     off='',
                     word='',
                     replies=''):
    text = text.lower()
    if continuous:
        chatroom = message.chatroom
        sender = message.sender
        for tup in replyList:
            ret = _1HandleExactReply(chatroom, sender, text, tup)
            if ret:
                return ret
        return CommandResult.Failed()
    else:
        if text == 'on':
            on = completeArg
        elif text == 'off':
            off = completeArg
        ret = []
        if not IsEmpty(on):
            a = (On(message.chatroom, message.sender, options, on, True))
            if a:
                ret.append(a)
        if not IsEmpty(off):
            d = (On(message.chatroom, message.sender, options, off, False))
            if d:
                ret.append(d)
        if IsEmpty(ret):
            raise Exception('Invalid parameters')
        return CommandResult(texts=ret)
示例#3
0
def HandleRegexReply(message,
                     options='',
                     text='',
                     continuous=CommandContinuousCallType.notContinuous,
                     activate='',
                     deactivate=''):
    text = text.lower()
    if continuous:
        chatroom = message.chatroom
        sender = message.sender
        for tup in replyList:
            ret = _1HandleRegexReply(chatroom, sender, text, tup)
            if ret:
                return ret
        return CommandResult.Failed()
    else:
        if text == 'on' or text == 'activate':
            activate = completeArg
        elif text == 'off' or text == 'deactivate':
            deactivate = completeArg
        ret = []
        if not IsEmpty(activate):
            a = (Activate(message.chatroom, message.sender, activate, True))
            if a:
                ret.append(a)
        if not IsEmpty(deactivate):
            d = (Activate(message.chatroom, message.sender, deactivate, False))
            if d:
                ret.append(d)
        if IsEmpty(ret):
            raise Exception('Invalid parameters')
        return CommandResult(texts=ret)
示例#4
0
 def ForceStart(self, sender):
     with self.lock:
         if sender not in self.playersByObj:
             self.SendText(
                 "%s, you havent joined and thus have no authority to forcestart the game"
                 % sender.name)
             return CommandResult.Failed()
         return self.Start()
示例#5
0
 def Start(self):
     with self.lock:
         if len(self.players) < 2:
             self.SendText("Need at least 2 players to start")
             return CommandResult.Failed()
         self.phase = RoomPhase.starting
         self.round = 0
         self.obj.client.Thread(self.RoundStart)
         return CommandResult.Done()
示例#6
0
 def Solve(self, text):
     with self.lock:
         if self.nums:
             self.SendText(
                 "Game is still running. Please stop it first if you want to solve. If the four numbers were also from me, just type '/24 next' to change the numbers and also give the answer"
             )
             return CommandResult.Failed()
     s = Solve(text)
     if s:
         self.SendText(s)
     return CommandResult.Done()
示例#7
0
 def Vote(self, voter, id):
     if voter not in self.playersByObj:
         self.SendText("%s, you havent even joined." % voter.name)
         return CommandResult.Failed()
     voter = self.playersByObj[voter]
     if self.phase != RoomPhase.explainVote:
         self.SendText("It's not time yet")
         return CommandResult.Failed()
     if voter not in self.losers:
         voter.SendText("You can't vote")
         return CommandResult.Failed()
     if id not in self.playersById:
         voter.SendText("Invalid ID : %d" % id)
     votee = self.playersById[id]
     ret = self.votes.Vote(voter, votee)
     if not self.allowRevote or self.quick and ret.type == CommandResultType.Done and len(
             self.votes.haventVoted) == 0:
         with self.cond:
             self.cond.notifyAll()
     return ret
示例#8
0
 def Stop(self, force=False):
     if not force:
         t = self.CheckTime()
         if t:
             self.SendText("You have to wait %d seconds" % t)
             return CommandResult.Failed()
     with self.lock:
         if self.nums:
             s = " ".join(FloatToStr(x) for x in self.nums)
             s2 = Solve(s)
             self.SendText(s2)
         self.nums = None
         return CommandResult.Done()
示例#9
0
def DeepArtBuiltin(message, style, images):
    if not style.isdigit():
        message.ReplyText("Invalid style (1)")
        return CommandResult.Failed()
    r = post(
        'http://turbo.deepart.io/api/post/',
        data={
            'style': style,
            'return_url': 'http://my.return/'
        },
        files={'input_image': ('file.jpg', images[0].bytes, 'image/jpeg')})

    img = r.text
    if len(img) > 100:
        message.ReplyText("Invalid style (2)")
        return CommandResult.Failed()

    path = ("/media/output/%s.jpg" % img)
    link = "https://turbo.deepart.io" + path
    message.ReplyText("[DeepArt] Please wait up to 3 minutes.\n" + link)
    WaitOK("turbo.deepart.io", path)
    img = Image(url=link)
    return CommandResult.Done(images=[img])
示例#10
0
def RObj(message, options, text=''):
    if not message.client.hasUser or not message.client.hasOA or not message.client.oAClient.obj:
        message.ReplyText("Sorry, this feature is unavailable")
        return CommandResult.Failed()
    client = message.client
    chatroom = message.chatroom
    sender = message.sender
    if chatroom.chatroomType == ChatroomType.user:
        message.ReplyText("This is a private chat")
        return CommandResult.Failed()
    if groupOnly and chatroom.chatroomType == ChatroomType.room:
        message.ReplyText("This needs to be a group")
        return CommandResult.Failed()
    if not sender or not sender.name:
        message.ReplyText("Sorry, we can't identify you")
        return CommandResult.Failed()
    if not chatroom.hasUser:
        message.ReplyText("You need to have our User Account Bot here.")
        return CommandResult.Failed()
    members = chatroom.members
    if len(members) == 0:
        message.ReplyText("Sorry, we couldn't get member list")
        return CommandResult.Failed()
    if client.oAClient.obj not in members:
        message.ReplyText(
            "Our Official Account Bot is not here. I'll try to invite it. Please retry after it joined"
        )  #\n%s\n%s" % (members, client.oAClient.obj))
        try:
            chatroom.Invite(client.oAClient.obj)
        except Exception:
            pass
        return CommandResult.Failed()
    if len(members) > 3:
        message.ReplyText("There can only be you, me, and the other bot")
        return CommandResult.Failed()
    sender.rObj = chatroom
    message.ReplyText("This room has been registered as %s's RObj" %
                      sender.name)
    return CommandResult.Done()
示例#11
0
def TwentyFour(message,
               options='',
               text='',
               continuous=CommandContinuousCallType.notContinuous,
               action='',
               solve='',
               top=None,
               bot=None):
    if continuous:
        if message.chatroom not in rooms:
            return CommandResult.Failed()
        return rooms[message.chatroom].Eval(text, message.sender)
    else:
        if IsEmpty(action):
            action = text
        if action == 'create' or (IsEmpty(action) and IsEmpty(solve)):
            with lock:
                if message.chatroom in rooms:
                    room = rooms[message.chatroom]
                    if not room.nums:
                        return room.Generate()
                    return room.Send()
                else:
                    room = Room(message.chatroom, top, bot)
                    rooms[message.chatroom] = room
                    return room.Generate()
        else:
            with lock:
                if message.chatroom in rooms:
                    room = rooms[message.chatroom]
                else:
                    room = Room(message.chatroom, top, bot)
                    rooms[message.chatroom] = room
            if solve:
                return room.Solve(solve)
            elif action == 'next':
                return room.Next(top, bot)
            elif action == 'stop':
                return room.Stop()
            else:
                return room.Send()
示例#12
0
 def Join(self, player):
     with self.lock:
         if player in self.playersByObj:
             player = self.playersByObj[player]
             if player in self.leavings:
                 self.leavings.remove(player)
                 player.SendText(
                     "You have canceled to leave the next round")
                 return CommandResult.Done()
             else:
                 player.SendText(
                     "Either you have already joined or waiting for the next round to join."
                 )
                 return CommandResult.Failed()
         player = Player(self, player)
         if self.running:
             self.SendText(
                 "%s, the game is currently running. You will automatically join the next round if any."
                 % player.name)
         else:
             self.AddWaitingPlayers()
         return CommandResult.Done()
示例#13
0
 def Leave(self, player):
     with self.lock:
         if player not in self.playersByObj:
             self.SendText("@%s, You havent even joined" % player.name)
             return CommandResult.Failed()
         self.playersByObj[player].Leave()
示例#14
0
def DeepStyle(message, options, images=[]):
    print("Getting session")
    s = Session()
    s.auth = (dsEmail, dsPw)
    s.headers.update({'User-Agent' : str(UserAgent().chrome)})
    print("Getting token")
    rToken = s.get(dsLoginUrl)
    if rToken.status_code != 200:
        message.ReplyText("Error DS 1")
        return CommandResult.Failed()
    mToken = dsTokenRx.match(rToken.text)


    token = mToken.group(1)
    info = {"_token":token, "email":dsEmail, "password":dsPw, "remember":"true"}
    
    print("Logging in")
    rLogin = s.post(dsLoginUrl, data=info)
    if rLogin.status_code != 200:
        message.ReplyText("Error DS 2")
        return CommandResult.Failed()
    TryChangeToken(rLogin.text, info)
    rDeepStyle = s.get(dsUrl, data=info)
    if rDeepStyle.status_code != 200:
        message.ReplyText("Error DS 3")
        return CommandResult.Failed()
    info = {"_token":info["_token"]}
    TryChangeToken(rDeepStyle.text, info)
    print("Getting images")
    style = images[0].bytes
    img = images[1].bytes
    print("Requesting deepstyle")
    info["style"] = "custom"
    info["dreamType"]="deep-style"
    info["resolution"]="normal"
    info["optimizer"]="alpha"
    info["iterationsDepth"] ="normal"
    info["preserveOriginalColors"]="no"
    info["access"] = "public"
    info["styleScale"] = "1"
    info["styleWeight"] = "5"
    rUploadImg = s.post(dsUploadUrl, data=info, files={'image':img, 'styleImage':style})
    if rUploadImg.status_code != 200:
        message.ReplyText("Error DS 4\n" + rUploadImg.text)
        return CommandResult.Failed()
    
    mDsLink = dsLinkRx.match(rUploadImg.text)
    if mDsLink is None:
        message.ReplyText("Error DS 5 : '" + dsErrorRx.match(rUploadImg.text).group(1).replace('&quot;', '"') + "'")
        return CommandResult.Failed()
        while mDsLink is None:
            time.sleep(300)
            rUploadImg = s.post(dsUploadUrl, data=info, files={'image':img, 'styleImage':style})
            if rUploadImg.status_code != 200:
                message.ReplyText("Error DS 6")
                return CommandResult.Failed()
            mDsLink = dsLinkRx.match(rUploadImg.text)
            
    dsLink = mDsLink.group(1)
    message.ReplyText("[DeepStyle] Please wait up to 5 minutes\n" + dsLink)
    mDsLinkParse = dsLinkParseRx.match(dsLink)
    host = mDsLinkParse.group(1)
    path = mDsLinkParse.group(2)
    WaitOK(host, path)
    img = Image(url=dsLink)
    return CommandResult.Done(images=[img])
示例#15
0
def TwentyFour2(message,
                options='',
                text='',
                continuous=CommandContinuousCallType.notContinuous,
                action='',
                top=None,
                bot=None,
                allowrevote=False,
                roundtime=60,
                rounds=5,
                votetime=30,
                explaintime=15,
                winpoint=1,
                explainpoint=1,
                nosolutionpoint=0.75,
                losepoint=0,
                failpoint=-2,
                quick=True,
                done=None,
                vote=0,
                *args,
                **kwargs):
    sender = message.sender
    chatroom = message.chatroom
    client = message.client
    if continuous:
        if not sender:
            return CommandResult.Failed()
        if chatroom not in rooms:
            return CommandResult.Failed()
        room = rooms[chatroom]
        return room.Explain(sender, text)
    else:
        if IsEmpty(action):
            action = text
        sender = message.sender
        chatroom = message.chatroom
        client = message.client
        if not client.hasOA or not client.hasUser:
            message.ReplyText(
                "Sorry TwentyFour2 needs both OAClient and UserClient")
            return CommandResult.Failed()
        elif not chatroom.hasUser:
            message.ReplyText("Please invite the UserClient here first")
            return CommandResult.Failed()
        elif not chatroom.hasOA:
            if client.oAClient.obj:
                client.oAClient.obj.InviteInto(chatroom)
                message.ReplyText(
                    "Please retry the command after the OAClient joined")
            else:
                message.ReplyText("Please invite the UserClient here first")
            return CommandResult.Failed()
        elif not sender or not sender.hasUser or (not sender.name
                                                  and not sender.GetName()):
            message.ReplyText("Sorry we can't identify you.")
            return CommandResult.Failed()
        elif not sender.rObj:
            message.ReplyText(
                "%s, please type '/robj' in a room consisting of only you, our UserClient, and our OAClient"
                % sender.name)
            #message.ReplyText("%s, please accept the group invitation" % sender.name)
            return CommandResult.Failed()
        elif action == 'create':
            with lock:
                if chatroom in rooms:
                    return rooms[chatroom].Send()
                else:
                    room = Room(sender,
                                chatroom,
                                top=top,
                                bot=bot,
                                allowRevote=allowrevote,
                                roundDuration=roundtime,
                                rounds=rounds,
                                voteDuration=votetime,
                                explainDuration=explaintime,
                                winPoint=winpoint,
                                explainPoint=explainpoint,
                                noSolutionPoint=nosolutionpoint,
                                losePoint=losepoint,
                                failPoint=failpoint,
                                quick=quick,
                                *args,
                                **kwargs)
                    rooms[chatroom] = room
        else:
            room = None
            with lock:
                if chatroom in rooms:
                    room = rooms[chatroom]
                else:
                    chatroom.SendText("No TwentyFour2 game session")
                    return CommandResult.Failed()
            if action == 'join':
                return room.Join(sender)
            elif action == 'leave':
                pass
            elif action == 'done' or done is not None:
                done = action == 'done' or done
                return room.Done(sender, done)
            elif action == 'forcestart':
                return room.ForceStart(sender)
            elif vote:
                room.Vote(sender, vote)
示例#16
0
 def Explain(self, obj, text):
     sender = obj
     with self.lock:
         if not self.phase == RoomPhase.explain:
             return CommandResult.Failed()
         if obj not in self.playersByObj:
             return CommandResult.Failed()
         explainer = self.playersByObj[obj]
         if explainer != self.explainer:
             return CommandResult.Failed()
         if not self.nums:
             return CommandResult.Failed()
         text = text.strip()
         if not IsValid(text):
             return CommandResult.Failed()
         mExRx = Room.exRx.match(text)
         if not mExRx:
             return CommandResult.Failed()
         nums = None
         try:
             nums = [
                 float(mExRx.group(2)),
                 float(mExRx.group(6)),
                 float(mExRx.group(10)),
                 float(mExRx.group(14))
             ]
         except Exception as e:
             self.SendText("Error. Invalid numbers.\n%s" % (s, e))
             return CommandResult.Done()
         try:
             for i in range(0, 4):
                 x = nums[i]
                 if x < self.bot or x > self.top:
                     raise Exception(
                         "Only integers ranging from %d-%d are allowed. %g is not in range"
                         % (self.bot, self.top, x))
                 y = int(x)
                 if x != y:
                     raise Exception(
                         "Only integers ranging from %d-%d are allowed. %g is not an integer"
                         % (self.bot, self.top, x))
                 nums[i] = y
         except Exception as e:
             self.SendText("Error. Invalid numbers.\n%s" % (s, e))
             return CommandResult.Done()
         nums.sort()
         if nums != self.nums:
             self.SendText("Error. Invalid numbers.\n%s != %s" %
                           (nums, self.nums))
             return CommandResult.Done()
         s = ''
         for i in range(1, 16):
             c = mExRx.group(i)
             if c:
                 s = s + c
         try:
             name = ''
             if explainer.name:
                 name = ", %s" % explainer.name
             ret = float(eval(text))
             if ret == 24:
                 rep = "Correct%s.\n%s == 24"
                 self.SendText(rep % (name, s))
                 self.explained = True
                 with self.cond:
                     self.cond.notifyAll()
             else:
                 rep = "Wrong%s.\n%s == %g"
                 self.SendText(rep % (name, s, ret))
         except Exception as e:
             self.SendText(
                 "Error. '%s' may not be a valid math expression.\n%s" %
                 (s, e))
         return CommandResult.Done()
示例#17
0
 def Done(self, sender, done=True):
     with self.lock:
         if sender not in self.playersByObj:
             self.SendText("%s, you're not even in the game" % sender.name)
             return CommandResult.Failed()
         return self.playersByObj[sender].Done(done)
示例#18
0
def LunaPic(message, options, text='', images=[]):
    link = images[0].imgurUrl

    splitArgs = text.split(' ')

    if splitArgs[0] == 'random':
        if len(splitArgs) < 1 or isEmpty(splitArgs[1]) or not splitArgs[1].isdigit():
            iterations = 1
        else:
            iterations = int(splitArgs[1])
        if iterations < 1:
            iterations = 1
        if iterations > 20:
            iterations = 20
        #l = list(lpRandoms)
        splitArgs = []
        for i in range(0, iterations):
            #splitArgs.append(l.pop(randint(0, len(l) - 1)))
            splitArgs.append(lpRandoms[randint(0,maxLpRandomIndex)])

    print(str(splitArgs))
    s = Session()
    r0 = s.get("http://lunapic.com/editor/?action=" + splitArgs[0] + "&url=" + link)
    if r0.status_code != 200:
        message.ReplyText("Error LP 1. LunaPic is probably down. Please try again later.")
        return
    lp0m = lprx0.match(r0.url)
    if lp0m is None:
        #print(r0.text)
        message.ReplyText("Error LP 2. LunaPic is probably down. Please try again later.")
        return

    lpurl = 'http://' + lp0m.group(1) + '/editor/'
    
    for arg0 in splitArgs:
        arg1 = arg0.split(':')
        arg = arg1[0]
        if arg not in lpActions:
            continue
        arg2 = None
        if len(arg1) > 1:
            arg2 = arg1[1]
        info = {'action':arg, 'url':link}
        if arg == 'tint' or arg == 'groovy-color':
            if arg2 is None:
                arg2 = lpColors[randint(0, maxLpColorIndex)]
            info['color'] = arg2
        if arg == 'transitions':
            if arg2 is None:
                arg2 = lpTransitions[randint(0, maxLpTransitionIndex)]
            info['type'] = arg2
        if arg == 'scan':
            if arg2 is None:
                arg2 = 1
            info['hoz'] = arg2
        r1 = s.post(lpurl, data=info)
        if r1.status_code != 200:
            message.ReplyText("Error LP 3. LunaPic is probably down\n" + "lpurl='" + lpurl + "'\ninfo='" + str(info) + "'")
            return CommandResult.Failed()
        r2a = s.get(lpurl + "?action=imgur")
        if r2a.status_code != 200:
            message.ReplyText("Error LP 4. LunaPic is probably down\n" + "lpurl='" + lpurl + "'\ninfo='" + str(info) + "'")
            return CommandResult.Failed()
        mLpimgurRx = lpimgurRx.match(r2a.text)
        if mLpimgurRx is None:
            message.ReplyText("Error LP 5. LunaPic is probably down or you submitted invalid action\n" + "lpurl='" + lpurl + "'\ninfo='" + str(info) + "'")
            return CommandResult.Failed()
        link = mLpimgurRx.group(1).replace("http:", "https:")

    img = Image(url=link)
    return CommandResult.Done(images=[img])