Example #1
0
def arriscarPalavra2(chat_id, u_id, u_name, message_id, text):
    l = c.getLanguage(chat_id)
    bds.setArriscarBlock(chat_id, False)
    rpl = []
    palavra = bds.getPalavra(chat_id)
    if bds.checkPalavra(chat_id, u_id, text): #Jogador acertou o chute e venceu. O jogo acaba.
        keyboard = c.makeKb(c.getKb(chat_id, 'main')[0], resize_keyboard = True)
        rpl.append(c.toDict(chat_id, l.venceu(u_name) + '\n' + l.googleMsg(palavra), replyMarkup = keyboard))
        #rpl.append(c.toDict(chat_id, l.googleMsg(palavra)))
        return rpl
    else: #Jogador errou o chute
        rm = bds.rmPlayer(chat_id, u_id, message_id)
        if rm == True: #Jogador não era Adm, nada acontece.
            rpl.append(c.toDict(chat_id, l.perdeu(u_name), replyTo = message_id, replyMarkup = c.makeKbh(True, selective = True)))
            rpl.append(nextRound(chat_id))
            return rpl
        elif rm == 'setAdm': #Jogador era Adm e o Adm será passado para outro
            adm = bds.getAdm(chat_id)
            rpl.append(c.toDict(chat_id, l.perdeu(u_name) + '\n' + l.novoAdmMsg(adm[1]), replyTo = message_id, replyMarkup = c.makeKbh(True, selective = True)))
            #rpl.append(c.toDict(chat_id, l.novoAdmMsg(adm[1])))
            rpl.append(nextRound(chat_id))
            return rpl
        else: #O jogo acaba
            keyboard = c.makeKb(c.getKb(chat_id, 'main')[0], resize_keyboard = True)
            return [c.toDict(chat_id, l.perdeu(u_name)+'\n'+ l.gameover_msg, replyMarkup = keyboard)]
Example #2
0
def cancelarJogo(chat_id, u_id):
    l = c.getLanguage(chat_id)
    if bds.checkAdm(chat_id, u_id):
        bds.delGame(chat_id)
        keyboard = c.makeKb(c.getKb(chat_id, 'main')[0], resize_keyboard = True)
        return [c.toDict(chat_id, l.cancelar_jogo_msg, replyMarkup = keyboard)]
    return [c.toDict(chat_id, l.cantdo_msg)]
Example #3
0
def fecharJogo(chat_id, u_id, message_id, date):
    l = c.getLanguage(chat_id)
    rpl = []
    if bds.checkAdm(chat_id, u_id):
        bds.setPreGame(chat_id, False)
        bds.setInGame(chat_id, True)
        lista = bds.getCats(chat_id)
        if ((len(lista) == 0) or (0 in lista)):
            categoria = randint(0, (len(l.palavras)-1))
        else:
            cat = randint(0, len(lista)-1)
            categoria = lista[cat]-1
        palavra = randint(1, (len(l.palavras[categoria])-1))
        palavra = l.palavras[categoria][palavra].decode('utf-8')
        categoria = l.palavras[categoria][0]
        mascara = bds.setCP(chat_id, categoria, palavra)
        vidas = bds.setVidas(chat_id)
        bds.shufflePlayers(chat_id, date)
        u_names = bds.getPlayers(chat_id)[1]
        message_ids = bds.getPlayers(chat_id)[2]
        ordem = ''
        for i in range(len(u_names)):
            ordem = ordem+u_names[i]+'\n'
        kb = c.makeKb(c.getKb(chat_id, 'main')[0], resize_keyboard = True, selective = True)
        rpl.append(c.toDict(chat_id, l.close_game_msg, replyMarkup = c.makeKbh(True)))
        rpl.append(c.toDict(chat_id, ordem + '\n' + l.categoria_msg+categoria +
                                    '\n' + l.palavra_msg+mascara + '\n' +  
                                    l.vidas_msg+g.vidasEmoji(chat_id),
                                    replyTo = message_ids[0], replyMarkup = kb))
        """rpl.append(c.toDict(chat_id, l.categoria_msg+categoria))
        rpl.append(c.toDict(chat_id, l.palavra_msg+mascara))
        rpl.append(c.toDict(chat_id, l.vidas_msg+g.vidasEmoji(chat_id)))"""
        return rpl
    return [c.toDict(chat_id, l.cantdo_msg)]
Example #4
0
def cancelarJogo(chat_id, u_id):
    l = c.getLanguage(chat_id)
    if bds.checkAdm(chat_id, u_id):
        bds.delGame(chat_id)
        keyboard = c.makeKb(c.getKb(chat_id, 'main')[0], resize_keyboard = True)
        return [c.toDict(chat_id, l.cancelar_jogo_msg, replyMarkup = keyboard)]
    return [c.toDict(chat_id, l.cantdo_msg)]
