Пример #1
0
import os
from webwhatsapi import WhatsAPIDriver
profiledir = os.path.join('.', 'firefox_cache')
if not os.path.exists(profiledir):
    os.makedirs(profiledir)
driver = WhatsAPIDriver(profile=profiledir, headless=True)
print('login')
driver.wait_for_login()
driver.save_firefox_profile(remove_old=False)
print('start')
chat = driver.get_chat_from_phone_number('491xxxxxxxxxx')
driver.send_message_to_id(chat.id, 'This works')
class WhatsAppBot:
    def __init__(self):
        try:
            self.driver = WhatsAPIDriver(username="******")

            # self.driver = webdriver.Chrome()
        except:
            print('There was an error in loading the chrome driver.')
        #     try:
        #         self.driver = webdriver.Firefox()
        #
        #     except:
        #         print('There was an error in loading firefox driver.')
        #         try:
        #             self.driver = webdriver.Safari()
        #
        #         except:
        #             print('There was an error in loading Safari driver.')
        #
        # # self.driver = webdriver.Firefox()
        # self.driver.get("https://web.whatsapp.com/")
        # self.wait = WebDriverWait(self.driver, 600)

    def prepareContacts(self):
        print('prepare contacts called ')

        # self.target = ['tanu jio', 'myself', 'mujahid sir data science python', 'papa', 'bhaijan banglore']
        # self.target = []
        # csv_file = "./MohsinGroups23Sep.csv"
        # df = pd.read_csv(csv_file)
        # for name in df.First:
        #     self.target.append(str(name))

        # In future we will read from google contacts
        #         self.target = []
        #         csv_file = "./MohsinGroups23Sep.csv"		#instead of csv file
        #         df = pd.read_csv(csv_file)
        #         for name in df.First:
        #             self.target.append(str(name))

        # self.target = ['*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**',
        #                '*****@*****.**', '*****@*****.**']
        self.target = ['*****@*****.**']
        # ''*****@*****.**', '*****@*****.**', '*****@*****.**']
        # '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**']

    def send_message(self, string):
        for member in self.target:
            self.driver.send_message_to_id(member, string)

    #     x_arg = '//*[@id="side"]/div[2]/div/label/input'
    #     print(type (self.wait))
    #     group_title = self.wait.until(EC.presence_of_element_located((By.XPATH, x_arg)))
    #
    #     for member in self.target:
    #         group_title.send_keys(member)
    #         print(member)
    #         group_title.send_keys(u'\ue007')
    #         print("group key send done")
    #         message = self.driver.find_elements_by_xpath('//*[@id="main"]/footer/div[1]/div[2]/div/div[2]')[0]
    #         print("message is " + str(message))
    #         message.send_keys(string)
    #         print("send keys done: " + string)
    #         # sendbtn = '//*[@id="main"]/footer/div[1]/div[3]/button'
    #         sendbtn = '/html/body/div/div/div/div[3]/div/footer/div[1]/div[3]/button'
    #         sendbutton = self.wait.until(EC.presence_of_element_located((By.XPATH, sendbtn)))
    #         print("send button found" + str(sendbutton))
    #         sendbutton.click()
    #         print("button clicked")
    #     self.driver.close()

    def fetch_group_participants(self):
        print('fetch_group_participants called')
        participants_chat_ids = []
        participants = self.driver.group_get_participants_ids('*****@*****.**') # this return  a list of dictionaries with key values of the participants
        print(participants)
        for members in participants: # thi is to iterate the list of dictionaries
            participants_chat_ids.append(participants[0]['_serialized']) # fetch only the values(chat ids) related to key "_serialized"
            # print(participants[0]['_serialized'])
            # print(type(participants))

        print(participants_chat_ids)
        print(len(participants_chat_ids))
        return participants_chat_ids # This is our target list which will have chat ids of all the participants in the group
Пример #3
0
import time, json
from webwhatsapi import WhatsAPIDriver
from webwhatsapi.objects.message import Message
from pprint import pprint

driver = WhatsAPIDriver()
print("Waiting for QR")
driver.wait_for_login()

print("Bot started")

with open('data/nomer_pm.json') as data_file:
    numbers = json.load(data_file)

message = "test test test"

i = 0
for number in numbers:
    print('sending to', number)
    driver.send_message_to_id(number, message)
    i += 1

