How to make a whatsapp chatbot in python
aaaaaaa
Creating a WhatsApp chatbot in Python involves several steps, and it's important to note that WhatsApp does not officially support chatbot development on their platform. However, you can create a chatbot that interacts with WhatsApp by using a library called "yowsup" to interface with WhatsApp's servers and respond to messages.
Here's a simplified example of how you can create a basic WhatsApp chatbot in Python using the "yowsup" library:
Note: WhatsApp's policies regarding automated messaging may change, and using unofficial libraries like yowsup may violate their terms of service. Make sure to review WhatsApp's policies before proceeding.
Install the necessary libraries:
First, you need to install the yowsup library and some other required packages:
bash
Copy code
pip install yowsup2
Create a WhatsApp account:
You'll need a WhatsApp account to use for your chatbot. You can't use the same number for your personal WhatsApp and the chatbot.
Create the Python script:
Here's a simple Python script to get you started:
python
Copy code
import threading
from yowsup.layers import YowParallelLayer
from yowsup.layers.auth import YowAuthenticationProtocolLayer
from yowsup.layers.protocol_messages import YowMessagesProtocolLayer
from yowsup.layers.protocol_receipts import YowReceiptProtocolLayer
from yowsup.layers.protocol_acks import YowAckProtocolLayer
from yowsup.layers.network import YowNetworkLayer
from yowsup.layers.stanzaregulator import YowStanzaRegulator
from yowsup.layers.protocol_iq import YowIqProtocolLayer
from yowsup.layers.protocol_presence import YowPresenceProtocolLayer
from yowsup.stacks import YowStackBuilder
from yowsup.common import YowConstants
class EchoLayer(YowParallelLayer):
def receive(self, protocol_entity, message):
text = message.getBody()
if text:
response = "You said: " + text
self.toLower(message.reply(response))
credentials = ("YOUR_PHONE_NUMBER", "YOUR_PASSWORD") # Use the phone number and password you created
stackBuilder = YowStackBuilder()
stack = stackBuilder\
.pushDefaultLayers(True)\
.push(EchoLayer)\
.build()
stack.setCredentials(credentials)
stack.broadcastEvent(YowLayerEvent(YowNetworkLayer.EVENT_STATE_CONNECT))
try:
stack.loop()
except KeyboardInterrupt:
stack.broadcastEvent(YowLayerEvent(YowNetworkLayer.EVENT_STATE_DISCONNECT))
Replace "YOUR_PHONE_NUMBER" and "YOUR_PASSWORD" with the phone number and password you created for your WhatsApp bot.
Run the script:
Run the Python script to start the chatbot. It will listen for incoming messages and respond with "You said: [message]" to any message it receives.
Remember that using this approach may violate WhatsApp's terms of service, and your WhatsApp account could be banned. Always ensure you comply with their policies and use any automation responsibly and within their guidelines. Additionally, WhatsApp's policies and APIs may change over time, so be prepared for potential updates or changes.
import numpy as np
import nltk
import string
import random
f=open('chatbot.txt','r',errors='ignore')
raw_doc=f.read()
raw_doc=raw_doc.lower()
nltk.download('punkt')
nltk.download('wordnet')
sent_tokens=nltk.sent_tokenize(raw_doc)
word_tokens=nltk.word_tokenize(raw_doc)
sent_tokens[:2]
word_tokens[:2]
lemmer=nltk.stem.WordNetLemmatizer()
def LemTokens(tokens):
return[lemmer.lemmatize(token)for token in tokens]
remove_punct_dict= dict((ord(punct),None) for punct in string.punctuation)
def LemNormalize(text):
return LemTokens(nltk.word_tokenize(text.lower().translate(remove_punct_dict)))
GREET_INPUTS=("hello","hi","sup","greetings","what's up","hey",)
GREET_RESPONSES=("hi","hey","*nods*","hi there","hello","I'm glad! You are talking to me")
def greet(sentence):
for word in sentence.split():
if word.lower() in GREET_INPUTS:
return random.choice(GREET_RESPONSES)
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
def response(user_response):
robo1_response=''
TfidfVec=TfidfVectorizer(tokenizer=LemNormalize, stop_words='english')
tfidf=TfidfVec.fit_transform(sent_tokens)
vals=cosine_similarity(tfidf[-1],tfidf)
idx=vals.argsort()[0][-2]
flat=vals.flatten()
flat.sort()
req_tfidf=flat[-2]
if(req_tfidf==0):
robo1_response=robo1_response+"I am sorry! I don't understand you"
return robo1_response
else:
robo1_response=robo1_response+sent_tokens[idx]
return robo1_response
flag=True
print("Bot: My name is Stark. Let's have a conversation! Also, if you want to exit anytime, just type Bye!")
while(flag==True):
user_response=input()
user_response=user_response.lower()
if (user_response!='bye'):
if (user_response=='thanks' or user_response=='thank you'):
flag=False
print("BOT: You are welcome..")
else:
if(greet(user_response)!=None):
print("BOT: "+greet(user_response))
else:
sent_tokens.append(user_response)
word_tokens=word_tokens+nltk.word_tokenize(user_response)
final_words=list(set(word_tokens))
print("BOT: ",end="")
print(response(user_response))
sent_tokens.remove(user_response)
else:
flag=False
print("BOT: Goodbye! Take care <3")
Learn PYTHON
0 Comments