Example #5
0
def chutarLetra(chat_id, u_id, u_name, message_id, letra):
    l = c.getLanguage(chat_id)
    r = bds.checkLetra(chat_id, u_id, letra)
    #print r
    rpl = []
    if r == True:  #Se acertou a letra
        rpl.append(
            c.toDict(chat_id,
                     l.acertou_letra_msg,
                     replyTo=message_id,
                     replyMarkup=c.makeKbh(True, selective=True)))
        rpl.append(nextRound(chat_id))
    elif r == 2:  #Se a letra já foi chutada
        rpl.append(c.toDict(chat_id, l.jachutada_msg))
    elif type(r) == type("str"):
        rpl = arriscarPalavra2(chat_id, u_id, u_name, message_id, r)
    else:  #Se errou a letra
        rpl.append(
            c.toDict(chat_id,
                     l.errou_letra_msg,
                     replyTo=message_id,
                     replyMarkup=c.makeKbh(True, selective=True)))
        vida = bds.menosVida(chat_id)
        if vida == True:  #Se acabou as vidas
            keyboard = c.makeKb(c.getKb(chat_id, 'main')[0],
                                resize_keyboard=True)
            rpl.append(c.toDict(chat_id, l.gameover_msg, replyMarkup=keyboard))
        elif vida == 2:  #Se resta somente uma vida
            rpl.append(c.toDict(chat_id, l.umavida_msg))
            rpl.append(nextRound(chat_id))
        else:
            rpl.append(nextRound(chat_id))
    return rpl
Example #6
0
def entrar(chat_id, u_id, u_name, message_id):
    l = c.getLanguage(chat_id)
    if bds.addPlayer(chat_id, u_id, u_name, message_id):
        kb = c.makeKb(c.getKb(chat_id, 'main', u_id=u_id)[0],
                      selective=True,
                      resize_keyboard=True)
        return [
            c.toDict(chat_id,
                     l.entrarMsg(u_name),
                     replyTo=message_id,
                     replyMarkup=kb)
        ]
    return [c.toDict(chat_id, l.esta_dentro_msg)]
Example #7
0
def nextRound(chat_id):
    l = c.getLanguage(chat_id)
    bds.roundPlus(chat_id)
    players = bds.getPlayers(chat_id)
    aRound = bds.getRound(chat_id)
    vidas = vidasEmoji(chat_id)
    categoria = bds.getCategoria(chat_id)
    keyboard = c.makeKb(c.getKb(chat_id, 'main')[0], resize_keyboard = True, selective = True)
    return c.toDict(chat_id, (categoria+'\n\n'+bds.getMascara(chat_id)+'\n\n'+l.vidas_msg+vidas+'\n'+l.nextPlayer(players[1][aRound])), replyTo = players[2][aRound], replyMarkup = keyboard)
Example #8
0
def arriscarPalavra1(chat_id, u_id, message_id):
    l = c.getLanguage(chat_id)
    bds.setArriscarBlock(chat_id, True)
    return [
        c.toDict(chat_id,
                 l.arriscar_msg,
                 replyTo=message_id,
                 replyMarkup=c.makeFr(True, selective=True))
    ]
Example #9
0
def sair(chat_id, u_id, u_name, message_id):
    aux = bds.rmPlayer(chat_id, u_id, message_id)
    l = c.getLanguage(chat_id)
    if aux == False:
        kb = c.makeKb(c.getKb(chat_id, 'main')[0], resize_keyboard = True)
        return [c.toDict(chat_id, l.sem_jogador_msg, replyMarkup = kb)]
    elif aux == 'setAdm':
        rpl = []
        pl = bds.getPlayers(chat_id)
        kb = c.makeKb(c.getKb(chat_id, 'main', u_id = u_id)[0], selective = True, resize_keyboard = True)
        rpl.append(c.toDict(chat_id, l.playerQuitMsg(u_name), replyTo = message_id, replyMarkup = kb))
        kb = c.makeKb(c.getKb(chat_id,'main')[1], resize_keyboard = True, selective = True)
        rpl.append(c.toDict(chat_id, l.novoAdmMsg(pl[1][0]), replyTo = pl[2][0], replyMarkup = kb))
        return rpl
    elif aux == True:
        kb = c.makeKb(c.getKb(chat_id,'main',u_id = u_id)[0], selective = True, resize_keyboard = True)
        return [c.toDict(chat_id, l.playerQuitMsg(u_name), replyTo = message_id, replyMarkup = kb)]
    elif aux == 'semPlayer':
        return [c.toDict(chat_id, l.is_out_msg)]
Example #10
0
def categorias(chat_id, u_id, message_id):
    l = c.getLanguage(chat_id)
    if bds.checkAdm(chat_id, u_id):
        bds.setCategorias(chat_id, True)
    return [
        c.toDict(chat_id,
                 l.cat_msg,
                 replyTo=message_id,
                 replyMarkup=c.makeFr(True, selective=True))
    ]