print("============================")
print("=====BLASTING COMPLETE======")
print("============================")
Пример #4
0
						chat_file.write(": ")
						chat_file.write(str(m.content))
						chat_file.write("\n")


						# RTS query
						query_RTS_match = query_RTS_regex.match(str(m.content).lower())
						if query_RTS_match is not None:
							RTS_tally = get_RTS_from_file(NEW_CHATFILE_NAME)
							RTS_message = '*Current RTS tally*\n\n'
							if len(RTS_tally) == 0:
								RTS_message += "It's empty lol"
							else:
								for person, tally in RTS_tally:
									RTS_message += '@' + person + ": " + str(tally) + '\n'
							driver.send_message_to_id(GROUP_ID, RTS_message)

						# Someone got an RTS!
						add_RTS_match = add_RTS_regex.match(str(m.content).lower())
						if add_RTS_match is not None:
							RTS_person = add_RTS_match.group(1)
							RTS_message = '@' + RTS_person + ' Congrats! You got an RTS :D'
							driver.send_message_to_id(GROUP_ID, RTS_message)

						# Help section
						help_match = help_regex.match(str(m.content).lower())
						if help_match is not None:
							driver.send_message_to_id(GROUP_ID, HELP_STRING)

						# But why
						but_why_match = but_why_regex.match(str(m.content).lower())
Пример #5
0
    for contact in driver.get_unread():
        for message in contact.messages:

            ## Celular de quien chatea ##
            # celular_completo = message.sender.id
            # celular = celular_completo[1:celular_completo.find('@')]
            celular_completo = message.sender.id
            celular = celular_completo[1:len(celular_completo)]

            if message.type == 'chat':
                logging.info('Mensaje recibido de :{}'.format(message.sender.id) + ' {}'.format(message.content))

                respuesta = cBotDialogflow.buscaIntent(message.sender.id, message.content.encode('utf-8'))

                logging.info('Respuesta: {}'.format(respuesta))
                driver.send_message_to_id(message.sender.id, respuesta)


                # driver.send_message_to_id(message.sender.id, respuesta)
                # driver.send_message(respuesta)
                # driver.send_message_to_id(message.sender.id, respuesta

            # print(json.dumps(message.get_js_obj(), indent = 4))
            # print 'class', message.__class__.__name__
            # print 'message', message
            # print 'id', message.id
            # print 'type', message.type
            # print 'timestamp', message.timestamp
            # print 'chat_id', message.chat_id
            # print 'sender', message.sender
            # print 'sender.id', message.sender.id
Пример #6
0
                    f = open("safechat_" + message.chat_id['_serialized'] + ".chat.log", "a+")
                    f.write("[ {sender} | {timestamp} ] {content}\n".format(
                        sender=message.sender.get_safe_name(), timestamp=message.timestamp, content=message.safe_content))
                    f.close()

                    if message.sender.id.split("@")[0] == masters_number:
                        print_and_log("Message from master: '{cmd}'.".format(cmd=message.content))
                        if message.content.lower() in COMMANDS:
                            process_command(message.content)
                        else:
                            response(message)
                    elif message.sender.id.split("@")[0] != config('CLIENT_NUMBER'):
                        response(message)
                else:
                    driver.send_message_to_id(
                        message.sender.id, '🤖 - Ainda não entendo mensagens desse \
                            tipo 😔\n\nMas tranquilo! Creio que meus criadores já \
                            estão trabalhando em uma forma de me ensinar ☺')

                # elif message.type == 'image' or message.type == 'video' or message.type == 'document' or message.type == 'audio':
                    # print('-- Media')
                    # print('filename', message.filename)
                    # print('size', message.size)
                    # print('mime', message.mime)
                    # msg_caption = ''
                    # if hasattr(message, 'caption'):
                    #     msg_caption = message.caption
                    #     print('caption', message.caption)
                    # print('client_url', message.client_url)
                    # f = open("chat_" + message.chat_id['_serialized'] + ".chat.log", "a+")
                    # f.write("[ {sender} | {timestamp} ] sent media chat_{id}\{filename} with caption '{caption}'\n".format(sender=message.sender.get_safe_name(
                    # ), timestamp=message.timestamp, id=message.chat_id['_serialized'], filename=message.filename, caption=msg_caption))
