コード例 #1
0
ファイル: sort3.py プロジェクト: winbotscript/JeBB
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)])
コード例 #2
0
ファイル: regexreply.py プロジェクト: winbotscript/JeBB
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)
コード例 #3
0
ファイル: exactreply.py プロジェクト: winbotscript/JeBB
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)
コード例 #4
0
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))
コード例 #5
0
 def __init__(self, altTextHeader='', columnText=''):
     self.buttons = []
     if IsEmpty(columnText):
         self.SetColumnText(altTextHeader)
     else:
         self.SetColumnText(columnText)
     if IsEmpty(altTextHeader):
         self.SetAltTextHeader(columnText)
     else:
         self.SetAltTextHeader(altTextHeader)
コード例 #6
0
ファイル: deepart.py プロジェクト: winbotscript/JeBB
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)
コード例 #7
0
 def __init__(self, label, text, altTextEntry=''):
     self.label = label
     self.text = text
     if IsEmpty(altTextEntry):
         self.altTextEntry = '\n' + label + ":'" + text + "'"
     else:
         self.altTextEntry = altTextEntry
コード例 #8
0
ファイル: sort2.py プロジェクト: winbotscript/JeBB
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])
コード例 #9
0
 def imgurUrl(self):
     with self.lock:
         if not IsEmpty(
                 self.url) and self._1url.startswith("https://i.imgur"):
             return self._1url
         self._1url = self.UploadPyImgur()
         return self._1url
コード例 #10
0
ファイル: twentyfour.py プロジェクト: winbotscript/JeBB
def Solve(text):
    mSolveRx = solveRx.match(text)
    if not mSolveRx:
        return ''
    nums = [
        mSolveRx.group(1),
        mSolveRx.group(2),
        mSolveRx.group(3),
        mSolveRx.group(4)
    ]
    print("nums=%s" % nums)
    for i in range(0, 4):
        x = nums[i]
        if IsEmpty(x):
            return "Need 4 numbers separated by a space"
        y = None
        try:
            y = float(x)
        except Exception:
            return "Invalid number '" + str(x) + "'"
        nums[i] = y
    for x in permutations(nums):
        msg24a = [x[0], -1, x[1], -1, x[2], -1, x[3]]
        s = TryOperators(msg24a, 0)
        if s:
            return s
    return ''
コード例 #11
0
ファイル: twentyfour.py プロジェクト: winbotscript/JeBB
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 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)])
コード例 #13
0
ファイル: exactreply.py プロジェクト: winbotscript/JeBB
 def __init__(self,
              exactStart=None,
              exactEnd=None,
              exactWordIns=None,
              exactWordInRule=Rule.And,
              exactIns=None,
              exactInRule=Rule.And,
              replies=[]):
     if IsEmpty(replies):
         raise Exception("Replies can't be empty")
     if IsEmpty(exactStart):
         self.exactStart = None
     else:
         self.exactStart = exactStart
     if IsEmpty(exactEnd):
         self.exactEnd = None
     else:
         self.exactEnd = exactEnd
     if IsEmpty(exactWordIn):
         self.exactWordIns = None
     else:
         if isinstance(exactWordIns, str):
             self.exactWordIns = [exactWordIns]
         else:
             self.exactWordIns = exactWordIns
     if exactWordInRule not in Rule.All:
         raise Exception("Invalid exactWordInRule : " +
                         str(exactWordInRule))
     self.exactWordInRule = exactWordInRule
     if IsEmpty(exactIns):
         self.exactIns = None
     else:
         if isinstance(exactIns, str):
             self.exactIns = [exactIns]
         else:
             self.exactIns = exactIns
     if exactInRule not in Rule.All:
         raise Exception("Invalid exactInRule : " + str(exactInRule))
     self.exactInRule = exactInRule
コード例 #14
0
ファイル: vapor.py プロジェクト: winbotscript/JeBB
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])
コード例 #15
0
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])
コード例 #16
0
ファイル: mocksb.py プロジェクト: winbotscript/JeBB
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])
コード例 #17
0
ファイル: byksw.py プロジェクト: j4p/JeBB
def Byksw(message, options, text=''):
    if IsEmpty(text):
        message.ReplyText("Please specify 'text' argument.")
        return

    vocal_w = 'AaEeOoUu'
    vocal_y = 'Ii'
    ret = ""

    for c in text:
        if c in vocal_w:
            if c.isupper():
                ret += 'W'
            else:
                ret += 'w'
        elif c in vocal_y:
            if c.isupper():
                ret += 'Y'
            else:
                ret += 'y'
        else:
            ret += c

    return CommandResult(type=CommandResultType.done, texts=[ret])
