def testRazaMultipleTimesInSentence(self): multi_raza_pattern = TextMessageProtocolEntity("/raza pura /raza so", to=self.mock_to) self.assertEqual(self.regex_matcher.message_matches_a_pattern(multi_raza_pattern), True)
def sendMsg(self, text, to=Jid.normalize('447760333610-1485190753')): logging.info('Sent %s to %s', text, to) messageEntity = TextMessageProtocolEntity(text, to=to) self.toLower(messageEntity)
def _on_error(self, jid, *args, **kwargs): self.interface_layer.toLower( TextMessageProtocolEntity("{Feature Not Working}", to=jid))
def wikipedia_query(message, match): query = match.group("query") print("QUERY: " + query) result = wikipedia.summary(str(query), sentences=1) return TextMessageProtocolEntity(result, to=message.getFrom())
def message_send(self, number, content): outgoingMessage = TextMessageProtocolEntity( content, to=self.normalizeJid(number)) self.toLower(outgoingMessage)
def setpath(self, message, match): file_name = match.group("inputw") file = open("/app/storage/menu.txt", "w") file.write(file_name) file.close() return TextMessageProtocolEntity("done", to=message.getFrom())
def test1(self, message, match): number = self.session_db.get(message.getFrom()) return TextMessageProtocolEntity("Stored Number is " + str(number), to=message.getFrom())
def testRollInMiddleOfSentence(self): oh_grande_botosan = TextMessageProtocolEntity("oh grande botosan tesing", to=self.mock_to) self.assertEqual(self.regex_matcher.message_matches_a_pattern(oh_grande_botosan), True)
def testUppercaseOhGran(self): oh_grande_botosan = TextMessageProtocolEntity("Oh GRAN BoToSAN tesing", to=self.mock_to) self.assertEqual(self.regex_matcher.message_matches_a_pattern(oh_grande_botosan), True)
def testSlashRollPattern(self): o_gran_pattern = TextMessageProtocolEntity("o gran botosan cual es el", to=self.mock_to) self.assertEqual(self.regex_matcher.message_matches_a_pattern(o_gran_pattern), True)
def testNoRollPattern(self): false_pattern = TextMessageProtocolEntity("no aparece el sentence", to=self.mock_to) self.assertEqual(self.regex_matcher.message_matches_a_pattern(false_pattern), False)
def testBebanDoesNotShowInSentence(self): no_beban_pattern = TextMessageProtocolEntity("BotoSan insulta a Esteban", to=self.mock_to) self.assertEqual(self.regex_matcher.message_matches_a_pattern(no_beban_pattern), False)
def testBebanMultipleTimesInSentence(self): multi_beban_pattern = TextMessageProtocolEntity( "BotoSan porfavor insulta a Esteban , BotoSan porfavor insulta a Esteban", to=self.mock_to) self.assertEqual(self.regex_matcher.message_matches_a_pattern(multi_beban_pattern), True)
def testBebanInSentence(self): beban_pattern = TextMessageProtocolEntity("Hola, BotoSan porfavor insulta a Esteban pronto", to=self.mock_to) self.assertEqual(self.regex_matcher.message_matches_a_pattern(beban_pattern), True)
def send_message(self, phone, message): entity = TextMessageProtocolEntity(message, to=phone) self.toLower(entity)
def testgrandioso(self): false_pattern = TextMessageProtocolEntity("Testing oh grandioso botosan testing ", to=self.mock_to) self.assertEqual(self.regex_matcher.message_matches_a_pattern(false_pattern), True)
def phone(self, message, match): name = match.group("term") result, pic = phone(name) self.image_sender.send_by_url(jid=message.getFrom(), file_url=pic) return TextMessageProtocolEntity(result, to=message.getFrom())
def testMisericordiosoTestSinRey(self): oh_grande_botosan = TextMessageProtocolEntity("oh misericordioso botosan tesing", to=self.mock_to) self.assertEqual(self.regex_matcher.message_matches_a_pattern(oh_grande_botosan), True)
def setlink(self, message, match): content = match.group("inputw") file = open("/app/storage/link.txt", "r") menu = file.read() file.close() return TextMessageProtocolEntity(cur, to=message.getFrom())
def testAll(self): oh_grande_botosan = TextMessageProtocolEntity("Oh grandioso misericordioso rey BoToSAN tesin", to=self.mock_to) self.assertEqual(self.regex_matcher.message_matches_a_pattern(oh_grande_botosan), True)
def quiz(self, message, match): # Gets a random quiz and store in the sender' session quiz = self._get_quiz() self.session_db.set(message.getFrom(), quiz) return TextMessageProtocolEntity(self._get_quiz_text(quiz), to=message.getFrom())
def _on_error(self, jid, *args, **kwargs): error_message = "{! Sorry, error processing request for [%s]... }" % self.MEDIA_TYPE self.interface_layer.toLower( TextMessageProtocolEntity(error_message, to=jid))
def onMessage(self, messageProtocolEntity): # receipt = OutgoingReceiptProtocolEntity(messageProtocolEntity.getId(), messageProtocolEntity.getFrom(), 'read', messageProtocolEntity.getParticipant()) # self.toLower(receipt) # if messageProtocolEntity.getType() == "text": # if messageProtocolEntity.getBody().startswith("!"): # header = "*=== TARS PokeBot ===*\n\n" # message = header # outgoingMessageProtocolEntity = TextMessageProtocolEntity( # message, # to = messageProtocolEntity.getAuthor()) # self.toLower(outgoingMessageProtocolEntity) conn = sqlite3.connect('database.db') # send receipt otherwise we keep receiving the same message over and over time.sleep(2) receipt = OutgoingReceiptProtocolEntity( messageProtocolEntity.getId(), messageProtocolEntity.getFrom(), 'read', messageProtocolEntity.getParticipant()) self.toLower(receipt) if messageProtocolEntity.getType() == "text": body = "" c = conn.cursor() userNumber = messageProtocolEntity.getAuthor().split('@')[0] c.execute( 'SELECT * FROM Users WHERE number={0}'.format(userNumber)) user = c.fetchone() if user == None: c.execute("INSERT INTO Users ('number') values ('{0}')".format( userNumber)) conn.commit() # print("=============================================================") # print(dir(messageProtocolEntity)) # print("AUTHOR: "+messageProtocolEntity.getAuthor()) # print("FROM: "+messageProtocolEntity.getFrom()) # print("TO: "+str(messageProtocolEntity.getTo()).encode('utf-8')) # print("PARTICIPANT: "+str(messageProtocolEntity.getParticipant()).encode('utf-8')) # print("TYPE: "+messageProtocolEntity.getType()) # print("Isgroup: "+str(messageProtocolEntity.isGroupMessage()).encode('utf-8')) # print("BODY: "+messageProtocolEntity.getBody()) # print("=============================================================") if messageProtocolEntity.getBody().startswith("!"): command = messageProtocolEntity.getBody().split('!')[1] command = command.split(' ') #ações if command[0] == "registrar": #!novaraid <local> <hora> <inimigo> <codigo> if len(command) == 4: c.execute( "SELECT u.* from Users as u WHERE u.number == '{0}'" .format(userNumber)) result = c.fetchone() if len(result) != 0: c.execute( "UPDATE Users SET 'nickname' = '{0}', 'team' = '{1}','level' = '{2}' WHERE Users.number == '{3}'" .format(command[1], command[2], command[3], userNumber)) conn.commit() body = "Você foi registrado com sucesso {0}".format( command[1]) else: body = "Erro, você não está nos conformes" else: body = "Para executar esta ação utilize esta sintaxe: \n!registrar <nickname> <time> <nível>" elif command[0] == "nova": #!novaraid <local> <hora> <inimigo> <codigo> if len(command) == 5: c.execute( "SELECT r.* from Raids as r WHERE r.code == '{0}'". format(command[4])) result = c.fetchall() if len(result) != 0: body = "Uma raid com este código já existe" else: c.execute( "INSERT INTO Raids ('location', 'time', 'enemy', 'code') values ('{0}','{1}','{2}','{3}')" .format(command[1], command[2], command[3], command[4])) conn.commit() body = "Raid cadastrada com sucesso" elif len(command) == 4: code = self.randomword(4) c.execute( "SELECT r.* from Raids as r WHERE r.code == '{0}'". format(code)) result = c.fetchall() if len(result) != 0: code = self.randomword(4) c.execute( "INSERT INTO Raids ('location', 'time', 'enemy', 'code') values ('{0}','{1}','{2}','{3}')" .format(command[1], command[2], command[3], code)) conn.commit() body = "Raid cadastrada com sucesso" else: body = "Para executar esta ação utilize esta sintaxe: \n!novaraid <local> <hora> <inimigo> <codigo>\nSe o código não for fornecido, será gerado um randomico." elif command[0] == "listar": #!listaraids c.execute("SELECT r.* from Raids as r") result = c.fetchall() if len(result) != 0: for row in result: c.execute( "SELECT p.*, u.* from Participants as p JOIN Users as u ON u.number == p.user WHERE p.raid == '{0}'" .format(row[3])) result2 = c.fetchall() body = body + "*({4})* Raid codigo *{0}* contra o *{1}* as *{2}* no(a) *{3}* ".format( row[3], row[2], row[1], row[0], len(result2)) if len(result2) != 0: for row2 in result2: body = body + "->{0} ({1}), {2} level {3}\n".format( row2[4], row2[3], row2[6], row2[7]) body = body + "\n\n" else: body = "Nenhuma raid cadastrada" elif command[0] == "remover": if len(command) == 2: c.execute( "SELECT r.* from Raids as r WHERE r.code == '{0}'". format(command[1])) result = c.fetchall() if len(result) == 0: body = "Esta raid não existe" else: c.execute( "SELECT r.* from Raids as r WHERE r.code == '{0}'" .format(command[1])) # c.execute("SELECT r.* from Raids as r WHERE r.code == '{0}' and r.owner == '{1}'".format(command[1],userNumber)) result = c.fetchall() if len(result) == 0: body = "Apenas o criador pode remover uma lista de raid" else: c.execute( "DELETE FROM Raids WHERE code = '{0}'". format(command[1])) conn.commit() body = "Raid removida com sucesso" else: body = "Para executar esta ação utilize esta sintaxe: \n!removerraid <codigo>" elif command[0] == "entrar": if len(command) == 2: c.execute( "SELECT p.* from Participants as p WHERE p.raid == '{0}' and p.user == '{1}'" .format(command[1], userNumber)) result = c.fetchall() if len(result) != 0: body = "Você já está nesta lista" else: c.execute( "INSERT INTO Participants ('raid', 'user') values ('{0}','{1}')" .format(command[1], userNumber)) conn.commit() body = "Acesso permitido" else: body = "Para executar esta ação utilize esta sintaxe: \n!entrarraid <codigo>" elif command[0] == "sair": if len(command) == 2: c.execute( "SELECT p.* from Participants as p WHERE p.raid == '{0}' and p.user == '{1}'" .format(command[1], userNumber)) result = c.fetchall() if len(result) == 0: body = "Você não está nesta lista" else: c.execute( "DELETE FROM Participants WHERE raid = '{0}' AND user = '******'" .format(command[1], userNumber)) conn.commit() body = "Você foi removido da lista da Raid {0}".format( command[1]) else: body = "Para executar esta ação utilize esta sintaxe: \n!sairraid <codigo>" # Comandos cadastrados no banco else: c.execute( "SELECT c.label as command, r.text as response from Commands as c left join Responses as r on r.command == c.id where c.label == '{0}'" .format(command[0])) dbCommand = c.fetchone() if dbCommand != None: body = dbCommand[1] else: body = "Comando desconhecido" header = "*=== TARS PokeBot ===*\n\n" message = header + body time.sleep(2) outgoingMessageProtocolEntity = TextMessageProtocolEntity( message, to=messageProtocolEntity.getAuthor()) self.toLower(outgoingMessageProtocolEntity) conn.close()
def echo(message, match): return TextMessageProtocolEntity("Eco: %s" % match.group("echo_message"), to=message.getFrom())
def send_text(self, data, to): self.interface_layer.toLower(TextMessageProtocolEntity(data, to=to))
def ping(message, match): if random.randint(0, 10) == 5: pong = "Pong caralho!" else: pong = "Pong!" return TextMessageProtocolEntity(pong, to=message.getFrom())
def onMessage(self, messageProtocolEntity): #send receipt otherwise we keep receiving the same message over and over if True: receipt = OutgoingReceiptProtocolEntity( messageProtocolEntity.getId(), messageProtocolEntity.getFrom(), 'read', messageProtocolEntity.getParticipant()) if messageProtocolEntity.getType() == 'text': number = messageProtocolEntity.getFrom().split('@')[0] if messageProtocolEntity.getBody().find('#') != -1: #Contiene hashtag, puede ser voto isVote = False topicFound = "" cant = 0 for topic in topiclist: if messageProtocolEntity.getBody().lower().find( topic[1].lower()) != -1: isVote = True cant += 1 topicFound = topic[0] if isVote: if cant > 1: #Tiene mas de un voto a la vez outgoingMessageProtocolEntity = TextMessageProtocolEntity( "Sólo puedes votar por 1 participante a la vez. Por favor elige uno y vuelve a intentar", to=messageProtocolEntity.getFrom()) self.toLower(outgoingMessageProtocolEntity) msg = { "name": messageProtocolEntity.getNotify(), "number": number, "text": messageProtocolEntity.getBody(), "vote": False, "date": datetime.datetime.utcnow() } whatsapp.insert_one(msg) else: currentCampaign = campaign.find_one( {"active": True}) if currentCampaign == None: outgoingMessageProtocolEntity = TextMessageProtocolEntity( "❌ CIERRE DE VOTACIÓN. Atento a los resultados en tu televisor y recuerda seguirme en Twitter @ISA_Vertigo. Gracias por participar.", to=messageProtocolEntity.getFrom()) msg = { "name": messageProtocolEntity.getNotify(), "number": number, "text": messageProtocolEntity.getBody(), "vote": False, "date": datetime.datetime.utcnow() } whatsapp.insert_one(msg) else: votes = whatsapp.find_one({ "$and": [{ "number": number }, { "vote": True }, { "campaign": currentCampaign["token"] }] }) if votes == None: outgoingMessageProtocolEntity = TextMessageProtocolEntity( "Hemos recibido tu voto. Gracias por participar 👍🏻", to=messageProtocolEntity.getFrom()) msg = { "name": messageProtocolEntity.getNotify(), "number": number, "text": messageProtocolEntity.getBody(), "vote": True, "campaign": currentCampaign["token"], "topic": topicFound, "date": datetime.datetime.utcnow() } whatsapp.insert_one(msg) else: outgoingMessageProtocolEntity = TextMessageProtocolEntity( "Sólo puedes votar 1 vez. Por favor espera la próxima votación. Tu último voto fue por " + votes["topic"].encode('utf8'), to=messageProtocolEntity.getFrom()) msg = { "name": messageProtocolEntity.getNotify(), "number": number, "text": messageProtocolEntity.getBody(), "vote": False, "date": datetime.datetime.utcnow() } whatsapp.insert_one(msg) self.toLower(outgoingMessageProtocolEntity) else: invitadoslist = ', '.join(invitados) outgoingMessageProtocolEntity = TextMessageProtocolEntity( "Recuerda votar por uno de los invitados: " + invitadoslist, to=messageProtocolEntity.getFrom()) self.toLower(outgoingMessageProtocolEntity) msg = { "name": messageProtocolEntity.getNotify(), "number": number, "text": messageProtocolEntity.getBody(), "vote": False, "date": datetime.datetime.utcnow() } whatsapp.insert_one(msg) else: msg = { "name": messageProtocolEntity.getNotify(), "number": number, "text": messageProtocolEntity.getBody(), "vote": False, "date": datetime.datetime.utcnow() } whatsapp.insert_one(msg) print messageProtocolEntity.getFrom( ), messageProtocolEntity.getBody() elif messageProtocolEntity.getType() == 'media': outgoingMessageProtocolEntity = TextMessageProtocolEntity( "Lo siento, no estamos recibiendo archivos", to=messageProtocolEntity.getFrom()) self.toLower(outgoingMessageProtocolEntity) print 'media message' self.toLower(receipt)
def _sendMessage(self, jid, message): print("Sending message '{}' to {}".format(message, jid)) self.toLower(TextMessageProtocolEntity(message, to=jid)) return Promise.resolve(None)
def sendMessage(self, to, msg): print("sendMessage", to, msg) messageEntity = TextMessageProtocolEntity(msg, to=to) self.toLower(messageEntity)
def testRazaInSentence(self): raza_pattern = TextMessageProtocolEntity("pura /raza", to=self.mock_to) self.assertEqual(self.regex_matcher.message_matches_a_pattern(raza_pattern), True)