Пример #7
0
class Whatsapp(threading.Thread):
    def __init__(self, identifier):
        self.driver = WhatsAPIDriver(loadstyles=True)
        self.identifier = identifier
        self.messagesSent = 0
        self.messageQueue = []
        self.status = {}
        
        print("Waiting for QR")
        try:
            self.driver.wait_for_login()
            super(Whatsapp, self).__init__()
            self.setDaemon(True)
        except Exception as ex:
            print("Error", ex)

        print("New Browser Opened")
        
    def get_chat(self, phone):
        try:
            chat = self.driver.get_chat_from_phone_number(phone)
        except ChatNotFoundError:
            url = self.driver._URL+"/send?phone="+phone
            self.driver.driver.get(url)
            t.sleep(5)
            chat = self.driver.get_chat_from_phone_number(phone)
        return chat

    # Give timeout_after_sent to avoid being suspected as a spammer.
    # Assign high value after multithreading is implemented.
    def send_whatsapp_message(self, phone, message, chat_id=None):
        try:
            if chat_id is None:
                chat = self.get_chat(phone)
                self.driver.chat_send_message(chat.id, message)
            else:
                self.driver.send_message_to_id(chat_id, message)

            self.messagesSent += 1
        except ChatNotFoundError:
            # This means the given number is invalid.
            Logger.warning("Invalid phone number: " + str(phone) + " will be deleted")
            c = Contact.objects.get(phone=phone)
            c.delete()
            raise ChatNotFoundError
        except Exception as e:
            # This means browser is still not available even after 5 seconds.
            # But the number is not invalid.(= valid)
            Logger.error(repr(e))
            raise e

    def send_message_and_save_log(self):
        messages = Message.objects.all().filter(use=True).filter(broadcast=True)
        for m in messages:
            logs = Log.objects.all().filter(message_id=m.id).filter(sent=True)
            contacts_already_sent = []
            for l in logs:
                contacts_already_sent.append(l.contact_id)
            contacts_to_send = Contact.objects.all().exclude(id__in=contacts_already_sent)

            if len(contacts_to_send) > 0:
                # Save the log first so that the same contact cannot be used in another browsers.
                for contact in contacts_to_send:
                    newLogs = Log.objects.filter(message_id=m.id).filter(contact_id=contact.id).get_or_create(message_id=m.id, contact_id=contact.id, sent=False, sender_id=self.identifier, broadcasted=True)
                    if len(newLogs) > 0:
                        l = newLogs[0]
                    
                    try:
                        print("Try to send message: [phone(", contact.id, ": ", contact.phone, "), text(", m.id, ": ", m.text, ")", sep="")
                        # If no exception, update 'sent', 'sent_at'
                        self.send_whatsapp_message(contact.phone, m.text)
                        l.sent = True
                        l.sent_at = now()
                        l.save(update_fields=['sent', 'sent_at'])
                        # The reason returning here is: once the message is sent to anyone of contacts,
                        # then server should bring available contacts again, not iterating over the given list.
                        # Otherwise, there is no way to control server immediately after insert new messages, contacts to DB.
                        return
                    except Exception as e:
                        Logger.warning(repr(e))
                        # Wait when error occurred so that browser can be opened again.
                        t.sleep(5)

    def poll_unread(self):
        try:
            if self.driver.is_logged_in():
                # Spam only works when this server is used as a spammer.
                if apps.WhatsappConfig.spammer == 'true':
                    try:
                        self.send_message_and_save_log()
                    except Exception as e:
                        Logger.error(repr(e))
                # Otherwise, this server will fetch unread messages and send webhook.
                else:
                    data = []
                    
                    try:
                        Logger.debug("(" + self.identifier + "): get_unread()")
                        for messageGroup in self.driver.get_unread():
                            unread_messages = []
                            for m in messageGroup.messages:
                                unread_messages.append({
                                    "content": m.content,
                                    "timestamp": "{timestamp}".format(timestamp=m.timestamp)
                                })
                            data.append({ "chatId": messageGroup.chat.id, "unreadMessages": unread_messages })
                    except Exception as e:
                        Logger.error(repr(e))

                    # Doesn't have to make a request when there is no unread message.
                    if len(data) > 0:
                        payload = {'data': data}
                        webhook_url = apps.WhatsappConfig.api_endpoint + '/no_auth/whatsapp/webhook'
                        try:
                            print("Request:", webhook_url)
                            r = requests.post(webhook_url, json=payload, timeout=3)
                            print("Response:", r.text)
                        except Exception as e:
                            print("Tokotalk API(" + webhook_url + ") doesn't respond in 3 second", sep='')

        except Exception as e:
            Logger.error(repr(e))

    def run(self):
        while True:
            try:
                self.poll_unread()
            except Exception as e:
                Logger.debug(repr(e) + ": POLL FAILED")
            
            # in case the interval is not set in .env
            interval = 5
            if apps.WhatsappConfig.message_interval is not None:
                interval = int(apps.WhatsappConfig.message_interval)
            t.sleep(interval)
