def Send(chatroom, sender=None, name='random', top='_', bot='_', font='impact', img=''): if name == 'random': rand = GetRandomTemplate(chatroom, sender) name = rand[0] img = rand[1] elif name == "custom": if IsEmpty(img): raise Exception("img is empty") else: if IsEmpty(img): img = GetImg(chatroom, sender, name) if IsEmpty(img): if name not in builtinTemplates: chatroom.SendText("[Command(Meme)] Template named '" + name + "' not found") return CommandResult.Done() else: name = "custom" top = Escape(top) bot = Escape(bot) if IsEmpty2(top) and IsEmpty2(bot) and not IsEmpty(img): return CommandResult(images=Image(client=chatroom.client, url=img)) url = GetUrl(name, top, bot, font, img) return CommandResult( images=Image(client=chatroom.client, url="https://" + url))
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)
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()
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)
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()
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()
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()
def DeepArt(message, options, text='', style='', images=[]): if IsEmpty(style): style = text if IsEmpty(style): style = 'custom' imageLen = len(images) if style == 'custom': if imageLen < 2: return CommandResult.ExpectImage(askImage=imagesStr[imageLen]) return DeepArtCustom(message, images) else: if imageLen == 0: return CommandResult.ExpectImage(askImage=imagesStr[1]) return DeepArtBuiltin(message, style, images)
def Sort(message, options, text=''): if IsEmpty(text): message.ReplyText("Please provide text") return s1s = text.split('\n') d = {} for s1 in s1s: s2s = s1.split(' ') for s2 in s2s: s2a = ''.join([c for c in s2 if c.isalpha()]) if not IsEmpty(s2a): s2 = s2a if s2 in d: d[s2] += 1 else: d[s2] = 1 d2 = {} for k, v in d.items(): if v in d2: d2[v].extend([k] * v) else: d2[v] = [k] * v d3 = {} ss = [] for k, v in d2.items(): d3[k] = sorted(v) for k, v in sorted(d3.items()): ss.extend(v) return CommandResult(type=CommandResultType.done, texts=[' '.join(ss)])
def Sort(message, options, text=''): if IsEmpty(text): message.ReplyText("Please provide text") return s1s = text.split('\n') s1s2 = [] for s1 in s1s: s2s = s1.split('.') s2s2 = [] for s2 in s2s: s3s = s2.split(';') s3s2 = [] for s3 in s3s: s4s = s3.split(',') s4s2 = [] for s4 in s4s: s5s2 = s4.split(' ') try: s5s2 = [int(x) for x in s5s2] s5s2.sort() s5s2 = [str(x) for x in s5s2] except Exception: s5s2.sort() s4s2.append(' '.join(s5s2)) s3s2.append(','.join(s4s2)) s2s2.append(';'.join(s3s2)) s1s2.append('.'.join(s2s2)) text = '\n'.join(s1s2) return CommandResult(type=CommandResultType.done, texts=[text])
def Reply(self, text): if self.exactStart: if not text.startswith(self.exactStart): return if self.exactEnd: if not text.endswith(self.exactEnd): return if self.exactWordIns: words = {x: 0 for x in text.split(' ')} words2 = { x.strip('.,/;\'\\<>?:"{}|!@#$%^&*()_+=-~`'): 0 for x in words.iterkeys() } words3 = {x.strip('123457890'): 0 for x in words2.iterkeys()} if self.exactWordInRule == Rule.And: for x in self.exactWordIns: if x not in words and x not in words2 and x not in words3: return elif self.exactWordInRule == Rule.Or: for x in self.exactWordIns: if x in words or x in words2 or x in words3: break if self.exactIns: if self.exactWordInRule == Rule.And: for x in self.exactIns: if x not in text: return elif self.exactWordInRule == Rule.Or: for x in self.exactIns: if x in text: break return CommandResult(texts=[Get(self.replies)])
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()
def _1ExactReplace(l, text): exactReplaced = False for kv in l: word = kv[0] if not exactReplaced and word in text: exactReplaced = True text = text.replace(word, Get(kv[1])) if exactReplaced: return CommandResult(texts=[text])
def _1RegexReplace(l, text): replaced = False for rrp in l: res = subn(rrp[0], Get(rrp[1]), text) if res[1]: replaced = True text = res[0] if replaced: return CommandResult(texts=[text])
def Stop(self, force=False): with self.lock: if self.nums: s = " ".join(FloatToStr(x) for x in self.nums) s2 = Solve(s) if s2: self.SendText(s2) else: send.SendText("Theres no solution to '%s'" % s) self.nums = None return CommandResult.Done()
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
def _1ExactWordIn(l, text): words = {x: 0 for x in text.split(' ')} words2 = { x.strip('.,/;\'\\<>?:"{}|!@#$%^&*()_+=-~`'): 0 for x in words.iterkeys() } words3 = {x.strip('123457890'): 0 for x in words2.iterkeys()} for kv in l: key = kv[0] if key in words or key in words2 or key in words3: return CommandResult(texts=[Get(kv[1])])
def Sort(message, options, text=''): if IsEmpty(text): message.ReplyText("Please provide text") return s1s = text.split('\n') ss = [] for s1 in s1s: s2s = s1.split(' ') ss.extend(s2s) ss.sort() return CommandResult(type=CommandResultType.done, texts=[' '.join(ss)])
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()
def CommandList(message, options, text='', admin=False): client = message.client if admin: if client.hasAdminCommands: l = sorted([x for x in client._1adminCommands.items()]) s = 'Admin commands :' for k, v in l: si = "\n%s" % k if k != v.name: si = si + (" (%s)" % v.name) s = s + si return CommandResult.Done(texts=[s]) return CommandResult.Done(texts=['No admin command registered']) elif client.hasCommands: l = sorted([x for x in client._1commands.items()]) s = 'Commands :' for k, v in l: si = "\n%s" % k if k != v.name: si = si + (" (%s)" % v.name) s = s + si return CommandResult.Done(texts=[s]) return CommandResult.Done(texts=['No command registered'])
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])
def Send(self): if self.nums: buts = Buttons(" ".join(FloatToStr(x) for x in self.nums)) buts.AddButton( "Next", "/24 next", "\nTo give up and ask for next numbers, type '/24 next'") buts.AddButton("Stop", "/24 stop", "\nTo just give up, type '/24 stop'") else: buts = Buttons("Game is not running") buts.AddButton("Create", "/24 create", "\nTo run it, type '/24 create'") self.SendButtons(buts) return CommandResult.Done()
def JPEG(message, options, images=[], quality=50, iterations=50): img = images[0].bytes imgIn = BytesIO(img) baseQuality=quality for i in range(0, iterations): #open previously generated file compImg = PILImage.open(imgIn) #compress file at 50% of previous quality imgOut = BytesIO() compImg.save(imgOut, "JPEG", quality=quality) quality = int(quality*baseQuality/100) imgIn = imgOut imgIn.seek(0) img = imgIn.read() img = Image(bytes=img) return CommandResult.Done(images=[img])
def Vapor(message, options, text=''): if IsEmpty(text): message.ReplyText("Please specify 'text' argument.") return l = [] for c in text: if c in vaporDict: l.append(vaporDict[c]) else: l.append(c + ' ') ret = ''.join(l) return CommandResult(type=CommandResultType.done, texts=[ret])
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()
def Emoji(message, options, text=''): if IsEmpty(text): message.ReplyText("Please specify 'text' argument.") return for emoji in emojiList: text = text.replace(emoji[0], emoji[1]) for emoji in emojiList4: e1 = emoji[1] i = randint(0, e1[0] - 1) text = text.replace(emoji[0], e1[1][i]) #for emoji in emojiList2: # text = sub(emoji[0], emoji[1], text) #for emoji in emojiList3: # regex = emoji[0] # r = emoji[1] # replace = r[1][randint(0, r[0]-1)] # text = sub(regex, replace, text) l = [] for c in text: if c in emojiDict: if c in emojiDict2: t1 = emojiDict[c] t2 = emojiDict2[c] n1 = t1[0] n = n1 + t2[0] r = randint(0, n - 1) if r < n1: l.append(t1[1][r]) else: l.append(t2[1][r - n1]) else: t = emojiDict[c] l.append(t[1][randint(0, t[0] - 1)]) elif c in emojiDict2: t = emojiDict2[c] l.append(t[1][randint(0, t[0] - 1)]) else: l.append(c) ret = "".join(l) return CommandResult(type=CommandResultType.done, texts=[ret])
def DeepArtCustom(message, images): s = Session() print("Getting token ...") rToken = s.get(daLoginUrl, verify=False) mToken = daTokenRx.match(rToken.text) token = mToken.group(1) print("Logging in ...") info = {'csrfmiddlewaretoken': token, 'email': daEmail, 'password': daPw} rLogin = s.post(daLoginUrl, verify=False) print("Uploading image ...") img = images[1].bytes rImg = s.post(daContentUploadUrl, files={'image': img}, verify=False) jImg = loads(rImg.text) print("Uploading style ...") style = images[0].bytes rStyle = s.post(daStyleUploadUrl, files={'image': style}, verify=False) jStyle = loads(rStyle.text) print("Requesting ...") info = { 'content_img': jImg['hash'], 'style_img': jStyle['hash'], 'email': daEmail, 'password': daPw, 'privacy': 'private' } rDa = s.post(daUrl, data=info, verify=False) jDa = loads(rDa.text) rDa = s.post(daHomeUrl + jDa['redirect'], verify=False) mDaCode = daCodeRx.match(rDa.text) daCode = mDaCode.group(1) daCodeUrl = daHost + daCode + "/" message.ReplyText("[DeepArt] Please wait up to 15 minutes.\n" + daCodeUrl) while True: rDaCode = s.get(daCodeUrl, verify=False) if rDaCode.url == daCodeUrl: mDaImg = daImgRx.match(rDaCode.text) daImg = mDaImg.group(1) img = Image(url=daImg) return CommandResult.Done(images=[img]) sleep(5)
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()
def MockSB(message, options, text=''): if IsEmpty(text): message.ReplyText("Please specify 'text' argument.") return text = text.lower() tlen = len(text) l = list(text) consUp = 0 consLow = 0 for i in range(0, tlen): if consUp >= 2: low = l[i] if low.upper() != low: consUp=0 consLow=1 elif consLow >=2: low = l[i] up = low.upper() if up != low: consUp=1 consLow=0 l[i] = up elif random() > 0.5: low = l[i] up = low.upper() if up != low: consUp=consUp+1 consLow=0 l[i] = up else: consLow=consLow+1 consUp=0 ret = "".join(l) #message.ReplyText(ret) return CommandResult(type=CommandResultType.done, texts=[ret])
def Send(self): if self.nums: s = "Round %d\n%s" % (self.round, '\n'.join( ("%s : %d (%d)" % (player.name, player.score, player.pendingScore)) for player in self.players)) self.SendText( "Round%d\n%s\n%d seconds left.\nType '/242 done' if you figured it out\nPlayers who 'figured it out':%d\n%s\nPlayers who 'haven't figured it out':%d\n%s" % (self.round, " ".join("%g" % x for x in self.nums), round(self.end - time()), len(self.winners), '\n'.join( ("%s : %d (%d)" % (x.name, x.score, x.pendingScore)) for x in self.winners), len(self.losers), '\n'.join( ("%s : %d" % (x.name, x.score)) for x in self.losers))) buts = Buttons("Have you figured it out?") buts.AddButton("Yes", "/242 done", "\nIf so, type '/242 done'") self.SendButtons(buts) else: buts = Buttons( "TwentyFour2 is already running, but not started yet.") buts.AddButton("Force Start", "/242 forcestart", "\nTo start it, type '/242 forcestart'") self.SendButtons(buts) return CommandResult.Done()