def webhook(): print(request.data) data = request.get_json() if data['object'] == "page": entries = data['entry'] for entry in entries: messaging = entry['messaging'] for messaging_event in messaging: sender_id = messaging_event['sender']['id'] recipient_id = messaging_event['recipient']['id'] if messaging_event.get('message'): if messaging_event['message'].get('text'): query = messaging_event['message']['text'] reply = fetch_reply(query, sender_id) if reply['type'] == 'news': bot.send_generic_message(sender_id, reply['data']) else: bot.send_text_message(sender_id, reply['data']) elif messaging_event.get('postback'): if messaging_event['postback']['payload'] == 'SHOW_HELP': bot.send_text_message( sender_id, "Ok. I will show you help message!") return "ok", 200
def sms_reply(): msg = request.form.get('Body') sender = request.form.get('From') # The reply object resp = MessagingResponse() #Calling function to generate reply rec_reply = fetch_reply(msg, sender) # If a simple string is returned print that string if type(rec_reply) == str: message = Message() message.body(rec_reply) resp.append(message) return str(resp) # If 2 objects (string and url are returned append the media to message and send) for row in rec_reply: message = Message() link = requests.get('http://tinyurl.com/api-create.php?url={}'.format( row['link'])).content.decode('utf-8') message.body("{}\n{}".format(row['title'], link)) if row['media']: message.media(row['media']) resp.append(message) return str(resp)
def sms_reply(): # Fetch the message msg = request.form.get('Body') sender = request.form.get('From') # Create reply resp = MessagingResponse() recieved_obj = fetch_reply(msg, sender) # If the recieved object is from get_weather() if isinstance(recieved_obj[0], str): message = Message() message.body(recieved_obj[0]) message.media(recieved_obj[1]) resp.append(message) return str(resp) # If the recieved object is from get_news() for row in recieved_obj: message = Message() link = requests.get('http://tinyurl.com/api-create.php?url={}'.format( row['link'])).content.decode('utf-8') message.body("{}\n{}".format(row['title'], link)) if row['media']: message.media(row['media']) resp.append(message) return str(resp)
def webhook(): print(request.data) data = request.get_json() if data['object'] == 'page': entries = data['entry'] for entry in entries: messaging = entry['messaging'] for messaging_event in messaging: sender_id = messaging_event['sender']['id'] recipient_id = messaging_event['recipient']['id'] if messaging_event.get('message'): if messaging_event['message'].get('text'): query = messaging_event['message']['text'] reply = fetch_reply(query, sender_id) if reply['type'] == 'Places': bot.send_generic_message(sender_id, reply['data']) else: bot.send_text_message(sender_id, reply['data']) elif messaging_event['message'].get('attachments'): bot.send_text_message(sender_id, HELP_MSG) elif messaging_event.get('postback'): bot.send_text_messsage(sender_id, HELP_MSG) return 'ok', 200
def sms_reply(): """Respond to incoming calls with a simple text message.""" # Fetch the message print(json.dumps(request.form,indent = 2)) msg = request.form.get('Body') sender = request.form.get('From') reply, cover, mov_search = fetch_reply(msg,sender) # Create reply resp = MessagingResponse() if msg == 'help' or msg == 'Help' or msg =='HELP': reply = "Hello, I am a *_HelpBot_*. How may I help you? \n\nYou can search for news by providing us the *<new></new>s type*! \nEg: *show me sports news* \n\nYou can also search for *restaurants/cafes* in any area \nEg: *show me restaurants in gurgaon* \n\nYou can check the *temperature* of any paticular location \nEg: *what is the temperature of amritsar* \n\nYou can check movie reviews \n Eg: *Reviews of Uri*" resp.message(reply) new_record = { 'message_body': msg, 'sender_id' : sender, 'bot_reply': reply, 'sent_at' : str(datetime.datetime.now()) } print(new_record) record.insert_one(new_record) elif mov_search == 'reviews': resp.message(reply).media(cover) new_record = { 'message_body': msg, 'sender_id' : sender, 'bot_reply': reply, 'cover': cover, 'sent_at' : str(datetime.datetime.now()) } record.insert_one(new_record) else: resp.message(reply) new_record = { 'message_body': msg, 'sender_id' : sender, 'bot_reply': reply, 'sent_at' : str(datetime.datetime.now()) } record.insert_one(new_record) return str(resp)
def sms_reply(): """Respond to incoming calls with a simple text message.""" # Fetch the message print(request.form) msg = request.form.get('Body') sender = request.form.get('From') # records.count_documents({}) new_user = { 'sender': sender, 'message_body': msg, 'sender_id': sender, 'send_at': str(datetime.datetime.now()) } records.insert_one(new_user) # print(condition.text) # Create reply resp = MessagingResponse() # reply,reply_type = fetch_reply(msg,sender) # if reply_type == 'text' # resp.message(reply) # return(str) resp.message("You said: {}".format(msg)).media( "https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png" ) resp.message(fetch_reply(msg, sender)) return str(resp)
def sms_reply(): """Respond to incoming calls with a simple text message.""" # Fetch the message print(json.dumps(request.form,indent = 2)) msg = request.form.get('Body') sender = request.form.get('From') reply,img,search = fetch_reply(msg,sender) # Store in DB # # Create reply # # resp.message("You said: {}".format(msg)).media("https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png") resp = MessagingResponse() if msg == 'help' or msg == 'Help' or msg =='HELP': resp.message("Hello, I am a *_HelpBot_*. How may I help you? \n\nYou can search for news by providing us the *<new></new>s type*! \nEg: *show me sports news* \n\nYou can also search for *restaurants/cafes* in any area \nEg: *show me restaurants in gurgaon* \n\nYou can check the *temperature* of any paticular location \nEg: *what is the temperature of amritsar*") new_record = { 'message_body': msg, 'sender_id' : sender, 'bot_reply': reply, 'sent_at' : str(datetime.datetime.now()) } records.insert_one(new_record) elif search == 'reviews': resp.message('{}'.format(reply)).media(img) new_record = { 'message_body': msg, 'sender_id' : sender, 'bot_reply': reply, 'cover': img, 'sent_at' : str(datetime.datetime.now()) } records.insert_one(new_record) else: resp.message(reply) new_record = { 'message_body': msg, 'sender_id' : sender, 'bot_reply': reply, 'sent_at' : str(datetime.datetime.now()) } records.insert_one(new_record) return str(resp)
def sms_reply(): #Fetch message msg = request.form.get('Body') sender = request.form.get('From') # Create reply resp = MessagingResponse() my_message = fetch_reply(msg, sender) #Message starting with 'Here is your news:' are from news query if my_message[0:18]=='Here is your news:': image = 'https://www.thelillahuset.com/wp-content/uploads/2018/11/news.jpg' resp.message(my_message).media(image) #Message starting with 'Weather for ' are from weather query elif my_message[0:12]=='Weather for ': city = '' for ch in my_message[12:]: if ch==':': break city+=ch try: image = wikipedia.page(city).images[0] except: image = 'https://wi-images.condecdn.net/image/doEYpG6Xd87/crop/2040/f/weather.jpg' resp.message(my_message).media(image) #Case for not understanding the user query else: resp.message(my_message) return str(resp)
def sms_reply(): """Respond to incoming calls with a simple text message.""" # Fetch the message print(request.form) msg = request.form.get('Body') sender = request.form.get('From') # Create reply resp = MessagingResponse() if (type(fetch_reply(msg, sender)) == str): text = fetch_reply(msg, sender) resp.message(text) else: text, url = fetch_reply(msg, sender) resp.message(text).media(url) return str(resp)
def sms_reply(): """Respond to incoming calls with a simple text message.""" # Fetch the message msg = request.form.get('Body') phone_no = request.form.get('From') # Create reply resp = MessagingResponse() mss = resp.message() responded = False if msg == "who": mss.body(artgoblin()) responded = True elif msg == "//help": mss.body(helpaa()) responded = True elif msg == "Meeting-links": mss.body(meetinglinks()) responded = True elif msg == "Attendance-links": mss.body(attendancelinks()) responded = True elif msg == "Show-routine": mss.body(rou()) responded = True elif msg == "//syl": mss.body(syl()) responded = True elif msg == "Funn-time": mss.body(fun()) responded = True elif msg == "meet": mss.body((replya())) responded = True elif msg == "memes": r = requests.get( 'https://www.reddit.com/r/memes/top.json?limit=20?t=day', headers={'User-agent': 'your bot 0.1'}) if r.status_code == 200: data = r.json() memes = data['data']['children'] random_meme = random.choice(memes) meme_data = random_meme['data'] title = meme_data['title'] image = meme_data['url'] mss.body(title) mss.media(image) responded = True else: reply = fetch_reply(msg, phone_no) mss.body(reply) responded = True return str(resp)
def webhook(): print(request.data) data = request.get_json() if data['object'] == "page": entries = data['entry'] for entry in entries: messaging = entry['messaging'] for messaging_event in messaging: sender_id = messaging_event['sender']['id'] recipient_id = messaging_event['recipient']['id'] if messaging_event.get('message'): # HANDLE NORMAL MESSAGES HERE if messaging_event['message'].get('text'): # HANDLE TEXT MESSAGES query = messaging_event['message']['text'] reply = fetch_reply(query, sender_id) bot.send_text_message(sender_id, reply) return "ok", 200
def sms_reply(): """Respond to incoming calls with a simple text message.""" # Fetch the message print(request.form) msg = request.form.get('Body') sender = request.form.get('From') if (msg == ""): # when media was send, message space was empty to cover it msg = "Random image" # Create reply resp = MessagingResponse() text, reply = fetch_reply(msg, sender) if text == 'picture': resp.message(reply).media(reply) elif text == 'image_whatsapp': num_media = int(request.values.get("NumMedia")) if not num_media: msg = resp.message("Send us an image!") else: msg = resp.message("Thanks for the image(s).") msg.media(GOOD_BOY_URL) else: resp.message(reply) return str(resp)
def sms_reply(): """Respond to incoming calls with a simple text message.""" # Fetch the message msg = request.form.get('Body') sender=request.form.get('From') mongo_client=MongoClient("mongodb+srv://mybotdatabase:[email protected]/test?retryWrites=true&w=majority") db=mongo_client.get_database('mybotdatabase') records=db.mybot_collection #records.update_many({'number':sender.strip()},{'$addToSet': {'requests':msg}},,upsert=True) #Dictionary 'links' To respond with random media images links={ 1:"https://animals.sandiegozoo.org/sites/default/files/2016-08/category-thumbnail-mammals_0.jpg", 2:"https://ichef.bbci.co.uk/images/ic/480xn/p049tgdb.jpg", 3:"https://404store.com/2017/07/26/Beautiful-Animal-Panther.jpg", 4:"https://i.pinimg.com/originals/d8/02/ea/d802ea3a31a002a44cb4cb0eedd3fd80.jpg", 5:"https://www.irishcentral.com/uploads/article/99949/cropped_GettyImages-940461304.jpg?t=1551257695" } if request.values['NumMedia'] != '0': # Use the message SID as a filename. filename = request.values['MessageSid']+'.jpg' DOWNLOAD_DIRECTORY="images\\" with open('{}\\{}'.format(DOWNLOAD_DIRECTORY, filename), 'wb') as f: image_url = request.values['MediaUrl0'] f.write(requests.get(image_url).content) # Create reply resp = MessagingResponse() resp.message(" Thanks for img") #TO STORE MESSAGE SENT AND RESPONSE records.update_one({'number':str(sender).strip()},{'$push': {'requests':image_url, 'responses':str(resp)[57:-21]}},upsert=True) return str(resp) else: resp = MessagingResponse() #response needs to be sent in a particular format...so we use this #resp.message("You said: {}".format(msg)).media("https://images.unsplash.com/photo-1543549790-8b5f4a028cfb?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80") reply=fetch_reply(msg,sender) if(reply=='picture10'): resp.message("Here is an image").media(links[random.randint(1,5)]) else: resp.message(reply) from utils import dict_news print("__________________________________________________________________________________________________") print("dict_news",dict_news) print("__________________________________________________________________________________________________") #STORE USER`S NEWS PREFERENCES if(dict_news['topic']!=""): records.update_one({'number':str(sender).strip()},{'$addToSet': {'news_topic':dict_news['topic'] }},upsert=True) if(dict_news['location']!=""): records.update_one({'number':str(sender).strip()},{'$addToSet': {'news_location':dict_news['location'] }},upsert=True) if(dict_news['language']!=""): records.update_one({'number':str(sender).strip()},{'$addToSet': {'news_language':dict_news['language'] }},upsert=True) #TO STORE MESSAGE SENT AND RESPONSE records.update_one({'number':str(sender).strip()},{'$push': {'requests':msg, 'responses':str(resp)[57:-21]}},upsert=True) return str(resp)
def say_hello(**payload): data = payload['data'] web_client = payload['web_client'] text = data.get('text') subtype = data.get('subtype') if subtype is None and text: channel_id = data['channel'] user = data['user'] client_msg_id = data['client_msg_id'] reply = fetch_reply(text,client_msg_id) if reply['type'] == 'playerranking': data = json.loads(reply['data']) string = 'Rank\tName\n' for i in data: string += f'{i[0]}\t{i[1]}\n' web_client.chat_postMessage(channel=channel_id, text=string) if reply['type'] == 'resulttoday': data = json.loads(reply['data']) if data['result'] == 'success': string = '' for i in data['content']: match = i['match'] link = i['link'] string += f'{match}\t{link}\n' web_client.chat_postMessage(channel=channel_id, text=string) else: web_client.chat_postMessage(channel=channel_id, text='Sorry :( ,not able to find it.') if reply['type'] == 'scorer': data = json.loads(reply['data']) if data['result'] == 'success': string = f'Name\t\tTeam\tGoals\tAssist\n' for i in data['content']: string += f'{i[0]}\t{i[1]}\t{i[2]}\t{i[3]}\n' web_client.chat_postMessage(channel=channel_id, text=string) else: web_client.chat_postMessage(channel=channel_id, text='Sorry :( ,not able to find it.') if reply['type'] == 'points_table': data = json.loads(reply['data']) if data['result'] == 'success': string = 'pos\tName\t\tP\tGd\tPts\n' for i in data['content']: string += f'{i[0]}\t{i[1]}\t{i[2]}\t{i[3]}\t{i[4]}\n' web_client.chat_postMessage(channel=channel_id, text=string) else: web_client.chat_postMessage(channel=channel_id, text='Sorry :( ,not able to find it.') else: web_client.chat_postMessage(channel=channel_id, text=reply.get('data') )
def sms_reply(): msg = request.form.get('Body') sender = request.form.get('From') resp = MessagingResponse() resp.message(fetch_reply(msg, sender)) return str(resp)
def sms_reply(): msg = request.form.get('Body') phone_no = request.form.get('From') reply = fetch_reply(msg, phone_no) resp = MessagingResponse() resp.message(reply) return str(resp)
def sms_reply(): #fetch message from post request #print(request.form) msg = request.form.get('Body') sender = request.form.get('From') # Create reply resp = MessagingResponse() resp.message(fetch_reply(msg, sender)) return str(resp)
def webhook(): print(request.data) data = request.get_json() if data['object'] == "page": entries = data['entry'] for entry in entries: messaging = entry['messaging'] for messaging_event in messaging: sender_id = messaging_event['sender']['id'] recipient_id = messaging_event['recipient']['id'] if messaging_event.get('message'): # HANDLE NORMAL MESSAGES HERE if messaging_event['message'].get('text'): # HANDLE TEXT MESSAGES query = messaging_event['message']['text'] if messaging_event['message'].get('quick_reply'): # HANDLE TEXT MESSAGE WITH QUICK REPLY payload = messaging_event['message']['quick_reply']['payload'] if payload in list(zip(*news_categories))[1]: query = payload reply = fetch_reply(query, sender_id) with open('data.json', 'w') as outfile: json.dump(reply, outfile) # print("---------------------------------------------------------------------------------------------------------") # print(reply) # print("---------------------------------------------------------------------------------------------------------") print(reply['type']) if reply['type'] == 'news': bot.send_generic_message(sender_id, reply['data']) elif reply['type'] == 'none': bot.send_button_message(sender_id, "Sorry, I didn't understand. :(", reply['data']) elif reply['type'] == 'help': bot.send_quickreply(sender_id, HELP_MSG, news_categories) else: bot.send_text_message(sender_id, reply['data']) elif messaging_event.get('postback'): # HANDLE POSTBACKS HERE payload = messaging_event['postback']['payload'] if payload == 'SHOW_HELP': bot.send_quickreply(sender_id, HELP_MSG, news_categories) return "ok", 200
def sms_reply(): """Respond to incoming calls with a simple text message.""" # Fetch the message print(request.form) msg = request.form.get('Body') sender = request.form.get('From') # Create reply resp = MessagingResponse() resp.message(fetch_reply(msg, sender)) return str(resp)
def sms_reply(): """Respond to incoming calls with a simple text message.""" # Fetch the message msg = request.form.get('Body') phone_number = request.form.get('From') # Create reply reply = fetch_reply(msg, phone_number) resp = MessagingResponse() resp.message(reply) return str(resp)
def sms_reply(): # Responde a mensagem recebida" # Pega o conteúdo da mensagem e o numero de quem enviou msg = request.form.get('Body') phone_no = request.form.get('From') reply = fetch_reply(msg,phone_no) # Cria resposta resp = MessagingResponse() resp.message(reply) return str(resp)
def sms_reply(): """Respond to incoming calls with a simple text message.""" # Fetch the message print(request.form) msg = request.form.get('Body') sender = request.form.get('From') # Create reply resp = MessagingResponse() #resp.message("You said: {}".format(msg)).media('https://lh3.googleusercontent.com/proxy/ogwfaF0iwa05OnTNQFyD0rZ384sAN74p5xwJE6qfJmrEFcmgxlXo4zg22lrlaLcaS_hp9pFCu8s8QZ-GgDy37DxWVOHpq2B4IV35vb4wgHBWfJiYqI_AVARVMaguPane4Raedg=w530-h212-p-rw') resp.message(fetch_reply(msg, sender)) return str(resp)
def sms_reply(): """Respond to incoming calls with a simple text message.""" # Fetch the message print(request.form) msg = request.form.get('Body') sender = request.form.get('From') # Create reply resp = MessagingResponse() p = resp.message(fetch_reply(msg, sender)) # p.media("https://images.app.goo.gl/METnxz4uDcAzwcnx5.jpeg") return str(resp)
def sms_reply(): print(request.form) msg = request.form.get('Body') sender = request.form.get('From') resp = MessagingResponse() x, y = fetch_reply(msg, sender) if y == "": resp.message(x) else: resp.message(y).media(x) return str(resp)
def whatsapp_reply(): #Fetch the message msg = request.form.get('Body') tel_no = request.form.get('From') reply = fetch_reply(msg,tel_no) #create reply resp = MessagingResponse() resp.message(reply) #resp.message("Did you say that you are {}?".format(msg)) return str(resp)
def sms_reply(): """Respond to incoming calls with a simple text message.""" # Fetch the message msg = request.form.get('Body') phone_no = request.form.get("From") reply = fetch_reply(msg,phone_no) # Create reply resp = MessagingResponse() #resp.message("You said: {}".format(msg)) resp.message(reply) return str(resp)
def sms_reply(): """Respond to incoming calls with a simple text message.""" # Fetch the message msg = request.form.get('Body') phone_no = request.form.get('From') replies = fetch_reply(msg, phone_no) # Create reply resp = MessagingResponse() for reply in replies: resp.message(reply.text) return str(resp)
def sms_reply(): """Respond to incoming calls with a simple text message.""" # Fetch the message msg = request.form.get('Body') phone_no = request.form.get('From') reply = fetch_reply(msg, phone_no) # Create reply resp = MessagingResponse() resp.message(reply) #resp.message("{}\nI need a doctor, to bring me back to life, right?".format(msg)) return str(resp)
def sms_reply(): """Respond to incoming calls with a simple text message.""" msg = request.form.get('Body') #get the message phone_no = request.form.get('From') #get phone number reply = fetch_reply(msg, phone_no) #setting input for fetch reply in utils # Create reply resp = MessagingResponse() resp.message(reply) return str(resp)
def sms_reply(): """ Respon to incoming msgs """ msg = request.form.get('Body') phone_no = request.form.get('From') reply = fetch_reply(msg, phone_no) resp = MessagingResponse() resp.message(f"ECHO: {reply}") return str(resp)