Skip to content

Commit 1bb1ec0

Browse files
Create bot.py
1 parent fb53889 commit 1bb1ec0

File tree

1 file changed

+87
-0
lines changed

1 file changed

+87
-0
lines changed

bot.py

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
import os
2+
from twilio.rest import Client
3+
from flask import Flask, request, jsonify
4+
import random
5+
import requests
6+
7+
# Bot creator info
8+
CREATOR = os.getenv("BOT_CREATOR", "Phantomz@jumamohammed")
9+
10+
# Twilio account details (replace these with your own from your Twilio console)
11+
ACCOUNT_SID = 'ACec9c1022b402c04c975822465f06828b'
12+
AUTH_TOKEN = '18c24e39f6ff959178942aa6d81f69bf'
13+
FROM_PHONE = 'whatsapp:+14155238886' # Replace with your Twilio sandbox number
14+
15+
# Initialize Twilio Client
16+
client = Client(ACCOUNT_SID, AUTH_TOKEN)
17+
18+
# Create a Flask app to handle incoming webhooks
19+
app = Flask(__name__)
20+
21+
# Helper functions
22+
def get_random_greeting():
23+
greetings = ["Hi!", "Hello!", "Hey there!", "Greetings!"]
24+
return random.choice(greetings)
25+
26+
def handle_command(command):
27+
command = command.lower() # Normalize to lowercase
28+
commands = {
29+
'help': """Here are the available commands:
30+
1. hello - Greet the bot.
31+
2. who made you - Know the creator.
32+
3. !help - List of commands.
33+
4. !joke - Get a random joke.
34+
5. !about - Learn about this bot.""",
35+
'about': f"This bot is created by {CREATOR} using Twilio's WhatsApp API.",
36+
'joke': get_joke,
37+
}
38+
39+
if command in commands:
40+
if command == 'joke':
41+
return commands[command]() # Calls the get_joke function
42+
else:
43+
return commands[command]
44+
else:
45+
return "Unknown command. Try '!help' for the list of commands."
46+
47+
def get_joke():
48+
try:
49+
response = requests.get('https://official-joke-api.appspot.com/random_joke')
50+
joke = response.json()
51+
return f"{joke['setup']} - {joke['punchline']}"
52+
except requests.exceptions.RequestException:
53+
return "Sorry, I couldn't fetch a joke right now. Try again later!"
54+
55+
# Flask route to handle incoming messages
56+
@app.route("/incoming", methods=['POST'])
57+
def incoming_message():
58+
# Get incoming message from the request
59+
incoming_msg = request.values.get('Body', '').lower()
60+
from_number = request.values.get('From', '')
61+
62+
if incoming_msg == 'hello':
63+
reply_msg = get_random_greeting()
64+
elif incoming_msg == 'who made you':
65+
reply_msg = f"I was crafted by {CREATOR}. Let me know if you want to learn more!"
66+
elif incoming_msg.startswith('!'):
67+
command = incoming_msg[1:] # Remove the '!' from the command
68+
reply_msg = handle_command(command)
69+
else:
70+
reply_msg = "I'm not sure what you mean. Try saying 'hello' or 'who made you'."
71+
72+
# Send the response back to the user
73+
send_whatsapp_message(from_number, reply_msg)
74+
return jsonify({'status': 'Message sent'})
75+
76+
def send_whatsapp_message(to, body):
77+
"""Send WhatsApp message via Twilio"""
78+
message = client.messages.create(
79+
body=body,
80+
from_=FROM_PHONE,
81+
to=to
82+
)
83+
print(f"Sent message to {to}: {body}")
84+
85+
# Run the Flask app
86+
if __name__ == "__main__":
87+
app.run(port=5000)

0 commit comments

Comments
 (0)