Example #11
0
def arriscarPalavra2(chat_id, u_id, u_name, message_id, text):
    l = c.getLanguage(chat_id)
    bds.setArriscarBlock(chat_id, False)
    rpl = []
    palavra = bds.getPalavra(chat_id)
    if bds.checkPalavra(
            chat_id, u_id,
            text):  #Jogador acertou o chute e venceu. O jogo acaba.
        keyboard = c.makeKb(c.getKb(chat_id, 'main')[0], resize_keyboard=True)
        rpl.append(
            c.toDict(chat_id,
                     l.venceu(u_name) + '\n' + l.googleMsg(palavra),
                     replyMarkup=keyboard))
        #rpl.append(c.toDict(chat_id, l.googleMsg(palavra)))
        return rpl
    else:  #Jogador errou o chute
        rm = bds.rmPlayer(chat_id, u_id, message_id)
        if rm == True:  #Jogador não era Adm, nada acontece.
            rpl.append(
                c.toDict(chat_id,
                         l.perdeu(u_name),
                         replyTo=message_id,
                         replyMarkup=c.makeKbh(True, selective=True)))
            rpl.append(nextRound(chat_id))
            return rpl
        elif rm == 'setAdm':  #Jogador era Adm e o Adm será passado para outro
            adm = bds.getAdm(chat_id)
            rpl.append(
                c.toDict(chat_id,
                         l.perdeu(u_name) + '\n' + l.novoAdmMsg(adm[1]),
                         replyTo=message_id,
                         replyMarkup=c.makeKbh(True, selective=True)))
            #rpl.append(c.toDict(chat_id, l.novoAdmMsg(adm[1])))
            rpl.append(nextRound(chat_id))
            return rpl
        else:  #O jogo acaba
            keyboard = c.makeKb(c.getKb(chat_id, 'main')[0],
                                resize_keyboard=True)
            return [
                c.toDict(chat_id,
                         l.perdeu(u_name) + '\n' + l.gameover_msg,
                         replyMarkup=keyboard)
            ]
Example #12
0
def sair(chat_id, u_id, u_name, message_id):
    aux = bds.rmPlayer(chat_id, u_id, message_id)
    l = c.getLanguage(chat_id)
    if aux == False:
        kb = c.makeKb(c.getKb(chat_id, 'main')[0], resize_keyboard = True)
        return [c.toDict(chat_id, l.sem_jogador_msg, replyMarkup = kb)]
    elif aux == 'setAdm':
        rpl = []
        pl = bds.getPlayers(chat_id)
        kb = c.makeKb(c.getKb(chat_id, 'main', u_id = u_id)[0], selective = True, resize_keyboard = True)
        rpl.append(c.toDict(chat_id, l.playerQuitMsg(u_name), replyTo = message_id, replyMarkup = kb))
        kb = c.makeKb(c.getKb(chat_id,'main')[1], resize_keyboard = True, selective = True)
        rpl.append(c.toDict(chat_id, l.novoAdmMsg(pl[1][0]), replyTo = pl[2][0], replyMarkup = kb))
        return rpl
    elif aux == True:
        kb = c.makeKb(c.getKb(chat_id,'main',u_id = u_id)[0], selective = True, resize_keyboard = True)
        return [c.toDict(chat_id, l.playerQuitMsg(u_name), replyTo = message_id, replyMarkup = kb)]
    elif aux == 'semPlayer':
        return [c.toDict(chat_id, l.is_out_msg)]
Example #13
0
def setCategorias(chat_id, text, message_id, u_id):
    l = c.getLanguage(chat_id)
    cats = []
    text = text.split(' ')
    try:
        for i in range(len(text)):
            if ((int(text[i]) <= len(l.palavras)) and (int(text[i]) >= 0) and (int(text[i]) not in cats)): #Tratamento de macacagem
                cats.append(int(text[i]))
            else:
                int('a') # T_T
    except Exception, e: #Caso existam elementos diferentes de numeros
        return [c.toDict(chat_id, l.cat_erro_msg, replyTo = message_id, replyMarkup = c.makeFr(True, selective = True))]
Example #14
0
def setCategorias(chat_id, text, message_id, u_id):
    l = c.getLanguage(chat_id)
    cats = []
    text = text.split(' ')
    try:
        for i in range(len(text)):
            if ((int(text[i]) <= len(l.palavras)) and (int(text[i]) >= 0) and (int(text[i]) not in cats)): #Tratamento de macacagem
                cats.append(int(text[i]))
            else:
                int('a') # T_T
    except Exception, e: #Caso existam elementos diferentes de numeros
        return [c.toDict(chat_id, l.cat_erro_msg, replyTo = message_id, replyMarkup = c.makeFr(True, selective = True))]
Example #15
0
def chutarLetra(chat_id, u_id, message_id, letra):
    l = c.getLanguage(chat_id)
    r = bds.checkLetra(chat_id, u_id, letra)
    rpl = []
    if r == True: #Se acertou a letra
        rpl.append(c.toDict(chat_id, l.acertou_letra_msg, replyTo = message_id, replyMarkup = c.makeKbh(True, selective = True)))
        rpl.append(nextRound(chat_id))
    elif r == 2: #Se a letra já foi chutada
        rpl.append(c.toDict(chat_id, l.jachutada_msg))
    else: #Se errou a letra
        rpl.append(c.toDict(chat_id, l.errou_letra_msg, replyTo = message_id, replyMarkup = c.makeKbh(True, selective = True)))
        vida = bds.menosVida(chat_id)
        if vida == True: #Se acabou as vidas
            keyboard = c.makeKb(c.getKb(chat_id, 'main')[0], resize_keyboard = True)
            rpl.append(c.toDict(chat_id, l.gameover_msg, replyMarkup = keyboard))
        elif vida == 2: #Se resta somente uma vida
            rpl.append(c.toDict(chat_id, l.umavida_msg))
            rpl.append(nextRound(chat_id))
        else:
            rpl.append(nextRound(chat_id))
    return rpl
