danielcardeenas / whatsapp-framework

⚗️Whatsapp python api
1.16k stars 363 forks source link

How to send a message? #137

Open JosemariC opened 6 years ago

JosemariC commented 6 years ago

Hello everyone!

I've started using this framework, it's really fantastic, congratulations @danielcardeenas!

I have written my own module so that the bot responds only to some messages (those that meet certain conditions and the recipient is in my contact list) and I am very happy because it works very well.

My problem is that I am new programming in python. I am trying to write a module that simply sends a message to one of the contacts in my list at any time. But not in response to a previously received message, just as the beginning of a conversation or as a reminder. Can someone help me please with a simple example? Should I write a new module in the modules folder and add it to the init.py file? How can I execute it later?

Thank you very much in advance

JosemariC commented 6 years ago

I have made some small progress, with this code:

from app.mac import mac, signals
@signals.initialized.connect
def manda_mensaje (message):
       text = "bla bla bla"
       dest = "34666123456@s.whatsapp.net"
       mac.send_message_to (text, dest)

I have placed it in the modules folder and it works, that is, it sends the message to the destination mobile but only when I run ./start.sh

How can I do to send a message at any time while the bot is running?

Thank you very much!

LabtronicsDesign commented 6 years ago

@signals.initialized.connect This is for a function to run once on initialisation (startup) off the bot.

@signals.message_received.connect This is for a function to run when any message is received.

@signals.command_received.connect This is for a function to run when a message stating with ! is received.

JosemariC commented 6 years ago

Thank you very much for your answer @SPWC

But then, is there any way to send messages at any given time? It's possible?

Thanks again!

jhonarodriguez commented 6 years ago

Hello Jose, according to I understand your question is like sending a message in a certain time to a recipient, Remember not to send Spam if you will not be banned .

I think the following thing, that you do a function in python in the module that you have where you bring the contacts that you want to send by a message, for example:

import requests
r = requests
urlglobal = 'http://www.dominio.com/traercontactos'
pet = r.post(urlglobal)
contactsJSON = pet.json()

already having the contacts to which you must send the reminder, you have a function equivalent to setTimeOut of javascript where you pass the number to which you want to send the message, the message and the time in which you want to send it, for example it would be something like this:

def enviarRecordatorio(num,msn):
       mac.send_message(msn,num)

def setTimeOut(num,msn,sec):
    def func_wrapper():
        enviarRecordatorio(num,msn)
    t = threading.Timer(sec, func_wrapper)
    t.start()
    return t

and what remains is that you scroll through the contacts, what message will reach each contact and in what time likewise calling the function setTimeOut ()

Remember also that you should only send messages to those who have previously sent you a message

JosemariC commented 6 years ago

Thank you very much for your help @elchory96

I have a question. The code to get the list of contacts to send the message to, is a function in python that I must place in the modules folder (in the style of the example hihelp.py)? How is the execution of this function triggered? Imagine that I should send a personalized reminder every day only to those contacts that meet a certain condition that day ... How can I force the function to run?

I sincerely appreciate your help

jhonarodriguez commented 6 years ago

Yes, do it in a module that you are using unless you do it with classes.

do a function where you call the data of the contacts from a database for example, using the library requests with requests post or get or using the mysql library of python.

when you have all the data of the contacts in json, valid those that you have to send that day and you only call the function mac.send_message (msn, num) and returns to do the setTimeout placing 86400 seconds that in hour would be 24, I leave you a example of more or less as it would be.

def getContactosDay():
    data = [
        {
            "nombrecontact": "Contacto 1",
            "enviarmensaje": 1,
                "mensaje": "Recuerda que hoy tienes una tarea para las 4 de la tarde",
            'numero': '323023138765'
        },
        {
            "nombrecontact": "Contacto 2",
            "enviarmensaje": 0,
            "mensaje": "Recuerda que hoy tienes una tarea para las 7 de la tarde",
            'numero': '323023138765'
        },
        {
                "nombrecontact": "Contacto 3",
                "enviarmensaje": 1,
            "mensaje": "Recuerda que hoy tienes una tarea para las 2 de la tarde",
            'numero': '323023138765'
        }
    ]
    return data