コード例 #18
0
def Space(message, options, text=''):
    #print("SPACE TEXT=%s" % text)
    if not IsEmpty(text):
        return CommandResult(type=CommandResultType.done,
                             texts=[' '.join(list(text.strip()))])
コード例 #19
0
ファイル: twentyfour2.py プロジェクト: winbotscript/JeBB
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)
コード例 #20
0
def SendTemplateList(chatroom, sender):
    GetBuiltinTemplates()
    ret = []
    s2Templates = ['Builtin Templates :']
    global builtinTemplatesByDesc
    for kv in builtinTemplatesByDesc:
        si = '\n' + kv[0] + ' : ' + kv[1]
        s2 = s2Templates[-1] + si
        if len(s2) > 2000:
            s2Templates.append('Builtin Templates :' + si)
        else:
            s2Templates[-1] = s2
    ret = ret + s2Templates
    #for s2 in s2Templates:
    #    chatroom.SendText(s2)

    global customTemplateCount
    if customTemplateCount > 0:
        s2Templates = ['Global Custom Templates :']
        global customTemplatesByDesc
        for kv in customTemplatesByDesc:
            desc = kv[0]
            if IsEmpty(desc):
                desc = 'No description'
            print("desc '%s' kv1 '%s'" % (str(desc), str(kv[1])))
            si = '\n' + desc + ' : ' + kv[1]
            s2 = s2Templates[-1] + si
            if len(s2) > 2000:
                s2Templates.append('Global Custom Templates :' + si)
            else:
                s2Templates[-1] = s2

        #for s2 in s2Templates:
        #    chatroom.SendText(s2)
        ret = ret + s2Templates

    if chatroom.chatroomType != ChatroomType.user:
        global roomCustomTemplates
        rId = chatroom._2id
        if rId is not None and rId in roomCustomTemplates:
            roomTemplates = roomCustomTemplates[rId]
            if roomTemplates.count > 0:
                s2Templates = ['Room Custom Templates :']
                for kv in roomTemplates.byDesc:
                    desc = kv[0]
                    if IsEmpty(desc):
                        desc = 'No description'
                    si = '\n' + desc + ' : ' + kv[1]
                    s2 = s2Templates[-1] + si
                    if len(s2) > 2000:
                        s2Templates.append('Room Custom Templates :' + si)
                    else:
                        s2Templates[-1] = s2

                #for s2 in s2Templates:
                #    chatroom.SendText(s2)
                ret = ret + s2Templates

    if sender is not None:
        global userCustomTemplates
        uId = sender._2id
        if uId is not None and uId in userCustomTemplates:
            userTemplates = userCustomTemplates[uId]
            if userTemplates.count > 0:
                s2Templates = ['User Custom Templates :']
                for kv in userTemplates.byDesc:
                    desc = kv[0]
                    if IsEmpty(desc):
                        desc = 'No description'
                    si = '\n' + desc + ' : ' + kv[1]
                    s2 = s2Templates[-1] + si
                    if len(s2) > 2000:
                        s2Templates.append('User Custom Templates :' + si)
                    else:
                        s2Templates[-1] = s2

                #for s2 in s2Templates:
                #    chatroom.SendText(s2)
                ret = ret + s2Templates
    return CommandResult(texts=ret)