Example #16
0
def arriscarPalavra2(chat_id, u_id, u_name, message_id, text):
    l = c.getLanguage(chat_id)
    bds.setArriscarBlock(chat_id, False)
    if bds.checkPalavra(chat_id, u_id, text):
        keyboard = c.makeKb(c.getKb(chat_id, 'main')[0], resize_keyboard = True)
        return [c.toDict(chat_id, l.venceu(u_name), replyMarkup = keyboard)]
    else:
        rm = bds.rmPlayer(chat_id, u_id, message_id)
        if rm == True:
            rpl = []
            rpl.append(c.toDict(chat_id, l.perdeu(u_name), replyTo = message_id, replyMarkup = c.makeKbh(True, selective = True)))
            rpl.append(nextRound(chat_id))
            return rpl
        elif rm == 'setAdm':
            rpl = []
            adm = bds.getAdm(chat_id)
            rpl.append(c.toDict(chat_id, l.perdeu(u_name), replyTo = message_id, replyMarkup = c.makeKbh(True, selective = True)))
            rpl.append(c.toDict(chat_id, l.novoAdmMsg(adm[1])))
            rpl.append(nextRound(chat_id))
            return rpl
        else:
            keyboard = c.makeKb(c.getKb(chat_id, 'main')[0], resize_keyboard = True)
            return [c.toDict(chat_id, l.perdeu(u_name)+'\n'+ l.gameover_msg, replyMarkup = keyboard)]
Example #17
0
def nextRound(chat_id):
    l = c.getLanguage(chat_id)
    bds.roundPlus(chat_id)
    players = bds.getPlayers(chat_id)
    aRound = bds.getRound(chat_id)
    vidas = vidasEmoji(chat_id)
    categoria = bds.getCategoria(chat_id)
    keyboard = c.makeKb(c.getKb(chat_id, 'main')[0],
                        resize_keyboard=True,
                        selective=True)
    return c.toDict(
        chat_id,
        (categoria + '\n\n' + bds.getMascara(chat_id) + '\n\n' + l.vidas_msg +
         vidas + '\n' + l.nextPlayer(players[1][aRound])),
        replyTo=players[2][aRound],
        replyMarkup=keyboard)
Example #18
0
def arriscarPalavra1(chat_id, u_id, message_id):
    l = c.getLanguage(chat_id)
    bds.setArriscarBlock(chat_id, True)
    return [c.toDict(chat_id, l.arriscar_msg, replyTo = message_id, replyMarkup = c.makeFr(True, selective = True))]
Example #19
0
def setCategorias(chat_id, text, message_id, u_id):
    l = c.getLanguage(chat_id)
    cats = []
    text = text.split(' ')
    try:
        for i in range(len(text)):
            if ((int(text[i]) <= len(l.palavras)) and (int(text[i]) >= 0) and (int(text[i]) not in cats)): #Tratamento de macacagem
                cats.append(int(text[i]))
            else:
                int('a') # T_T
    except Exception, e: #Caso existam elementos diferentes de numeros
        return [c.toDict(chat_id, l.cat_erro_msg, replyTo = message_id, replyMarkup = c.makeFr(True, selective = True))]

    bds.setCats(chat_id,cats)
    kb = c.makeKb(c.getKb(chat_id,'main',u_id = u_id)[1], selective = True, resize_keyboard = True)
    return [c.toDict(chat_id, l.categorias_msg, replyTo = message_id, replyMarkup = kb)]



def entrar(chat_id, u_id, u_name, message_id):
    l = c.getLanguage(chat_id)
    if bds.addPlayer(chat_id, u_id, u_name, message_id):
        kb = c.makeKb(c.getKb(chat_id,'main',u_id = u_id)[0], selective = True, resize_keyboard = True)
        return [c.toDict(chat_id, l.entrarMsg(u_name), replyTo = message_id, replyMarkup = kb )]
    return [c.toDict(chat_id, l.esta_dentro_msg)]

def sair(chat_id, u_id, u_name, message_id):
    aux = bds.rmPlayer(chat_id, u_id, message_id)
    l = c.getLanguage(chat_id)
    if aux == False:
        kb = c.makeKb(c.getKb(chat_id, 'main')[0], resize_keyboard = True)