Пример #8
0
import os
import sys
import time

from webwhatsapi import WhatsAPIDriver

driver = WhatsAPIDriver(username="******")
for x in arr:
    chat = driver.get_chat_from_phone_number(x, True)
    driver.send_message_to_id(chat.id, "testando velocidade do envio")
Пример #9
0
class WPChannelBot():
    def __init__(self):
        self.model = WPChannelBotModel()
        self.data = self.model.get_all()
        self.convs = self.model.get_convs()
        self.convs_state = self.model.get_convs_state()

        self.simple_steps = True
        self.log_file = "log/chatbot.log"

        self.cmd_wait_from = None
        self.cmd_wait = False

        self.profile = "profile"
        self.driver = None

    def start(self):
        print("Iniciando bot...")
        self.driver = WhatsAPIDriver(profile=self.profile)
        time.sleep(3)
        if not self.driver.get_status() == "LoggedIn":
            print("Carregando QRCode")
            self.driver.get_qr("qrcode.png")

            print("Escaneie o QRCode no arquivo qrcode.png")
            self.driver.wait_for_login()

        print("Bot iniciado")
        self.driver.save_firefox_profile()

        while True:
            time.sleep(1)
            for contact in self.driver.get_unread(include_me=False,
                                                  include_notifications=True,
                                                  use_unread_count=True):
                if len(contact.messages) == 1:
                    for message in contact.messages:
                        if isinstance(message, Message):
                            self.new_message(message.content, contact)
                            self.driver.chat_send_seen(contact.chat.id)
                            time.sleep(3)
                else:
                    contact.chat.send_message(
                        "Fico confuso com muitas mensagens :S Por favor, envie uma de cada vez e espere eu responder tá?"
                    )
                    contact.chat.send_message(CHANNEL_ASK_KEYWORD)

    def new_message(self, message, contact):
        if not self._is_cmd(message):
            if self.cmd_wait and contact.chat.id == self.cmd_wait_from:
                self._cmd_envio(message, contact.chat)

            elif not contact.chat.id in self.convs:
                self._proc_etapa(contact.chat.id, message, contact.chat, 2)
            else:
                for conv in self.convs_state:
                    if conv['id'] == contact.chat.id:
                        e = self._proc_etapa(contact.chat.id, message,
                                             contact.chat, conv['etapa'])
                        conv['etapa'] = e

                        self.model.conv_update(contact.chat.id, e)
        else:
            print("ADMINISTRADOR")
            self._run_cmd(message, contact.chat)

    def shutdown(self):
        print("Desconectando...")
        self.driver.close()
        time.sleep(3)
        print("Desconectado")

    def _already_user(self, id, chat):
        if isinstance(self.model.get(id), dict):
            chat.send_message(
                "Olá, você já está cadastrado neste canal. Assim que tiver novidade você vai receber!"
            )
            return True
        else:
            return False

    def _is_keyword(self, content, chat):
        if content.lower() == CHANNEL_KEYWORD:
            return True
        else:
            chat.send_message(CHANNEL_ASK_KEYWORD)
            return False

    def _proc_etapa(self, id, content, chat, etapa):
        if etapa == 2:
            if not self._already_user(id, chat) and self._is_keyword(
                    content, chat):
                # Efetua registros
                self.convs.append(id)
                self.convs_state.append({"id": id, "etapa": 4})
                self.model.conv_add(id, 4)

                # Introdução do canal - Solicita nome
                chat.send_message(CHANNEL_INTRO)
                chat.send_message(CHANNEL_MSGS[0])
                self._to_log("Iniciando cadastro: %s" % id)

        elif etapa == 4:
            # Armazena nome - Solicita cidade
            if self.simple_steps:
                self.data.append({"id": id, "nome": content})
                # Salva no banco de dados
                self.model.add(id, content)

                chat.send_message((CHANNEL_MSGS[3] % content))
                self._remove_convs(id)

                self._to_log("Finalizado cadastro: %s - %s" % (id, content))
            else:
                self.data.append({
                    "id": id,
                    "nome": content,
                    "cidade": "",
                    "bairro": ""
                })
                chat.send_message(CHANNEL_MSGS[1])
                # Salva no banco de dados
                self.model.add(id, content)

                self._to_log("Registrado nome: %s - %s" % (id, content))
                return 6

        elif etapa == 6:
            # Implementar veficação de validade de cidade
            # Verifica cidade - volta ao 5 : armazena cidade - solicita bairro ou passo
            for obj in self.data:
                if obj["id"] == id:
                    obj["cidade"] = content

                    self.model.update(id=id, cidade=content)
                    chat.send_message(CHANNEL_MSGS[2])

                    self._to_log("Registrado cidade: %s - %s" % (id, content))
            return 7
        elif etapa == 7:
            # Implementar veficação de validade de bairro
            if content == "passo":
                # Finaliza caso não seja informado bairro
                chat.send_message((CHANNEL_MSGS[3] % self._get_conv_nome(id)))

                self._remove_convs(id)
                self._to_log("Finalizado cadastro: %s - %s" % (id, content))
            else:
                # Armazena bairro - Finaliza cadastro
                for obj in self.data:
                    if obj["id"] == id:
                        obj["bairro"] = content
                        self.model.update(id=id, bairro=content)

                        chat.send_message(
                            (CHANNEL_MSGS[3] % self._get_conv_nome(id)))

                        self._remove_convs(id)
                        self._to_log("Finalizado cadastro: %s - %s" %
                                     (id, content))

    def _to_log(self, log):
        file = open(self.log_file, "a")
        file.write("\n>> %s " % log)
        file.close()
        return

    def _get_conv_nome(self, id):
        for obj in self.data:
            if obj["id"] == id:
                return obj["nome"]

    def _remove_convs(self, id):
        self.convs.remove(id)
        for conv in self.convs_state:
            if conv["id"] == id:
                self.convs_state.remove(conv)
                self.model.conv_delete(id)

    def _is_cmd(self, content):
        if content[:4] == "/cmd":
            return True
        else:
            return False

    def _run_cmd(self, content, chat):
        cmd = content[5:]
        if not self.model.check_admin(chat.id) == False:
            if cmd == "usuarios":
                self._cmd_usuarios(chat)
            elif cmd == "envio":
                self.cmd_wait = True
                self.cmd_wait_from = chat.id
                chat.send_message(
                    "*ENVIE A SEGUIR A MENSAGEM A SER ENVIADA PARA O CANAL*")
            else:
                chat.send_message("*COMANDO NÃO RECONHECIDO*")
        elif self.model.check_admin(id=None,
                                    all=True) == False and cmd[:5] == "admin":
            print("Cadastrando novo admin")
            self.model.add_admin(chat.id, content[11:])

            chat.send_message("*ADMINISTRADOR CADASTRADO*")
        else:
            chat.send_message(CHANNEL_ASK_KEYWORD)

    def _cmd_usuarios(self, chat):
        response = "*USUÁRIOS CADASTRADOS*\n\n"

        i = 0
        users = self.model.get_all()
        for user in users:
            i += 1
            response += "\n%d) %s - %s" % (i, user['id'], user['nome'])

        chat.send_message(response)

    def _cmd_envio(self, content, chat):
        i = 0
        users = self.model.get_all()
        for user in users:
            i += 1
            self.driver.send_message_to_id(user['id'], content)

        self.cmd_wait_from = None
        self.cmd_wait = False
        chat.send_message("*MENSAGEM ENVIADA PARA %d USUÁRIOS DO CANAL*" % i)
Пример #10
0
                        client='remote',
                        command_executor=os.environ["SELENIUM"])

print('Pedira el qr')
name = uuid4().hex + '.png'
if os.path.exists(name): os.remove(name)
driver.get_qr(name)
print('Guarda el qr')
os.rename('./' + name, '/app/files/qr/' + name)

print("Waiting for QR")
driver.wait_for_login()

while True:
    time.sleep(30)
    driver.send_message_to_id("*****@*****.**", "hola")
    print(" Bateria ", driver.get_battery_level())
    print(" Number ", driver.get_phone_number())
    print(" Status ", driver.get_status())
    name = uuid4().hex + '.png'
    if os.path.exists(name): os.remove(name)
    driver.screenshot(name)
    print('Guarda foto')
    os.rename('./' + name, '/app/files/qr/' + name)

# print("chats whit messages not read", driver.get_chats_whit_messages_not_read())

# for chat in driver.get_chats_whit_messages_not_read():
#    print(driver.get_all_messages_in_chat(chat[0]))
#    for message in driver.get_all_messages_in_chat(chat[0]):
#       print(message)