コード例 #21
0
def Meme(message,
         options='',
         text='',
         name=None,
         top=' ',
         bot=' ',
         font='impact',
         img=None,
         desc=None,
         images=None,
         admin=False,
         mode=None,
         params=None,
         activate=None,
         deactivate=None,
         new=None):
    if params is None:
        params = {}
    if text == 'templates':
        return SendTemplateList(message.chatroom, message.sender)
    a, b, c = text.partition(' ')
    if not IsEmpty(c):
        x = None
        if a == 'new':
            x = 'n'
        elif a == 'activate':
            x = 'a'
        elif a == 'deactivate':
            x = 'd'
        if x:
            options = options + x
            params['options'] = options
            text = c.strip()
    if activate:
        name = activate
        options = options + 'a'
        params['options'] = options
    if deactivate:
        name = deactivate
        options = options + 'd'
        params['options'] = options
    if new:
        name = new
        options = options + 'n'
        params['options'] = options
    if 'n' in options or 'a' in options or 'd' in options:
        if IsEmpty(name):
            name = text
        if IsEmpty(name):
            message.ReplyText("[Command(Meme):New] Name can't be empty")
            return CommandResult.Done()
        if 'n' in options:
            if name in invalidNames:
                message.ReplyText("[Command(Meme):New] Name can't be '%s'" %
                                  name)
                return CommandResult.Done()
            return NewMeme(message, options, name, desc, mode, admin, images,
                           params)
        if 'a' in options:
            return Activate(message, options, name, admin=admin)
        return Activate(message, options, name, admin=admin, activate=False)
    if name is None:
        if IsEmpty(text) or not IsEmpty2(top) or not IsEmpty2(
                bot) or not IsEmpty(options):
            name = 'random'
        else:
            name = text.split(' ')[0]
    if IsEmpty(name):
        chatroom.SendText("[Command(Meme)] Name can't be empty.")
        return CommandResult.Done()
    if name == 'custom':
        if IsEmpty2(top) and IsEmpty2(bot):
            message.ReplyText(
                "[Command(Meme)] Just send the image yourself wtf")
            return CommandResult.Done()
        if IsEmpty(img):
            if images is None or len(images) == 0:
                return CommandResult.ExpectImage()
            img = images[0].imgurUrl
            if IsEmpty(img):
                message.ReplyText("Failed to reupload image.")
                return CommandResult.ExpectImage()
    return Send(message.chatroom, message.sender, name, top, bot, font, img)
コード例 #22
0
def IsEmpty2(s):
    return IsEmpty(s.replace('_', ''))
コード例 #23
0
def NewMeme(message,
            options,
            name,
            desc=None,
            mode=None,
            admin=False,
            images=None,
            params=None):
    if mode is None:
        if admin:
            mode = 10
        else:
            mode = 0
            if 'r' in options:
                mode = 1
            elif 's' in options:
                mode = 2
        if params:
            params['mode'] = mode
    if not IsEmpty(images):
        return RegisterMeme(message, options, name, desc, mode, images, params)
    if 'f' not in options:
        cur = message.client.GetCursor()
        if mode == 10:
            cur.Execute('SELECT TRUE FROM CustomMemes WHERE name=%s', (name, ))
            if cur.rowCount > 0:
                message.ReplyText(
                    "[Command(Meme)] Global template named '%s' already exists. If you want to replace, please also provide the 'f' (force) option"
                    % name)
                return CommandResult.Done()
        roomMemeExists = False
        if mode == 0 or mode == 1:
            cur.Execute(
                'SELECT TRUE FROM RoomCustomMemes WHERE name=%s AND rId=%s',
                (name, message.chatroom._2id))
            if cur.rowCount > 0:
                if mode == 0:
                    roomMemeExists = True
                else:
                    message.ReplyText(
                        "[Command(Meme)] Room template named '%s' already exists. If you want to replace, please also provide the 'f' (force) option"
                        % name)
                    return CommandResult.Done()
        userMemeExists = 0
        if not message.sender:
            userMemeExists = 2
        elif mode == 0 or mode == 2:
            cur.Execute(
                'SELECT TRUE FROM UserCustomMemes WHERE name=%s AND uId=%s',
                (name, message.sender._2id))
            if cur.rowCount > 0:
                if mode == 0:
                    userMemeExists = 1
                else:
                    message.ReplyText(
                        "[Command(Meme)] User template named '%s' already exists. If you want to replace, please also provide the 'f' (force) option"
                        % name)
                    return CommandResult.Done()
        if mode == 0:
            if roomMemeExists:
                if userMemeExists == 2:
                    message.ReplyText(
                        "[Command(Meme)] Room template named '%s' already exists. We can't identify you so user template is also not possible. If you want to replace, please also provide the 'f' (force) option"
                        % name)
                    return CommandResult.Done()
                elif userMemeExists == 1:
                    message.ReplyText(
                        "[Command(Meme)] Room template and user template named '%s' already exists. If you want to replace, please also provide the 'f' (force) option"
                        % name)
                    return CommandResult.Done()
                elif userMemeExists == 0:
                    message.ReplyText(
                        "[Command(Meme)] Room template named '%s' already exists. This way, only user template will be registered. If you want to replace the room template too, please also provide the 'f' (force) option"
                        % name)
                    mode = 2
            else:
                if userMemeExists == 2:
                    message.ReplyText(
                        "[Command(Meme)] We can't identify you so user template is not possible. This way, only user template will be registered."
                    )
                    mode = 1
                elif userMemeExists == 1:
                    message.ReplyText(
                        "[Command(Meme)] User template named '%s' already exists. This way, only the room template will be registered. If you want to replace, please also provide the 'f' (force) option"
                        % name)
                    mode = 1
        if params:
            params['mode'] = mode
    return CommandResult.ExpectImage()