Example #20
0
    def post(self):
        urlfetch.set_default_fetch_deadline(60)
        body = json.loads(self.request.body)
        logging.info('request body:')
        logging.info(body)
        self.response.write(json.dumps(body))

        #Função que verifica se o forca_bot foi excluido ou se ele existe no BD
        def verifyBot(left_chat_participant = None):
            if left_chat_participant:
                first_name = left_chat_participant['first_name'].encode('utf-8')
                if first_name == 'The Hangman':
                    bds.delChat(chat_id)
                    return
            return

        #Dados que recebemos do telegram
        update_id = body['update_id']
        message = body.get('message') if body.get('message') else body.get('edited_message')
        if not message:
            return
        message_id = str(message.get('message_id')).encode('utf-8')
        left_chat_participant = message.get('left_chat_member')
        new_chat_participant = message.get('new_chat_member')
        group_chat_created = message.get('group_chat_created')
        date = message.get('date')
        text = message.get('text').encode('utf-8') if message.get('text') else message.get('text')
        if text:
            #if text.startswith('@ccuem_bot'):
            #    text = text[11:]
            if text.startswith('@PlayHangmanBot'):
                text = text[15:]
            if not text.startswith('/admin'):
                text = text.lower()
        fr = message.get('from')
        chat = message['chat']
        chat_id = str(chat['id'])
        user_id = message['from']
        u_id = str(user_id.get('id')).encode('utf-8')
        u_name = user_id.get('first_name').encode('utf-8')
        bds.checkChat(chat_id)

        #'Chama' a verificação.
        if left_chat_participant:
            verifyBot(left_chat_participant = left_chat_participant)

        if not text:
            logging.info('no text')
            return

        #Função que envia o dict para o Telegram
        def reply(dict = None):
            if dict:
                resp = urllib2.urlopen(BASE_URL + 'sendMessage', urllib.urlencode(dict)).read()
            else:
                logging.error('no msg or img specified')
                resp = None
            logging.info('send response:')
            logging.info(resp)

        #Lê as configurações
        def getLanguage(chat_id):
            s = bds.getSettings(chat_id) #Classe settings
            if s:
                if s.language == 'ptBR':
                    import ptBR as l
                    return l
                elif s.language == 'enUS':
                    import enUS as l
                    return l
                elif s.language == 'hbIL':
                    import hbIL as l
                    return l
            else:
                bds.checkChat(chat_id)
                s = bds.getSettings(chat_id) #Classe settings
                if s.language == 'ptBR':
                    import ptBR as l
                    return l
                elif s.language == 'enUS':
                    import enUS as l
                    return l
                elif s.language == 'hbIL':
                    import hbIL as l
                    return l
                return


        #Aqui começa a lógica principal
        l = getLanguage(chat_id)
        s = bds.getSettings(chat_id)
        ab = bds.getArriscarBlock(chat_id)
        shout = bds.getShout()
        first = bds.getFirstWelcome(chat_id)[0]
        rpl = [c.toDict(chat_id, l.sorry_msg)]

        text = '/start' if text == l.ligar.lower() else text #Tratamento para o caso do /start
        text = l.ajuda.lower() if text.startswith('/help') else text
        text = l.desligar.lower() if text.startswith('/stop') else text
        if shout:
            bds.checkChatBd(shout[0])
            try:
                reply(c.toDict(shout[0], shout[1].encode('utf-8')))
            except Exception, e:
                logging.info((str(e) + ' = ' + shout[0].encode('utf-8')))
                if (str(e) == "HTTP Error 403: Forbidden"):
                    bds.delChat(shout[0])
                    bds.lessPos()
                    reply(c.toDict('-27626712', ('Chat ' + shout[0].encode('utf-8') + ' excluído')))
                else:
                    time.sleep(0.5)
                    try:
                        reply(c.toDict(shout[0], shout[1].encode('utf-8')))
                    except Exception, e:
                        print(e)
Example #21
0
                    bds.delChat(shout[0])
                    bds.lessPos()
                    reply(c.toDict('-27626712', ('Chat ' + shout[0].encode('utf-8') + ' excluído')))
                else:
                    time.sleep(0.5)
                    try:
                        reply(c.toDict(shout[0], shout[1].encode('utf-8')))
                    except Exception, e:
                        print(e)

        if (u_id in creators) and (text.startswith('/admin')): #Funções especiais dos criadores do bot
            if text.startswith('/admindelchat'):
                chat = text[14:]
                if len(chat) > 0:
                    if bds.delChat(chat):
                        rpl = [c.toDict(chat_id, 'Chat '+chat+' deletado')]
                    else:
                        rpl = [c.toDict(chat_id, 'Chat '+chat+' não existe')]
            elif text.startswith('/adminsetshout'):
                text = text[15  :]
                bds.setShout(text)
                rpl = [c.toDict(chat_id, 'Mensagem sendo transmitida!')]
            elif text.startswith('/admingetshout'):
                if shout:
                    rpl = [c.toDict(chat_id, 'Mensagem:\n' + shout[1].encode('utf-8') + '\n\nRestantes: ' + str(shout[2] + 1))]
                else:
                    rpl = [c.toDict(chat_id, 'Não há mensagem sendo transmitida')]
            elif text.startswith('/admindelshout'):
                bds.delShout()
                rpl = [c.toDict(chat_id, 'Mensagem apagada')]
            elif text.startswith('/admingetdadoschat'):
Example #22
0
def setCategorias(chat_id, text, message_id, u_id):
    l = c.getLanguage(chat_id)
    cats = []
    text = text.split(' ')
    try:
        for i in range(len(text)):
            if ((int(text[i]) <= len(l.palavras)) and (int(text[i]) >= 0) and (int(text[i]) not in cats)): #Tratamento de macacagem
                cats.append(int(text[i]))
            else:
                int('a') # T_T
    except Exception, e: #Caso existam elementos diferentes de numeros
        return [c.toDict(chat_id, l.cat_erro_msg, replyTo = message_id, replyMarkup = c.makeFr(True, selective = True))]

    bds.setCats(chat_id,cats)
    kb = c.makeKb(c.getKb(chat_id,'main',u_id = u_id)[1], selective = True, resize_keyboard = True)
    return [c.toDict(chat_id, l.categorias_msg, replyTo = message_id, replyMarkup = kb)]



def entrar(chat_id, u_id, u_name, message_id):
    l = c.getLanguage(chat_id)
    if bds.addPlayer(chat_id, u_id, u_name, message_id):
        kb = c.makeKb(c.getKb(chat_id,'main',u_id = u_id)[0], selective = True, resize_keyboard = True)
        return [c.toDict(chat_id, l.entrarMsg(u_name), replyTo = message_id, replyMarkup = kb )]
    return [c.toDict(chat_id, l.esta_dentro_msg)]