def enviarRecordatorio():
    contacts = getContactosDay()

    for cont in contacts:
        if contacts[cont]['enviarmensaje'] == 1:
            mac.send_message(contacts[cont]['mensaje'],contacts[cont]['numero'])
    setTimeOut(86400)

def setTimeOut(sec):
    def func_wrapper():
        enviarRecordatorio()
    t = threading.Timer(sec, func_wrapper)
    t.start()
    return t
JosemariC commented 6 years ago

Great @elchory96

I will try to do it and I will update the result in this same thread.

And again, thank you very much for your help and your time!

JosemariC commented 6 years ago

Hello,

Hoping that this can help someone, this is the code I've written, based on the idea of @elchory96 (thanks again). Every 5 seconds it checks if there is any file with the .out extension (in the outbox folder). This file only contains the number of the recipient and the message to be sent (separated both by " - ").

Once all the messages have been sent, the file will be deleted and a new one will be created (inside the sent folder) with the same information, adding the date and time in which each message was sent. The code is more or less like this:

import threading, glob, time, os, random
from app.mac import mac, signals

@signals.initialized.connect
def sendReminder(texto):
        if texto == "from wrapper":
          lfiles = glob.glob("/root/whatsapp-aux/outbox/*.out")
          for i, fichero in enumerate(lfiles):
            with open(fichero, "r") as t:
              print ("processing file: ", fichero.rpartition('/')[2])
              with open("/root/whatsapp-aux/sent/"+fichero.rpartition('/')[2], "w") as u:
                for linea in t:
                  numero = linea.split(" - ", 1)[0]
                  mensaje = linea.split(" - ", 1)[1]
                  u.write (time.strftime("%d/%m/%Y %H:%M:%S - "))
                  u.write (numero+" - "+mensaje)
                  time.sleep(random.randrange(1,5))
                  mac.send_message_to(mensaje,numero)
                u.close()
                t.close()
                os.remove(fichero)
              print ("End process file")
        setTimeOut(5) # 5 seconds

def setTimeOut(sec):
        def func_wrapper():
                sendReminder("from wrapper")
        t = threading.Timer(sec, func_wrapper)
        t.start()
        return t

Best regards,

UmairAnjum commented 6 years ago

Hello This code gives me a File Not Found exception after one iteration because file is deleted and it keeps looking for the file*.out in outbox path

JosemariC commented 6 years ago

Hello,

could you please send here the code that you say fails? Because there should be no exception after deleting the * .out file.

Regards,

UmairAnjum commented 6 years ago

Hello, I have used above code after first iteration it still keep looking in outbox folder and throws a "FileNotFound" exception

rgchurion commented 5 years ago

Hola @JosemariC ante todo muchas gracias por el código, podrías por favor decirnos cómo corregir el error que sale al final del proceso?, adjunto lo enviado a consola.

Hello @JosemariC first of all, thank you very much for the code, could you please tell us how to correct the error that comes out at the end of the process ?, attach it out to the console.

`root@whatsapp:~/whatsapp-framework# ./start.sh [Whatsapp] Mac started

processing file: probando.out End process file Exception in thread Thread-2: Traceback (most recent call last): File "/usr/lib/python3.5/threading.py", line 914, in _bootstrap_inner self.run() File "/usr/lib/python3.5/threading.py", line 1180, in run self.function(*self.args, **self.kwargs) File "/root/whatsapp-framework/modules/enviarauto/enviarauto.py", line 27, in func_wrapper sendReminder("from wrapper") File "/root/whatsapp-framework/modules/enviarauto/enviarauto.py", line 12, in sendReminder for linea in t: ValueError: I/O operation on closed file. ` Gracias por tu tiempo. Thanks for your time.

rgchurion commented 5 years ago

Problema resuelto, está en la identación del código, Muchas Gracias por tan buena rutina!!

Problem solved, is in the indentation of the code, Thank you very much for such a good routine!

patelnilanj commented 5 years ago

thank you very much @danielcardeenas @elchory96 @JosemariC

gabrieru commented 5 years ago

someone can teach me how to send an message to whatsapp group every day at 23:50pm? or maybe evey day every 6 hours?