コード例 #24
0
ファイル: clap.py プロジェクト: winbotscript/JeBB
def Clap(message, options, text=''):
    if not IsEmpty(text):
        ret = text.replace(' ', ' 👏 ').replace('👏 👏', '👏').replace('👏  👏', '👏')
        return CommandResult(type=CommandResultType.done, texts=[ret])
コード例 #25
0
def GetUrl(name='blb', top='_', bot='_', font='impact', img=None):
    memeUrl = "memegen.link/" + name + "/" + top + "/" + bot + ".jpg?font=" + font
    if not IsEmpty(img):
        memeUrl = memeUrl + "&alt=" + img
    return memeUrl
コード例 #26
0
ファイル: chatrooms.py プロジェクト: winbotscript/JeBB
    def Sync(self, obj2=None):
        if obj2 is None:
            obja = None
            if self.client.hasOA and (not IsEmpty(
                    self.id)) and self.id in self.client._1objectsByLineId:
                obja = self.client._1objectsByLineId[self.id]
            objb = None
            if self.client.hasUser and (not IsEmpty(
                    self.mid)) and self.mid in self.client._1objectsByLineMid:
                objb = self.client._1objectsByLineMid[self.mid]
            if obja is self:
                obj2 = objb
            else:
                obj2 = obja
        if obj2 is self:
            return self
        if obj2 is not None:
            if self.chatroomType != obj2.chatroomType or not isinstance(
                    obj2, Room):
                raise Exception(
                    "[Sync] self and obj2 is not of the same type. id='%s', mid='%s'"
                    % (self.id or obj2.id, self.mid or obj2.mid))
            with Acquire(self.lock, obj2.lock, self.oLock, obj2.oLock,
                         self.uLock, obj2.uLock):
                if not IsEmpty(self.id):
                    obj2.id = self.id
                elif not IsEmpty(obj2.id):
                    self.id = obj2.id
                if not IsEmpty(self.mid):
                    obj2.mid = self.mid
                elif not IsEmpty(obj2.mid):
                    self.mid = obj2.mid
                hasOA = self._2hasOA or obj2._2hasOA
                self.hasOA = hasOA
                obj2.hasOA = hasOA
                self._1hasOA = hasOA
                obj2._1hasOA = hasOA
                self._2hasOA = hasOA
                obj2._2hasOA = hasOA
                hasUser = self._2hasUser or obj2._2hasUser
                self.hasUser = hasUser
                obj2.hasUser = hasUser
                self._1hasUser = hasUser
                obj2._1hasUser = hasUser
                self._2hasUser = hasUser
                obj2._2hasUser = hasUser
                if self.chatroomType == ChatroomType.room:
                    try:
                        with Acquire(self.client.lock):
                            self.client.rooms.remove(obj2)
                    except Exception:
                        pass
                else:
                    try:
                        with Acquire(self.client.lock):
                            self.client.groups.remove(obj2)
                    except Exception:
                        pass
                with Acquire(self.uLock, obj2.uLock):
                    if self.uId:
                        obj2.uId = self.uId
                        u = obj2.uObj
                        if u:
                            u.rObj = self
                    elif obj2.uId:
                        self.uId = obj2.uId
                        u = self.uObj
                        if u:
                            u.rObj = obj2
                if self.uId:
                    with Acquire(self.client.lock):
                        self.client._1objectsByRId[self._2id] = self
                with Acquire(self.oLock, obj2.oLock):
                    if self.time < obj2.time:
                        self.time = obj2.time
                        self._1members = obj2._1members
                        if self.chatroomType == ChatroomType.group:
                            self._1invitees = obj2._1invitees
                            self._1name = obj2._1name
                    else:
                        obj2.time = self.time
                        obj2._1members = self._1members
                        if obj2.chatroomType == ChatroomType.group:
                            obj2._1invitees = self._1invitees
                            obj2._1name = self._1name

        #print("Syncing mid=%s" % self.mid)
        with Acquire(self.client.lock):
            self.client._1objectsUserByMsgId = {
                k: v
                for k, v in self.client._1objectsUserByMsgId.items()
                if v is not obj2 and v is not self
            }
            self.client._1objectsOAByMsgId = {
                k: v
                for k, v in self.client._1objectsOAByMsgId.items()
                if v is not obj2 and v is not self
            }
            self.client._1objectsByLineId[self.id] = self
            self.client._1objectsByLineMid[self.mid] = self
            if self.key and self.key in self.client._1waitingRoom:
                del self.client._1waitingRoom[self.key]
            if obj2:
                if obj2.key and obj2.key in self.client._1waitingRoom:
                    del self.client._1waitingRoom[obj2.key]
                obj2.key = None
            self.key = None
            #print("Syncing mid=%s to DB" % self.mid)
            if self.client.db is not None and not IsEmpty(
                    self.id) and not IsEmpty(self.mid):
                with self.client.GetCursor() as cur:
                    #print("Syncing mid=%s to DB 2" % self.mid)
                    cur.Execute(
                        "SELECT id, lineId, lineMid FROM ChatRooms WHERE lineId=%s OR lineMid=%s ORDER BY hasOA",
                        (self.id, self.mid))
                    fs = cur.FetchAll()
                    lenfs = len(fs)
                    id = None
                    if lenfs == 0:
                        #print("Syncing mid=%s to DB lenfs == 0:" % self.mid)
                        cur.Execute(
                            "INSERT INTO ChatRooms(lineId, lineMid, type, hasOA, hasUser) Values(%s,%s,%s,%s,%s) RETURNING id",
                            (
                                self.id,
                                self.mid,
                                self.chatroomType,
                                self._2hasOA,
                                self._2hasUser,
                            ))
                        id = cur.FetchOne()[0]
                        cur.Commit()
                    elif lenfs > 2:
                        #print("Syncing mid=%s to DB lenfs > 2" % self.mid)
                        raise Exception("LENFS > 2 HOW DID THIS EVEN HAPPEN")
                    else:
                        if lenfs == 2:
                            #print("Syncing mid=%s to DB lenfs == 2" % self.mid)
                            cur.Execute("DELETE FROM Chatrooms WHERE id=%s",
                                        (fs[1][0], ))
                            cur.Commit()
                        f = fs[0]
                        id = f[0]
                        if IsEmpty(f[2]):
                            #print("Syncing mid=%s to DB IsEmpty(f[2])" % self.mid)
                            cur.Execute(
                                "UPDATE ChatRooms SET lineMid=%s, type=%s, hasOA=%s, hasUser=%s WHERE id=%s",
                                (self.mid, self.chatroomType, self._2hasOA,
                                 self._2hasUser, id))
                            cur.Commit()
                        elif IsEmpty(f[1]):
                            #print("Syncing mid=%s to DB IsEmpty(f[1])" % self.mid)
                            cur.Execute(
                                "UPDATE ChatRooms SET lineId=%s, type=%s, hasOA=%s, hasUser=%s WHERE id=%s",
                                (self.id, self.chatroomType, self._2hasOA,
                                 self._2hasUser, id))
                            cur.Commit()
                        else:
                            #print("Syncing mid=%s to DB f[1] and f[2] exists" % self.mid)
                            cur.Execute(
                                "UPDATE ChatRooms SET type=%s, hasOA=%s, hasUser=%s WHERE id=%s",
                                (self.chatroomType, self._2hasOA,
                                 self._2hasUser, id))
                            cur.Commit()

                    self._2id = id
                    cur.Execute("DELETE FROM LineIdByMsgId WHERE lineId=%s",
                                (self.id, ))
                    cur.Commit()
                    cur.Execute("DELETE FROM LineMidByMsgId WHERE lineMid=%s",
                                (self.mid, ))
                    cur.Commit()