def sair(chat_id, u_id, u_name, message_id):
    aux = bds.rmPlayer(chat_id, u_id, message_id)
    l = c.getLanguage(chat_id)
    if aux == False:
        kb = c.makeKb(c.getKb(chat_id, 'main')[0], resize_keyboard = True)
Example #23
0
    def post(self):
        urlfetch.set_default_fetch_deadline(60)
        body = json.loads(self.request.body)
        logging.info("request body:")
        logging.info(body)
        self.response.write(json.dumps(body))

        # Função que verifica se o forca_bot foi excluido ou se ele existe no BD
        def verifyBot(left_chat_participant=None):
            if left_chat_participant:
                first_name = left_chat_participant["first_name"].encode("utf-8")
                if first_name == "@hangerbot":
                    bds.delChat(chat_id)
                    return
            return

        # Dados que recebemos do telegram
        update_id = body["update_id"]
        message = body["message"]
        message_id = str(message.get("message_id")).encode("utf-8")
        left_chat_participant = message.get("left_chat_participant")
        new_chat_participant = message.get("new_chat_participant")
        group_chat_created = message.get("group_chat_created")
        date = message.get("date")
        text = message.get("text").encode("utf-8").lower() if message.get("text") else message.get("text")
        fr = message.get("from")
        chat = message["chat"]
        chat_id = str(chat["id"])
        user_id = message["from"]
        u_id = str(user_id.get("id")).encode("utf-8")
        u_name = user_id.get("first_name").encode("utf-8")

        #'Chama' a verificação
        if left_chat_participant:
            verifyBot(left_chat_participant=left_chat_participant)

        if not text:
            logging.info("no text")
            return

        # Função que envia o dict para o Telegram
        def reply(dict=None):
            if dict:
                resp = urllib2.urlopen(BASE_URL + "sendMessage", urllib.urlencode(dict)).read()
            else:
                logging.error("no msg or img specified")
                resp = None
            logging.info("send response:")
            logging.info(resp)

        # Lê as configurações
        def getLanguage(chat_id):
            s = bds.getSettings(chat_id)  # Classe settings
            if s:
                if s.language == "ptBR":
                    import ptBR as l

                    return l
                elif s.language == "enUS":
                    import enUS as l

                    return l
            else:
                bds.checkChat(chat_id)
                s = bds.getSettings(chat_id)  # Classe settings
                if s.language == "ptBR":
                    import ptBR as l

                    return l
                elif s.language == "enUS":
                    import enUS as l

                    return l
                return

        # Aqui começa a lógica principal
        l = getLanguage(chat_id)
        s = bds.getSettings(chat_id)
        ab = bds.getArriscarBlock(chat_id)
        first = bds.getFirstWelcome(chat_id)[0]
        rpl = [c.toDict(chat_id, "comando não reconhecido")]
        text = "/start" if text == l.ligar.lower() else text  # Tratamento para o caso do /start
        text = l.ajuda.lower() if text.startswith("/help") else text
        text = l.desligar.lower() if text.startswith("/stop") else text
        if text.startswith("@ccuem_bot"):
            text = text[11:]
        if u_id in creators:
            if text.startswith("/delchatadmin"):
                chat = text[14:]
                if len(chat) > 0:
                    if bds.delChat(chat):
                        rpl = [c.toDict(chat_id, "Chat " + chat + "deletado")]
                    rpl = [c.toDict(chat_id, "Chat " + chat + " não existe")]
        if (not s.waiting) or first:
            # comandos que indiferem do estado atual de jogo
            if "/start" in text:
                rpl = c.start(chat_id, u_id, message_id, first)
            elif bds.getEnabled(chat_id):
                if "/kb" in text:
                    rpl = c.kb(chat_id, u_id, message_id)
                elif l.desligar.lower() in text:
                    rpl = c.stop(chat_id)
                elif l.ajuda.lower() in text:
                    rpl = c.ajuda(chat_id)
                elif l.rank.lower() in text:
                    rpl = c.rank(chat_id)
                elif l.config.lower() in text:
                    rpl = c.config(chat_id, message_id)
                elif l.voltar.lower() in text:
                    rpl = c.voltar(chat_id, l.voltar_msg, message_id, u_id)
                elif l.comandos.lower() in text:
                    rpl = c.comandos(chat_id, message_id, u_id)
                # comandos inGame
                elif bds.getInGame(chat_id):
                    check = bds.checkUid(chat_id, u_id)
                    if l.cancelar_jogo.lower() in text:
                        rpl = g.cancelarJogo(chat_id, u_id)
                    elif check == True:
                        if bds.getArriscarBlock(chat_id):
                            rpl = g.arriscarPalavra2(chat_id, u_id, u_name, message_id, text)
                        elif l.arriscar.lower() in text:
                            rpl = g.arriscarPalavra1(chat_id, u_id, message_id)
                        elif (len(text) == 1) or (text.startswith("@ccuemBot")):
                            if text.startswith("@ccuemBot"):
                                text = text[10:]
                            rpl = g.chutarLetra(chat_id, u_id, message_id, text)
                    elif check == "rnd":
                        rpl = [c.toDict(chat_id, l.round_errado_msg)]
                    elif check == "out":
                        rpl = [c.toDict(chat_id, l.fora_msg)]

                # comandos preGame
                elif bds.getPreGame(chat_id):
                    if l.entrar.lower() in text:
                        rpl = p.entrar(chat_id, u_id, u_name, message_id)
                    elif l.sair.lower() in text:
                        rpl = p.sair(chat_id, u_id, u_name, message_id)
                    elif l.fechar_jogo.lower() in text:
                        rpl = p.fecharJogo(chat_id, u_id, message_id)
                    elif l.cancelar_jogo.lower() in text:
                        rpl = p.cancelarJogo(chat_id, u_id)
                # se preGame e inGame == False (vide flowchart)
                elif (not bds.getPreGame(chat_id)) and (not bds.getInGame(chat_id)):
                    if l.novojogo.lower() in text:
                        rpl = c.novojogo(chat_id, u_id, u_name, message_id)
        else:
            if l.ajuda.lower() in text:
                rpl = c.ajuda(chat_id)
            else:
                rpl = c.changeLanguage(chat_id, text, message_id, u_id)
        try:
            for i in range(len(rpl)):
                reply(rpl[i])
        except Exception, e:
            print e
            reply(c.toDict(chat_id, "erro"))