コード例 #27
0
ファイル: echo.py プロジェクト: winbotscript/JeBB
def Echo(message, options, text=''):
    if not IsEmpty(text):
        return CommandResult(type=CommandResultType.done, texts=[text])
コード例 #28
0
ファイル: api.py プロジェクト: winbotscript/JeBB
    def login(self, firstLogin=False):
        """Login to LINE server."""
        with self.lock:
            if self.provider == IdentityProvider.LINE:  # LINE
                j = self._1get_json(self.LINE_SESSION_LINE_URL)
            else:  # NAVER
                j = self._1get_json(self.LINE_SESSION_NAVER_URL)
            #self.transport.setCustomHeaders(self._1headers)
            prov = self.provider
            cert = self.certificate
            id = self.id
            password = self.password

            if firstLogin:
                cert = ""
            #if not IsEmpty(self.authToken):
            #pass
            #prov = 0
            #id = None
            #password = None

            if self.authToken is None:
                self._1headers['X-Line-Application'] = self.client.loginApp
                self._1client = ThriftClient(self,
                                             self.LINE_HTTP_URL,
                                             protocol=self.LINE_PROTOCOL)
            else:
                self._1headers['X-Line-Application'] = self.client.app
                self._1client = ThriftClient(self,
                                             self.LINE_HTTP_IN_URL,
                                             protocol=self.LINE_PROTOCOL)

            #key = self._1client.getRSAKeyInfo(prov)

            session_key = j['session_key']
            message = encode(
                chr(len(session_key)) + session_key + chr(len(self.id)) +
                self.id + chr(len(self.password)) + self.password, 'utf-8')

            keyname, n, e = j['rsa_key'].split(",")
            pub_key = PublicKey(int(n, 16), int(e, 16))
            en = encrypt(message, pub_key)
            #crypto = str(encode(en, 'hex'), 'utf-8')
            crypto = str(encode(en, 'hex'))

            #message2 = encode(chr(len(key.sessionKey)) + key.sessionKey + chr(len(self.id)) + self.id + chr(len(self.password)) + self.password, 'utf-8')
            #pub_key2 = PublicKey(int(key.nvalue,16), int(key.evalue,16))
            #en2 = encrypt(message2, pub_key2)
            #crypto2 = str(encode(en2, 'hex'))

            #print("KEYNAME " + str(keyname))
            #print("CRYPTO " + str(crypto))
            #print("KEYNM " + str(key.keynm))
            #print("CRYPTO2 " + str(crypto2))

            #print ("LOGGING IN HEADERS " + str(self._1headers))
            #msg = self._1client.loginWithIdentityCredential(prov, id, password, True, self.ip, self.com_name, cert)
            #msg = self._1client.loginWithIdentityCredentialForCertificate(prov, id, password, True, self.ip, self.com_name, cert)
            msg = self._1client.loginWithIdentityCredentialForCertificate(
                prov, keyname, crypto, True, self.ip, self.com_name, cert)
            #msg = self._1client.loginWithIdentityCredentialForCertificate(prov, key.keynm, crypto2, True, self.ip, self.com_name, cert)
            #msg = self._1client.loginWithIdentityCredentialForCertificate(id, password, keyname, crypto, True, self.ip, self.com_name, prov, cert)
            #msg = self._1client.loginWithIdentityCredentialForCertificate(id, password, key.keynm, crypto2, True, self.ip, self.com_name, prov, cert)

            if msg.type == 1:
                if not IsEmpty(msg.certificate):
                    self.certificate = msg.certificate
                self.authToken = self._1headers[
                    'X-Line-Access'] = msg.authToken
            elif msg.type == 2:
                msg = "require QR code"
                raise Exception(msg)
            elif msg.type == 3:
                self.verifier = self._1headers['X-Line-Access'] = msg.verifier
                pinCode = str(msg.pinCode)
                print("VERIFIER " + str(self.verifier))
                print("PINCODE " + pinCode)
                return pinCode
                self.resumeLogin()

                #raise Exception("Code is removed because of the request of LINE corporation")
            elif not (msg.authToken and msg.authToken.strip()):
                self.authToken = self._1headers[
                    'X-Line-Access'] = msg.authToken
コード例 #29
0
ファイル: twentyfour.py プロジェクト: winbotscript/JeBB
def IsValid(text):
    if not IsEmpty(text):
        c = text[0]
        return c == '(' or c.isdigit()
    return False
コード例 #30
0
ファイル: chatrooms.py プロジェクト: winbotscript/JeBB
 def _1hasUser(self):
     #with Acquire(self.lock):
     return not IsEmpty(self.mid)