Example #24
0
def categorias(chat_id, u_id, message_id):
    l = c.getLanguage(chat_id)
    if bds.checkAdm(chat_id, u_id):
        bds.setCategorias(chat_id,True)
    return [c.toDict(chat_id, l.cat_msg, replyTo = message_id, replyMarkup = c.makeFr(True, selective = True))]
Example #25
0
    def post(self):
        urlfetch.set_default_fetch_deadline(60)
        body = json.loads(self.request.body)
        logging.info('request body:')
        logging.info(body)
        self.response.write(json.dumps(body))

        #Função que verifica se o forca_bot foi excluido ou se ele existe no BD
        def verifyBot(left_chat_participant = None):
            if left_chat_participant:
                first_name = left_chat_participant['first_name'].encode('utf-8')
                if first_name == 'The Hangman':
                    bds.delChat(chat_id)
                    return
            return

        #Dados que recebemos do telegram
        update_id = body['update_id']
        message = body['message']
        message_id = str(message.get('message_id')).encode('utf-8')
        left_chat_participant = message.get('left_chat_participant')
        new_chat_participant = message.get('new_chat_participant')
        group_chat_created = message.get('group_chat_created')
        date = message.get('date')
        text = message.get('text').encode('utf-8') if message.get('text') else message.get('text')
        if text:
            if not text.startswith('/admin'):
                text = text.lower()
        fr = message.get('from')
        chat = message['chat']
        chat_id = str(chat['id'])
        user_id = message['from']
        u_id = str(user_id.get('id')).encode('utf-8')
        u_name = user_id.get('first_name').encode('utf-8')
        bds.checkChat(chat_id)

        #'Chama' a verificação.
        if left_chat_participant:
            verifyBot(left_chat_participant = left_chat_participant)

        if not text:
            logging.info('no text')
            return

        #Função que envia o dict para o Telegram
        def reply(dict = None):
            if dict:
                resp = urllib2.urlopen(BASE_URL + 'sendMessage', urllib.urlencode(dict)).read()
            else:
                logging.error('no msg or img specified')
                resp = None
            logging.info('send response:')
            logging.info(resp)

        #Lê as configurações
        def getLanguage(chat_id):
            s = bds.getSettings(chat_id) #Classe settings
            if s:
                if s.language == 'ptBR':
                    import ptBR as l
                    return l
                elif s.language == 'enUS':
                    import enUS as l
                    return l
                elif s.language == 'hbIL':
                    import hbIL as l
                    return l
            else:
                bds.checkChat(chat_id)
                s = bds.getSettings(chat_id) #Classe settings
                if s.language == 'ptBR':
                    import ptBR as l
                    return l
                elif s.language == 'enUS':
                    import enUS as l
                    return l
                elif s.language == 'hbIL':
                    import hbIL as l
                    return l
                return


        #Aqui começa a lógica principal
        l = getLanguage(chat_id)
        s = bds.getSettings(chat_id)
        ab = bds.getArriscarBlock(chat_id)
        first = bds.getFirstWelcome(chat_id)[0]
        rpl = [c.toDict(chat_id, l.sorry_msg)]

        text = '/start' if text == l.ligar.lower() else text #Tratamento para o caso do /start
        text = l.ajuda.lower() if text.startswith('/help') else text
        text = l.desligar.lower() if text.startswith('/stop') else text

        if text.startswith('@PlayHangmanBot'):
            text = text[15:]
        if (u_id in creators) and (text.startswith('/admin')): #Funções especiais dos criadores do bot
            if text.startswith('/admindelchat'):
                chat = text[14:]
                if len(chat) > 0:
                    if bds.delChat(chat):
                        rpl = [c.toDict(chat_id, 'Chat '+chat+' deletado')]
                    else:
                        rpl = [c.toDict(chat_id, 'Chat '+chat+' não existe')]
            elif text.startswith('/adminshout'):
                text = text[12:]
                chats = bds.getChats()
                rpl = []
                for i in range(len(chats)):
                    time.sleep(0.1)
                    rpl.append(c.toDict(chats[i], text))
            elif text.startswith('/admingetdadoschat'):
                chat = text[19:]
                if len(chat) > 0:
                    dados = bds.getDadosChat(chat)
                    jogos_dia = bds.getJogosDia(chat, date)
                    if dados:
                        rpl = [c.toDict(chat_id, 'Chat '+str(chat)+'\nJogos: '+ str(dados.games)+'\nJogadores: '+str(len(dados.players))+'\nJogos por dia: '+str(jogos_dia)+'\nTop player: '+dados.topPlayer.u_name.encode('utf-8')+'\n\tScore: '+str(dados.topPlayer.u_score)+'\n\tId: '+str(dados.topPlayer.u_id))]
                    else:
                        rpl = [c.toDict(chat_id, 'Chat '+chat+' não existe')]
            elif text.startswith('/admingetdadosglobais'):
                urlfetch.set_default_fetch_deadline(300)
                resp = bds.getDadosGlobais(date)
                rpl = [c.toDict(chat_id, 'Chats: '+str(resp[0])+'\nJogadores: '+str(resp[1])+'\nJogos por dia: '+str(resp[2])+'\nJogos: '+str(resp[3]))]
        elif (not s.waiting) or first:
            #comandos que indiferem do estado atual de jogo
            if '/start' in text:
                rpl = c.start(chat_id, u_id, first)
            elif bds.getEnabled(chat_id):
                if ('/kb' in text) or (l.att_kb in text):
                    rpl = c.kb(chat_id, u_id, message_id, s.waiting)
                elif l.desligar.lower() in text:
                    rpl = c.stop(chat_id)
                elif l.ajuda.lower() in text:
                    rpl = c.ajuda(chat_id)
                elif l.rank.lower() in text:
                    rpl = c.rank(chat_id)
                elif l.config.lower() in text:
                    rpl = c.config(chat_id, message_id)
                elif l.sobre.lower() in text:
                    rpl = c.sobre(chat_id)
                elif l.voltar.lower() in text:
                    rpl = c.voltar(chat_id, l.voltar_msg, message_id, u_id)
                elif l.comandos.lower() in text:
                    rpl = c.comandos(chat_id, message_id, u_id)
                #comandos inGame
                elif bds.getInGame(chat_id):
                    check = bds.checkUid(chat_id, u_id)
                    if l.cancelar_jogo.lower() in text:
                        rpl = g.cancelarJogo(chat_id, u_id)
                    elif check == True:
                        if bds.getArriscarBlock(chat_id):
                            rpl = g.arriscarPalavra2(chat_id, u_id, u_name, message_id, text)
                        elif l.arriscar.lower() in text:
                            rpl = g.arriscarPalavra1(chat_id, u_id, message_id)
                        elif (len(text) == 1) or (text.startswith('@PlayHangmanBot')):
                            if text.startswith('@PlayHangmanBot'):
                                text = text[10:]
                            rpl = g.chutarLetra(chat_id, u_id, u_name, message_id, text)
                    elif check == 'rnd':
                        rpl = [c.toDict(chat_id, l.round_errado_msg)]
                    elif check == 'out':
                        rpl = [c.toDict(chat_id, l.fora_msg)]

                #comandos preGame
                elif bds.getPreGame(chat_id):
                    if s.categorias and bds.checkAdm(chat_id, u_id):
                        rpl = p.setCategorias(chat_id, text, message_id,u_id)
                    elif l.entrar.lower() in text:
                        rpl = p.entrar(chat_id, u_id, u_name, message_id)
                    elif l.categorias_btn.lower() in text:
                        rpl = p.categorias(chat_id, u_id, message_id)
                    elif l.sair.lower() in text:
                        rpl = p.sair(chat_id, u_id, u_name, message_id)
                    elif l.fechar_jogo.lower() in text:
                        rpl = p.fecharJogo(chat_id, u_id, message_id, date)
                    elif l.cancelar_jogo.lower() in text:
                        rpl = p.cancelarJogo(chat_id, u_id)
                #se preGame e inGame == False (vide flowchart)
                elif (not bds.getPreGame(chat_id)) and (not bds.getInGame(chat_id)):
                    if l.novojogo.lower() in text:
                        rpl = c.novojogo(chat_id, u_id, u_name, message_id)
        else:
            if l.ajuda.lower() in text:
                rpl = c.ajuda(chat_id)
            elif '/kb' in text:
                rpl = c.kb(chat_id, u_id, message_id, s.waiting)
            else:
                rpl = c.changeLanguage(chat_id, text, message_id, u_id)

        error = False
        for i in range(len(rpl)):
                time.sleep(1.5)
                try:
                    reply(rpl[i])
                except Exception, e:
                    print e
                    if (str(e) == "HTTP Error 429: Unknown") and (not error):
                        error = True
                        time.sleep(2)
                        i = i - 1
                    else:
                        try:
                            reply(c.toDict(chat_id, l.error_msg))
                        except Exception, e:
                            print e
                            try:
                                reply(c.toDict(chat_id, 'Fatal error, contact @cristoferoswald or @bcesarg6.'))
                            except Exception, e:
                                print e
Example #26
0
def entrar(chat_id, u_id, u_name, message_id):
    l = c.getLanguage(chat_id)
    if bds.addPlayer(chat_id, u_id, u_name, message_id):
        kb = c.makeKb(c.getKb(chat_id,'main',u_id = u_id)[0], selective = True, resize_keyboard = True)
        return [c.toDict(chat_id, l.entrarMsg(u_name), replyTo = message_id, replyMarkup = kb )]
    return [c.toDict(chat_id, l.esta_dentro_msg)]