def __init__(self): self.client = zulip.Client(site="https://fazeup.zulipchat.com/api/") self.subscribe_all() self.hacknews = Hackernews() self.trans = Translate() self.movie = Movie() self.lyrics = Lyrics() self.holiday = Holiday() self.currency = Currency() self.cricket = Cricket() # self.chatbot.train("chatterbot.corpus.english") self.crypto = Crypto() self.trans = Translate() self.g = Giphy() self.w = WikiPedia() # self.tw = Twimega() # self.motivate = Motivate() self.shortenedurl = Urlshortener() self.geo = Geocode() self.weather = Weather() self.dict_ = Dictionary() self.joke = Joke() self.pnr = Pnr() self.mustread = Mustread() self.ss = Ss() self.cricket = Cricket() self.poll = Poll() print("done init") self.subkeys = [ "crypto", "translate", "define", "joke", "weather", "giphy", "pnr", "mustread", "poll", "hackernews", "hn", "HN", "motivate", "twitter", "screenshot", "memo", "cricnews", "help", "shorturl", "movie", "currency", "holiday", "lyrics" ]
def __init__(self): self.client = zulip.Client(site="https://chunkzz.zulipchat.com/api/") self.subscribe_all() self.chatbot = ChatBot( "Omega", trainer='chatterbot.trainers.ChatterBotCorpusTrainer') self.chatbot.train("chatterbot.corpus.english") self.crypto = Crypto() self.trans = Translate() self.g = Giphy() self.w = WikiPedia() self.tw = Twimega() self.motivate = Motivate() self.shortenedurl = Urlshortener() self.hacknews = Hackernews() self.geo = Geocode() self.weather = Weather() self.dict_ = Dictionary() self.joke = Joke() self.pnr = Pnr() self.mustread = Mustread() self.ss = Ss() self.cricket = Cricket() self.poll = Poll() self.subkeys = [ "crypto", "translate", "define", "joke", "weather", "giphy", "pnr", "mustread", "poll", "hackernews", "hn", "HN", "motivate", "twitter", "screenshot", "memo", "cricnews", "help", "shorturl" ]
def main(): """ This script exports jokes from the hgp_crawler database to the hgp_webapp database. """ jokes = jokes_to_export(limit=100) if jokes: crawler_bulk = db.jokes.initialize_ordered_bulk_op() webapp_bulk = webapp_db.jokes.initialize_ordered_bulk_op() for joke in jokes: update_crawler(joke, crawler_bulk) # Convert to a python Joke object joke_obj = Joke.from_json(joke) # Then, store it in webapp as json w/ only the fields relevant # to webapp export_webapp(joke_obj.get_export_json(), webapp_bulk) # Only execute if any unexported jokes to execute on crawler_result = crawler_bulk.execute() print "Crawler result: \n{}".format(crawler_result) webapp_result = webapp_bulk.execute() print "\nWebapp result: \n{}".format(webapp_result) else: print "No unexported jokes found"
def index(request): # 首页博客数据 page = request.GET.get('page') qureyList = Articles.objects.filter(~Q( keyword="生活")).order_by('-created_at') p = Paginator(qureyList, 4) if page == None: page = '1' has_next = False has_pre = False list2 = [] nextPage = 0 prevPage = 0 try: pIndex = int(page) list2 = p.page(pIndex) has_next = list2.has_next() has_pre = list2.has_previous() nextPage = pIndex + 1 prevPage = pIndex - 1 except Exception as ret: pass # 首页生活数据 live = Articles.objects.filter(keyword="生活").order_by('-created_at') pLive = Paginator(live, 4) listLive = pLive.page(1) # 首页笑话 joke = Joke() joke_data = joke.get_joke() # return HttpResponse(joke_data) contex = { 'dataList': list2, 'has_next': has_next, 'has_pre': has_pre, 'nextPage': nextPage, 'prevPage': prevPage, 'jsonData': serializers.serialize("json", list2), 'liveList': listLive, 'joke': joke_data, } return render(request, 'myBlog/index.html', contex)
def get_posts_from_subreddit(token, subreddit, last_timestamp=None): """ Takes a subreddit in the form of a string and fetches all jokes from this subreddit page that were posted past the given timestamp. Returns: a list of Jokes. subreddit must be a string, last_timestamp must be a """ authorization = "bearer " + token headers = {"Authorization": authorization, "User-Agent": user_agent} jokes = [] sub_pages = ['new', 'rising', 'hot'] for sub_page in sub_pages: url = "https://oauth.reddit.com/r/{}/new".format(subreddit) response = requests.get( url, headers=headers ) # Most endpoints in the API don't work for some reason; this one does results = response.json() if 'data' not in results: return None data = results['data'] if 'children' not in data: return None posts = data['children'] for post in posts: actual_post = post['data'] upvotes = actual_post['ups'] downvotes = actual_post['downs'] title = actual_post['title'] content = actual_post['selftext'] sourceUrl = actual_post['url'] pubdate = datetime.fromtimestamp(int(actual_post['created'])) guid = sourceUrl if not last_timestamp or pubdate >= last_timestamp: # These jokes are new compared to the last times we checked. Keep them aJoke = Joke(content, 'reddit', sourceUrl, guid, pubdate=pubdate, title=title, upvotes=upvotes, downvotes=downvotes) jokes.append(aJoke) return jokes
def __init__(self): self.client = zulip.Client(site="https://nokia3310.zulipchat.com/api/") self.subscribe_all() # self.chatbot = ChatBot("Friday", trainer='chatterbot.trainers.ChatterBotCorpusTrainer') # self.chatbot.train("chatterbot.corpus.english") self.hacknews = Hackernews() self.dictionary = Dictionary() self.joke = Joke() self.motivate = Motivate() self.subkeys = [ "joke", "news", "motivate", "help", "hi", "hello", "hey", "stat.*", "define", ["what", "is"] ]
def dadjokes(): """ Gets JSON data from the icanhazdadjoke.com public API which returns a random 'dad' joke. """ r = requests.get("https://icanhazdadjoke.com", headers={"Accept": "application/json"}) r_joke = r.json() joke = Joke(r_joke["id"], r_joke["joke"]) print(joke)
def generate_joke(self, model, promt=""): """Generate the joke from given promt. :param model: model to use to generate joke. :param promt: (optional) promt for a joke, if not given generates the whole joke :return: `Joke` object """ if promt: print(f'[INFO] continue - Model: {model.name}') res = self._continue_joke(model, promt) else: res = self._get_joke_from_buffer() res['text'] = self._prettify_result(res['text']) joke_id = self.store.add_joke(**res) return Joke(id=joke_id, text=res['text'])
def getInfo(message_string): client_access_token = "PQCM32TG4TIECXXTP5EGA2AFDLHTAPMD" client = Wit(client_access_token) response = client.message(message_string) # print(response['entities']) list_resp = {} for entity in response['entities']: list_resp[response['entities'][str(entity)][0]['confidence']] = [ str(entity), response['entities'][str(entity)][0]['value'] ] confidence_list = list(list_resp) # print(confidence_list) confidence_list = sorted(confidence_list, reverse=True) check = list_resp[confidence_list[0]][0] value = list_resp[confidence_list[0]][1] if check == "calculate": # print(value) content = Calculator.calculate(str(value)) elif check == "intent" and value == "proxy_get": content = Proxy.getProxyStatus() content = "Proxies Status--->\n\n" + content elif check == "intent" and value == "proxy_area": content = Proxy.getWorkingProxy() content = "Working Proxies in Your Area \n\n" + content elif check == "intent" and value == "cricknews_get": content = Cricket().news() elif check == "intent" and value == "joke_tell": content = Joke.tellJoke() elif check == "intent" and value == 'coding_get': content = Coding().getList() elif check == "intent" and value == 'college_notice': content = Dean.getNotice() else: content = "I couldn't understand what you just said!! Please try again" # print(content) return content
def main(): Dad.speak() Joke.reply()
class ZulipBot(object): def f(self, f_stop): print('timer..') self.client.send_message({ "type": "stream", "to": 'general', "subject": 'swiming turtles', "content": 'Make sure to wash your hands.' }) if not f_stop.is_set(): # call f() again in 60 seconds threading.Timer(5 * 60, self.f, [f_stop]).start() def __init__(self): self.client = zulip.Client(site="https://nokia3310.zulipchat.com/api/") self.subscribe_all() # self.chatbot = ChatBot("Friday", trainer='chatterbot.trainers.ChatterBotCorpusTrainer') # self.chatbot.train("chatterbot.corpus.english") self.hacknews = Hackernews() self.dictionary = Dictionary() self.joke = Joke() self.motivate = Motivate() self.subkeys = [ "joke", "news", "motivate", "help", "hi", "hello", "hey", "stat.*", "define", ["what", "is"] ] def urls(self, link): urls = re.findall( 'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', link) return urls def subscribe_all(self): json = self.client.get_streams()["streams"] stream_names = [{"name": stream["name"]} for stream in json] self.client.add_subscriptions(stream_names) def help(self): message = "**Welcome to Friday Bot**\nFriday Bot has various subfields\nType `friday help <subfield>` to get help for specific subfield.\n" message += "\n**Subfields**\n" message += "`joke` - Get Jokes\n" message += "`motivate` - Get a motivational quote\n" message += "`news <topic>` - Get Top News Results about a topic\n" message += "`coronavirus stats` - Get the current Covid-19 global/country statistics \n" message += "`friday <question>`Ask any query related to coronavirus.\n" message += "\nIf you're bored Talk to Friday Bot, it will supercharge you" return message def help_sub(self, key): key = key message = "**Usage**\n" if key == "define": message += "`friday define <word>` - To Get Definition of the word\n" elif key == "joke": message += "`friday joke` - Get a Joke\n" elif key == "mustread": message += "`friday mustread @**<User Mention>** <message>` - Pass Important Messages to Team Members\n" elif key == "news" or key == "news": message += "`friday news` OR `friday hackernews` - Show Top 10 stories News\n" else: message = self.help() message += "\n{} is not a valid subfield\n".format(key) return message def send(self, type, msg, message): # print('sending to:' + msg['display_recipient'][0]['email']) if type == 'stream': stream_name = stream_name = msg['display_recipient'] stream_topic = msg['subject'] self.client.send_message({ "type": "stream", "to": stream_name, "subject": stream_topic, "content": message }) else: if 'friday' in msg['display_recipient'][0]['email']: i = 1 else: i = 0 id = msg['display_recipient'][i]['email'] self.client.send_message({ "type": "private", "to": id, "content": message }) def checkFriday(self, msg, type): content = msg["content"] #check for reference to friday if (type == 'private' and content[0] in ['hi', 'hello', 'hey']) or ( len(content) > 1 and (((content[0] in ['hi', 'hello', 'hey']) and (content[1] == 'friday' or re.match('@\*\*friday.*', content[1]))) or ((content[1] in ['hi', 'hello', 'hey']) and (content[0] == 'friday' or re.match('@\*\*friday.*', content[0]))))): message = getHelloMessage(msg) self.send(type, msg, message) return elif type == 'stream' and (content[0] == 'friday' or '**friday' in content[0]): if len(content) > 1: index = 1 else: index = 0 elif type == 'private': if (content[0] == 'friday' or '**friday' in content[0]) and len(content) > 1: index = 1 else: index = 0 else: return # #check for subkey # # flag = 0 # for i in range(0, len(self.subkeys)): # for j in range(0, len(content)): # if( re.match(self.subkeys[i], content[j])): # flag = 1 # key = j # #set a value here as index of condition # #then replace all elifs below (enws, joke) with that index # break # if(flag == 1): # break # else: # return print('index is:' + str(index)) message = '' if ('family' in content or True in [bool(re.match('friend.*', i)) for i in content] or True in [bool(re.match('relative.*', i)) for i in content] or checkListContinsWords( list=content, words=[ 'brother', 'sister', 'mother', 'father', 'uncle', 'aunt', 'girlfriend', 'boyfriend', 'son', 'daughter' ] + ['pet', 'dog', 'cat', 'mouse', 'hamster', 'monkey'], relation='any')): if (True in [bool(re.match('symptom.*', i)) for i in content] or True in [bool(re.match('sign.*', i)) for i in content] ) or ('has' in content or 'got' in content or 'have' in content) or (checkListContinsWords( content, symptoms + ['symptom', 'coronavirus', 'covid'], 'any')): message = 'The symptoms of coronavirus (fever, cough, sore throat, and trouble breathing) can look a lot like illnesses from other viruses. If a family member or friend or relative has trouble breathing, go to the emergency room or call an ambulance right away.\n\nCall your doctor if someone in your family or friends or a relative has a fever, cough, sore throat, or other flu-like symptoms. If this person has been near someone with coronavirus or lived in or traveled to an area where lots of people have coronavirus, tell the doctor. The doctor can decide whether your family member:\n\n\t* can be treated at home\n\t* should come in for a visit\n\t* can have a telehealth visit\n\t* needs to be tested for coronavirus' self.send(type, msg, message) familyFlag = True elif checkListContinsWords( list=content, words=['has', 'have', 'show', 'display', 'visible', 'draw'], relation='any') and 'i' in content and (checkListContinsWords( list=content, words=symptoms.extend(['symptom', 'coronavirus', 'covid']), relation='any')): message = 'If you develop emergency warning signs for COVID-19 get medical attention immediately.' self.send(type, msg, message) return if (checkListContinsWords( list=content, words=['how', 'long', 'symptom'], relation='all') or checkListContinsWords(list=content, words=['how', 'long', 'sign'], relation='all') or checkListContinsWords(list=content, words=['when', 'will', 'symptom'], relation='all') or checkListContinsWords(list=content, words=['when', 'will', 'symptom'], relation='all')): message = 'The symptoms may appear 2-14 days after exposure to the virus:' self.send(type, msg, message) return if (content[index:index + 2] == ['what', 'is' ]) or content[index] == 'define': if (True in [bool(re.match('.*coronavirus.*', i)) for i in content] or (True in [bool(re.match('.*covid.*', i)) for i in content])): message = 'Coronaviruses are a large family of viruses that are known to cause illness ranging from the common cold to more severe diseases such as Middle East Respiratory Syndrome (MERS) and Severe Acute Respiratory Syndrome (SARS).\nCoronaviruses are a large family of viruses that are known to cause illness ranging from the common cold to more severe diseases such as Middle East Respiratory Syndrome (MERS) and Severe Acute Respiratory Syndrome (SARS).' self.send(type, msg, message) return elif ('of' in content): i = content.index('of') word = content[i + 1] message = word + ': ' + self.dictionary.words( word).capitalize() self.send(type, msg, message) return elif len(content) == index + 3: word = content[index + 2] message = word + ': ' + self.dictionary.words( word).capitalize() self.send(type, msg, message) return elif len(content) == index + 2: word = content[index + 1] message = word + ': ' + self.dictionary.words( word).capitalize() self.send(type, msg, message) return if checkListContinsWords(list=content, words=['incubation'], relation='any'): message = 'The symptoms may appear 2-14 days after exposure to the virus:' self.send(type, msg, message) return elif (content[index:index + 2] == ['what', 'are']): if checkListContinsWords(list=content, words=['symptom', 'sign'], relation='any'): message = 'Common signs include respiratory symptoms, fever, cough, shortness of breath, and breathing difficulties. In more severe cases, infection can cause pneumonia, severe acute respiratory syndrome, kidney failure and even death.' self.send(type, msg, message) return # if (True in [bool(re.match('.*coronavirus.*', i)) for i in content] or (True in [bool(re.match('.*covid.*', i)) for i in content])): # message = 'Coronaviruses are a large family of viruses that are known to cause illness ranging from the common cold to more severe diseases such as Middle East Respiratory Syndrome (MERS) and Severe Acute Respiratory Syndrome (SARS).\nCoronaviruses are a large family of viruses that are known to cause illness ranging from the common cold to more severe diseases such as Middle East Respiratory Syndrome (MERS) and Severe Acute Respiratory Syndrome (SARS).' # self.send(type, msg, message) elif (content[index] == 'can'): if (True in [bool(re.match('.*transmit.*', i)) for i in content]): message = 'The novel coronavirus can definitely be transmitted from an infected person to another person.' self.send(type, msg, message) return if (True in [bool(re.match('.*pet.*', i)) for i in content] or True in [bool(re.match('.*dog.*', i)) for i in content] or True in [bool(re.match('.*cat.*', i)) for i in content]): message += '\nThe answer for your pets varies. Visit: https://www.independent.co.uk/life-style/health-and-families/coronavirus-pet-dog-can-you-catch-it-transmission-a9376926.html' self.send(type, msg, message) return if ['no', 'symptom' ] in content or ['no', 'symptoms'] in content or ( 'without' in content and True in [bool(re.match('.*symptom.*', i)) for i in content]): message = 'It is possisble for you to have Covid-19 without showing any symptoms and be able to transmit it to others.' self.send(type, msg, message) return if ((True in [bool(re.match('.*coronavirus.*', i)) for i in content] or (True in [bool(re.match('.*covid.*', i)) for i in content]))) and 'get' in content: message = 'You can catch coronavirus from others who have the virus. This happens when an infected person sneezes or coughs, sending tiny droplets into the air. These can land in the nose, mouth, or eyes of someone nearby, or be breathed in. You also can get infected if they touch an infected droplet on a surface and then touch their own nose, mouth, or eyes.' self.send(type, msg, message) return if 'how' in content or len([ (x, y) for x, y in zip(['am', 'i'][0:], ['am', 'i'][1:]) if x in content and y in content ]) > 0 or len([(x, y) for x, y in zip(['i', 'am'][0:], ['i', 'am'][1:]) if x in content and y in content]) > 0: if (('likely' in content or 'risk' in content) and ((True in [bool(re.match('.*coronavirus.*', i)) for i in content]) or (True in [bool(re.match('.*covid.*', i)) for i in content]) or 'disease' in content or 'virus' in content or len([(x, y) for x, y in zip(['get', 'it'][0:], ['get', 'it'][1:]) if x in content and y in content]) > 0 or len([(x, y) for x, y in zip(['catch', 'it'][0:], ['catch', 'it'][1:]) if x in content and y in content]) > 0 or len([(x, y) for x, y in zip(['contract', 'it'][0:], ['contract', 'it'][1:]) if x in content and y in content]) > 0) and (True in [bool(re.match('get.*', i)) for i in content] or True in [bool(re.match('.*contract.*', i)) for i in content] or True in [bool(re.match('catch.*', i)) for i in content] or 'from' in content)) or checkListContinsWords( list=content, words=['safe'], relation='any'): if 'i' in content: message = 'As long as you are inside your house and following quarantine.. you are safe' self.send(type, msg, message) return elif checkListContinsWords(list=content, words=['pet'], relation='any'): message = 'The answer for your pets varies. Visit: https://www.independent.co.uk/life-style/health-and-families/coronavirus-pet-dog-can-you-catch-it-transmission-a9376926.html' self.send(type, msg, message) return #add health worker elif ((True in [bool(re.match('.*coronavirus.*', i)) for i in content] or (True in [bool(re.match('.*covid.*', i)) for i in content]))) and 'get' in content: message = 'You can catch coronavirus from others who have the virus. This happens when an infected person sneezes or coughs, sending tiny droplets into the air. These can land in the nose, mouth, or eyes of someone nearby, or be breathed in. You also can get infected if they touch an infected droplet on a surface and then touch their own nose, mouth, or eyes.' self.send(type, msg, message) return elif checkListContinsWords( list=content, words=['pet', 'dog', 'cat', 'mouse', 'hamster', 'monkey'], relation='any') and checkListContinsWords( list=content, words=['safe', 'danger', 'vulnerabl', 'risk'], relation='any'): message = 'The answer for your pets varies. Visit: https://www.independent.co.uk/life-style/health-and-families/coronavirus-pet-dog-can-you-catch-it-transmission-a9376926.html' self.send(type, msg, message) return if (content[index:index + 2] in [['how', 'to'], ['how', 'often'], ['how', 'much'], ['how', 'is'], ['how', 'should'], ['how', 'can'], ['how', 'may'], ['how', 'could'], ['relative', 'it'], ['what', 'should'], ['what', 'can'], ['what', 'could'], ['is', 'there'], ['are', 'there'], ['should', 'i'], ['should', 'we']]): if checkListContinsWords(list=content, words=['travel', 'plan'], relation='all'): message = 'Is there any place abroad that’s safe to travel right now? In a nutshell, no. The novel coronavirus has spread to more than 100 countries and every continent except for Antarctica.\nI recommend you don\'t travel anywhere outside, even another state or town for atleast a few months. This is for your own safety' self.send(type, msg, message) return elif checkListContinsWords(list=content, words=['out'], relation='any'): message = 'You should not go outside for any purpose other than for groceries, washroom stuff or medical stuff and that too only once a day for a short time.\nAnd remember, don\'t go too far from your home and always carry your ID proof when out!' self.send(type, msg, message) return elif ('family' in content or True in [bool(re.match('friend.*', i)) for i in content] or True in [bool(re.match('relative.*', i)) for i in content]): if (True in [bool(re.match('symptom.*', i)) for i in content] or True in [bool(re.match('sign.*', i)) for i in content]) or ('has' in content or 'got' in content): if (familyFlag == True): familyFlag = False else: message = 'The symptoms of coronavirus (fever, cough, sore throat, and trouble breathing) can look a lot like illnesses from other viruses. If a family member or friend or relative has trouble breathing, go to the emergency room or call an ambulance right away.\n\nCall your doctor if someone in your family or friends or a relative has a fever, cough, sore throat, or other flu-like symptoms. If this person has been near someone with coronavirus or lived in or traveled to an area where lots of people have coronavirus, tell the doctor. The doctor can decide whether your family member:\n\n\t* can be treated at home\n\t* should come in for a visit\n\t* can have a telehealth visit\n\t* needs to be tested for coronavirus' self.send(type, msg, message) return if (True in [bool(re.match('.*prevent.*', i)) for i in content] or True in [bool(re.match('.*protect.*', i)) for i in content]): message = 'Standard recommendations to reduce exposure to and transmission of a range of illnesses include maintaining basic hand and respiratory hygiene, and safe food practices and avoiding close contact, when possible, with anyone showing symptoms of respiratory illness such as coughing and sneezing. \n#StayHomeStaySafe' self.send(type, msg, message) return elif ( (True in [bool(re.match('.*cure.*', i)) for i in content] or True in [bool(re.match('.*treat.*', i)) for i in content] or True in [bool(re.match('.*vaccin.*', i)) for i in content]) and (True in [bool(re.match('.*coronavirus.*', i)) for i in content] or (True in [bool(re.match('.*covid.*', i)) for i in content]) or len([(x, y) for x, y in zip(['the', 'disease'][0:], ['the', 'disease'][1:]) if x in content and y in content]) > 0 or len([(x, y) for x, y in zip(['for', 'it'][0:], ['for', 'it'][1:]) if x in content and y in content]) > 0 or len([(x, y) for x, y in zip(['the', 'virus'][0:], ['the', 'virus'][1:]) if x in content and y in content]) > 0)): message = 'There is no specific treatment for disease caused by a novel coronavirus. However, many of the symptoms can be treated and therefore treatment based on the patient’s clinical condition. Moreover, supportive care for infected persons can be highly effective.' self.send(type, msg, message) return elif checkListContinsWords(list=content, words=['motivat'], relation='any'): message = self.motivate.get_quote() self.send(type, msg, message) return elif content[index] == "joke" or (content[index] in ["tell", "crack", "show"] and "joke" in content[index + 1:]): text = self.joke.tellJoke() self.send(type, msg, text) elif 'news' in content[index:]: print('news1') if len([x for x in content[index:] if re.match('corona.*', x) ]) > 0 or len([ x for x in content[index:] if re.match('covid.*', x) ]) > 0: print('news corona india') if 'india' in content[index:]: news = self.hacknews.get_hackernews('coronavirus india') self.send(type, msg, news) else: print('news corona') news = self.hacknews.get_hackernews('coronavirus') self.send(type, msg, news) elif content[index] == "help" and len(content) == index + 1: message = self.help() self.send(type, msg, message) elif content[index] == "help" and len(content) > index + 1: subkey = content[index + 1] message = self.help_sub(subkey) self.send(type, msg, message) elif ( len([x for x in content[index:] if re.match('corona.*', x)]) > 0 or len([x for x in content[index:] if re.match('covid.*', x)]) > 0 ) and (len([x for x in content[index:] if re.match('stat.*', x)]) > 0 or len([x for x in content[index:] if re.match('statistic.*', x) ]) > 0): j = -1 for i in content: if i in countries: j = countries.index(i) break if j >= 0: x = requests.get('https://api.covid19api.com/summary').json() x = x['Countries'] for i in range(0, len(x)): if (x[i]['CountryCode'] == list( pycountry.countries)[j].alpha_2): stats = 'New Confirmed: ' + str( x[i]['NewConfirmed'] ) + '\nTotal Confirmed: ' + str( x[i]['TotalConfirmed']) + '\nNew Deaths: ' + str( x[i]['NewDeaths']) + '\nTotal Deaths: ' + str( x[i]['TotalDeaths'] ) + '\nNew Recovered: ' + str( x[i]['NewRecovered'] ) + '\nTotal Recovered: ' + str( x[i]['TotalRecovered']) self.send( type, msg, 'Here are ' + countries[j][0].upper() + countries[j][1:] + '\'s statistics for today\n\n' + stats) else: #call api x = requests.get( 'https://api.covid19api.com/world/total').json() stats = '\nTotal Confirmed: ' + str( x['TotalConfirmed']) + '\nTotalDeaths: ' + str( x['TotalDeaths']) + '\nTotalRecovered: ' + str( x['TotalRecovered']) #global # self.send(type, msg, stats) self.send(type, msg, 'Here are the global statistics \n\n' + stats) self.send( type, msg, '\n\ndone Global stats. \nFor countries stats, write: friday [country] covid19 stats' ) elif "friday" in content: message = "Alas! Finally you called me :blush:" self.send(type, msg, message) else: return def process(self, msg): pprint.pprint(msg) print('\n\n' + msg['type'] + ' - ' + (msg['display_recipient'] + ' - ' + msg['subject'] if msg['type'] == 'stream' else '') + '\n' + msg['sender_full_name'] + ' sent a message: ' + str([x.lower() for x in msg['content'].split()]) + '\n\n') sender_email = msg["sender_email"] if sender_email == BOT_MAIL: return content = msg["content"].split() content = [x.lower() for x in content] content = [x.replace("?", "") for x in content] content = [x.replace(",", "") for x in content] content = [x.replace("!", "") for x in content] msg['content'] = content if (msg['type'] == 'private'): type = 'private' self.checkFriday(msg, type) else: type = 'stream' self.checkFriday(msg, type)
class ZulipBot(object): def __init__(self): self.client = zulip.Client(site="https://fazeup.zulipchat.com/api/") self.subscribe_all() self.hacknews = Hackernews() self.trans = Translate() self.movie = Movie() self.lyrics = Lyrics() self.holiday = Holiday() self.currency = Currency() self.cricket = Cricket() # self.chatbot.train("chatterbot.corpus.english") self.crypto = Crypto() self.trans = Translate() self.g = Giphy() self.w = WikiPedia() # self.tw = Twimega() # self.motivate = Motivate() self.shortenedurl = Urlshortener() self.geo = Geocode() self.weather = Weather() self.dict_ = Dictionary() self.joke = Joke() self.pnr = Pnr() self.mustread = Mustread() self.ss = Ss() self.cricket = Cricket() self.poll = Poll() print("done init") self.subkeys = [ "crypto", "translate", "define", "joke", "weather", "giphy", "pnr", "mustread", "poll", "hackernews", "hn", "HN", "motivate", "twitter", "screenshot", "memo", "cricnews", "help", "shorturl", "movie", "currency", "holiday", "lyrics" ] def subscribe_all(self): json = self.client.get_streams()["streams"] streams = [{"name": stream["name"]} for stream in json] self.client.add_subscriptions(streams) def process(self, msg): content = msg["content"].split() sender_email = msg["sender_email"] ttype = msg["type"] stream_name = msg['display_recipient'] stream_topic = msg['subject'] print(content) if sender_email == BOT_MAIL: return print("Sucessfully heard.") if content[0].lower() == "magnus" or content[0] == "@**magnus**": if content[1].lower() == "translate": ip = content[2:] ip = " ".join(ip) message = self.trans.translate(ip) self.client.send_message({ "type": "stream", "subject": msg["subject"], "to": msg["display_recipient"], "content": message }) if content[1].lower() == "movie": ip = content[2:] ip = " +".join(ip) message = self.movie.about(ip) self.client.send_message({ "type": "stream", "subject": msg["subject"], "to": msg["display_recipient"], "content": message }) if content[1].lower() == "lyrics": author = content[2] title = content[3:] title = " ".join(title) message = self.lyrics.about(author, title) self.client.send_message({ "type": "stream", "subject": msg["subject"], "to": msg["display_recipient"], "content": message }) if content[1].lower() == 'holiday': quote_data = self.holiday.holiday() self.client.send_message({ "type": "stream", "to": stream_name, "subject": stream_topic, "content": quote_data }) if content[1].lower() == 'currency': x = content[2] y = content[3] quote_data = self.currency.currency(x, y) self.client.send_message({ "type": "stream", "to": stream_name, "subject": stream_topic, "content": quote_data }) if content[1].lower() == "cricnews": news = self.cricket.news() self.client.send_message({ "type": "stream", "subject": msg["subject"], "to": msg["display_recipient"], "content": news }) if content[1].lower() == 'hackernews' or content[1].lower( ) == 'hn' or content[1].lower() == 'HN': news = self.hacknews.get_hackernews() self.client.send_message({ "type": "stream", "to": stream_name, "subject": stream_topic, "content": news }) if content[1].lower() == "crypto": if len(content) > 3 and content[3].lower() == "in": message = self.crypto.get_price(content[2], content[4]) else: message = self.crypto.get_price(content[2]) self.client.send_message({ "type": "stream", "subject": msg["subject"], "to": msg["display_recipient"], "content": message }) if content[1].lower() == "joke": text = self.joke.tellJoke() self.client.send_message({ "type": "stream", "subject": msg["subject"], "to": msg["display_recipient"], "content": text }) # if content[1].lower() == 'motivate': # quote_data = self.motivate.get_quote() # self.client.send_message({ # "type": "stream", # "to": stream_name, # "subject": stream_topic, # "content": quote_data # }) if content[1].lower() == "mustread": email = self.mustread.get_email(self.client.get_members(), msg["content"]) senderusername = self.mustread.get_username( self.client.get_members(), msg["sender_email"]) print(email) self.client.send_message({ "type": "private", "to": email, "content": "**" + senderusername + "** mentioned you in must read ! \nThe message says : " + " ".join(content[2:]) }) if content[1].lower() == "pnr": message = self.pnr.get_pnr(content[2]) self.client.send_message({ "type": "stream", "subject": msg["subject"], "to": msg["display_recipient"], "content": message }) if content[1].lower() == "screenshot": result = self.ss.get_ss(content[2]) print(result) self.client.send_message({ "type": "stream", "subject": msg["subject"], "to": msg["display_recipient"], "content": "Screenshot taken :wink:\n[Screenshot Link](" + result + ")" }) if content[1].lower() == "poll": if content[2].lower() == "create": print(",".join(content[4:])) idno = self.poll.create_poll(content[3], content[4:]) self.client.send_message({ "type": "stream", "subject": msg["subject"], "to": msg["display_recipient"], "content": "Poll Successfully Created and id is : **" + str(idno) + "**" }) elif content[2].lower() == "show": if content[3].lower() == "all": polldetails = self.poll.show_allpoll() self.client.send_message({ "type": "stream", "subject": msg["subject"], "to": msg["display_recipient"], "content": polldetails }) else: polldetails = self.poll.show_poll(content[3]) self.client.send_message({ "type": "stream", "subject": msg["subject"], "to": msg["display_recipient"], "content": "Poll ID: **" + polldetails["id"] + "**\n Question : **" + polldetails["pollname"] + "**\nOption : **" + polldetails["options"] + "**\n Votes : **" + polldetails["votes"] + "**" }) elif content[2].lower() == "vote": vote = self.poll.vote_poll(content[3], content[4]) self.client.send_message({ "type": "stream", "subject": msg["subject"], "to": msg["display_recipient"], "content": "Your Vote Has Been Recorded!" }) elif content[2].lower() == "delete": if content[3].lower() == "all": deleted = self.poll.delete_allpoll() self.client.send_message({ "type": "stream", "subject": msg["subject"], "to": msg["display_recipient"], "content": "all polls has been removed from database" }) else: deleted = self.poll.delete_poll(content[3]) self.client.send_message({ "type": "stream", "subject": msg["subject"], "to": msg["display_recipient"], "content": "The given poll has been removed from database" }) if content[1].lower() == "shorturl": short_url = self.shortenedurl.get_shorturl(content) self.client.send_message({ "type": "stream", "to": stream_name, "subject": stream_topic, "content": short_url }) if content[1] not in self.subkeys: ip = content[1:] ip = " ".join(ip) message = self.Chatbot.get_response(ip).text self.client.send_message({ "type": "stream", "subject": msg["subject"], "to": msg["display_recipient"], "content": message }) elif "magnus" in content and content[0] != "magnus": self.client.send_message({ "type": "stream", "subject": msg["subject"], "to": msg["display_recipient"], "content": "Hey there! :blush:" }) else: return
def handle_message(self, message: Dict[str, Any], bot_handler: Any) -> None: string = message['content'].split() content = "something went wrong" check = string[0].lower() if check == "calculate": content = Calculator.calculate(string) elif check == "coding_contest": content = Coding().getList() elif check.lower() == 'define': dictword = string[1] content = Dictionary.words(dictword) elif check.lower() == 'telljoke': content = Joke.tellJoke() elif check == "cricknews": content = Cricket().news() elif check == "proxy": if len(string) > 1: if string[1].lower() == "working": content = Proxy.getWorkingProxy() content = "Working Proxies in Your Area \n\n" + content elif string[1].lower() == "help": content = Proxy.getHelpList() else: content = WitHandler.getInfo(message['content']) else: content = Proxy.getProxyStatus() content = "Proxies Status--->\n\n" + content elif check.lower() == "play": try: pid = check_output(["pidof"], "mpg321") os.kill(int(pid), signal.SIGKILL) os.remove("hello.mp3") content = Music.main(string[1:]) except: content = Music.main(string[1:]) bot_handler.send_reply(message, "playing song ") elif check == "stop": pid = check_output(["pidof", "mpg321"]) #print(int(pid)) os.kill(int(pid), signal.SIGKILL) content = "Bye........:)" bot_handler.send_reply(message, content) elif check == "college_notice": content = Dean.getNotice() elif check == "add" and string[1] == "meeting": content = "Enter <Date> as <dd/mm/yyyy> <Time> as <hrs:min> and am/pm and purpose(one word)" elif len(string[0].split('/')) == 3: res = Meeting.AddMeeting(string) if res.lower() == "ok": content = "New Meeting successfully Added " else: content = res elif check == "show" and string[1].lower() == "meetings": content = Meeting.ShowMeeting() elif check == "pnr" and string[1].lower() == "status": content = Pnr.getpnr(string[2]) elif check == "message" or check == "find" or check == "where": content = Send_message.sendMessage(string) # elif check=="mood": # Mood.capture(); elif check == "symptom": string_1 = " " gender = string[1] dob = string[2] st = string[3:] string_1 = string_1.join(st) content = Sympton.getExactSympton(string_1) try: content = "Please Tell me clearly\n" + content except: p = int(content) content = Sympton.getIssueId(str(p), gender, dob) elif check == "search": st = " " strlist = string[1:] st = st.join(strlist) st = FriendLocation.plot(st) if "https" in st: webbrowser.open(st) content = "check out below link \n" + st else: content = "Please type exact name :)\n" + st elif check == "getjobs": content = JOBS.getjobs() elif check == "translate": stri = " " stri = stri.join(list(string[1:])) content = Translate.translate(stri) elif check == "help": Help.Message() content = "Message sent" elif check == "nearby": content = Nearby.Place(string[1]) else: #print(message['content']) content = WitHandler.getInfo(message['content']) bot_handler.send_reply(message, content)
import requests #The Standard module for requesting from web import json #The JSON Module import pyttsx3 #Python Text to Speech Module from joke import Joke url = "https://official-joke-api.appspot.com/random_ten" #API URL for Jokes response = requests.get(url) print(response.status_code) jsonData = json.loads(response.text) #Intializing Array Object jokes = [] for j in jsonData: setup = j["setup"] punchline = j["punchline"] joke = Joke(setup, punchline) jokes.append(joke) print(f"Got {len(jokes)} jokes") for joke in jokes: # print(joke) pyttsx3.speak("setup") pyttsx3.speak(joke.setup) pyttsx3.speak("The Punch Line") pyttsx3.speak(joke.punchline)
def main(): dad = Dad() joke = Joke() dad.speak() joke.reply()
now = datetime.now() week_difference = timedelta(days=7) week_ago = now - week_difference # TODO: Fetch jokes we saw posted at least a week ago jokes = db.jokes.find( { 'content': { # Content not found "$in": [None, ''] }, 'pubdate': { # Published at least a week ago '$lt': week_ago, }, 'visited': { # Unvisited '$in': [None, False] } }).limit(NUM_JOKES) if jokes: # Convert joke json to Joke objects jokes = map(lambda joke: Joke.fromJson(joke), jokes) crawlContent.crawlContent(jokes) hgp_jokes.saveJokes(jokes) print jokes print("--- %s seconds ---" % round(time.time() - start_time, 2))
from dad import Dad from joke import Joke if __name__ == "__main__": dad = Dad() joke = Joke() dad.speak() joke.reply()
def main(): d = Dad() d.speak() j = Joke() j.reply()
def joke(): r = requests.get('https://icanhazdadjoke.com', headers={"Accept":"application/json"}) raw_joke = r.json(); joke = Joke(raw_joke['id'], raw_joke['joke']) return joke
class ZulipBot(object): def __init__(self): self.client = zulip.Client(site="https://chunkzz.zulipchat.com/api/") self.subscribe_all() self.chatbot = ChatBot( "Omega", trainer='chatterbot.trainers.ChatterBotCorpusTrainer') self.chatbot.train("chatterbot.corpus.english") self.crypto = Crypto() self.trans = Translate() self.g = Giphy() self.w = WikiPedia() self.tw = Twimega() self.motivate = Motivate() self.shortenedurl = Urlshortener() self.hacknews = Hackernews() self.geo = Geocode() self.weather = Weather() self.dict_ = Dictionary() self.joke = Joke() self.pnr = Pnr() self.mustread = Mustread() self.ss = Ss() self.cricket = Cricket() self.poll = Poll() self.subkeys = [ "crypto", "translate", "define", "joke", "weather", "giphy", "pnr", "mustread", "poll", "hackernews", "hn", "HN", "motivate", "twitter", "screenshot", "memo", "cricnews", "help", "shorturl" ] def urls(self, link): urls = re.findall( 'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', link) return urls def subscribe_all(self): json = self.client.get_streams()["streams"] streams = [{"name": stream["name"]} for stream in json] self.client.add_subscriptions(streams) def help(self): message = "**Welcome to Omega Bot**\nOmega Bot has various subfields\nType `omega help <subfield>` to get help for specific subfield.\n" message += "\n**Subfields**\n" message += "`crypto` - Get Crypto Currency Prices\n" message += "`translate` - Translate Foreign Languages to English\n" message += "`define` - Get Word Meanings\n" message += "`joke` - Get Jokes\n" message += "`weather` - Get Weather Details\n" message += "`giphy` - Get GIFs from Giphy\n" message += "`pnr` - Get PNR Status\n" message += "`mustread` - Share Must Read Messages to Teammates\n" message += "`poll` - Create Amazing Polls in Zulip\n" message += "`hn` - Get Top Hacker News Results\n" message += "`motivate` - Get Motivational Quotes\n" message += "`twitter` - Tweet Directly from Zulip\n" message += "`screenshot` - Take Screenshot of Web Pages\n" message += "`memo` - Create Memos in Cloud\n" message += "`cricnews` - Get Cricket News\n" message += "`shorturl` - Create goo.gl short URLs\n" message += "\nIf you're bored Talk to Omega Bot, it will supercharge you" return message def help_sub(self, key): key = key.lower() message = "**Usage**\n" if key == "crypto": message += "`omega crypto <crypto-currency-code>` - To Get Price in USD\n" message += "`omage crypto <crypto-currency-code> in <currency>` - To Get Price in Specified Currency\n" elif key == "translate": message += "`omega translate <phrase to be translated>` - To Get Translate from Foreign Language to English\n" elif key == "define": message += "`omega define <word>` - To Get Definition of the word\n" elif key == "joke": message += "`omega joke` - Get a Joke\n" elif key == "weather": message += "`omega weather <location>` - Get the weather details of the given place\n" elif key == "giphy": message += "`omega giphy <search word>` - Get a random GIF from Giphy related to the given search word\n" elif key == "pnr": message += "`omega pnr <valid pnr number>` - Get PNR Details of the Given PNR number\n" elif key == "mustread": message += "`omega mustread @**<User Mention>** <message>` - Pass Important Messages to Team Members\n" elif key == "poll": message += "`omega poll create <number of choices> question <question> option <option1> <option2>...` - To Create a New Poll. It will return with a Poll ID Number\n" message += "`omega poll vote <POLL_ID> <Choice>` - To Vote for specified option\n" message += "`omega poll show all` - List all available polls\n" message += "`omega poll show <ID>` - List all details from specified Poll ID\n" message += "`omega poll delete all` - Delete All Polls\n" message += "`omega poll delete <ID>` - Delete Poll with specified ID\n" elif key == "hn" or key == "hackernews": message += "`omega hn` OR `omega hackernews` - Show Top 10 stories from Hacker News\n" elif key == "motivate": message += "`omega motivate` - Get a refreshing and motivating quote\n" elif key == "twitter": message += "`omega twitter post <tweet>` - Post a Tweet with given tweet\n" message += "`omega twitter post_image <image_url> <tweet>` - Post a Tweet with given tweet and image url\n" elif key == "screenshot": message += "`omega screenshot <website url>` - Take a screenshot of the given url\n" elif key == "memo": message += "`omega memo <filename>` - Creates a New Memo file and returns its link\n" elif key == "cricnews": message += "`omega cricnews` - Get top 10 Cricket News\n" elif key == "shorturl": message += "`omega shorturl <url>` - Get a Shorten URL from goo.gl\n" else: message = self.help() message += "\n{} is not a valid subfield\n".format(key) return message def process(self, msg): content = msg["content"].split() sender_email = msg["sender_email"] ttype = msg["type"] stream_name = msg['display_recipient'] stream_topic = msg['subject'] print(content) if sender_email == BOT_MAIL: return print("yeah") if content[0].lower() == "omega" or content[0] == "@**omega**": if content[1].lower() == "crypto": if len(content) > 3 and content[3].lower() == "in": message = self.crypto.get_price(content[2], content[4]) else: message = self.crypto.get_price(content[2]) self.client.send_message({ "type": "stream", "subject": msg["subject"], "to": msg["display_recipient"], "content": message }) if content[1].lower() == "translate": ip = content[2:] ip = " ".join(ip) message = self.trans.translate(ip) self.client.send_message({ "type": "stream", "subject": msg["subject"], "to": msg["display_recipient"], "content": message }) if content[1].lower() == "define": word = content[2].lower() result = self.dict_.words(word) print(result) self.client.send_message({ "type": "stream", "subject": msg["subject"], "to": msg["display_recipient"], "content": "**" + word + " means :" + "**" + '\n' + result }) if content[1].lower() == "screenshot": result = self.ss.get_ss(content[2]) print(result) self.client.send_message({ "type": "stream", "subject": msg["subject"], "to": msg["display_recipient"], "content": "Screenshot taken :wink:\n[Screenshot Link](" + result + ")" }) if content[1].lower() == "joke": text = self.joke.tellJoke() self.client.send_message({ "type": "stream", "subject": msg["subject"], "to": msg["display_recipient"], "content": text }) if content[1].lower() == "weather": place = " ".join(content[2:]) try: result = self.weather.getWeather(self.geo.convert(place)) message = "**" + "Weather update of " + place + "**" + "\n" + "Summary : " + "**" + result[ "currently"][ "summary"] + "**" + "\n" + "Temparature : " + "**" + str( result["currently"]["temperature"] ) + "**" + '\n' + "Apparent Temparature : " + "**" + str( result["currently"]["apparentTemperature"] ) + "**" + "\n" + "Dew Point : " + "**" + str( result["currently"]["dewPoint"] ) + "**" + "\n" + "Humidity : " + "**" + str( result["currently"]["humidity"]) + "**" except KeyError: message = "Weather Info is Not Working Right Now" self.client.send_message({ "type": "stream", "subject": msg["subject"], "to": msg["display_recipient"], "content": message }) if content[1].lower() == "giphy": text = content[2:] text = " ".join(text) im = str(self.g.search(text)) message = im[:im.find("?")] self.client.send_message({ "type": "stream", "subject": msg["subject"], "to": msg["display_recipient"], "content": message }) if content[1].lower() == 'memo': credentials = gdrivesignin.get_credentials() http = credentials.authorize(httplib2.Http()) service = discovery.build('drive', 'v3', http=http) file_metadata = {'name': content[2], 'mimeType': "text/plain"} file = service.files().create(body=file_metadata, fields='id').execute() web_link = service.files().get( fileId=file['id'], fields="webViewLink").execute()['webViewLink'] self.client.send_message({ "type": "stream", "to": stream_name, "subject": stream_topic, "content": 'Memo created.\nView & edit it at: ' + web_link }) if content[1].lower() == "pnr": message = self.pnr.get_pnr(content[2]) self.client.send_message({ "type": "stream", "subject": msg["subject"], "to": msg["display_recipient"], "content": message }) if content[1].lower() == "mustread": email = self.mustread.get_email(self.client.get_members(), msg["content"]) senderusername = self.mustread.get_username( self.client.get_members(), msg["sender_email"]) print(email) self.client.send_message({ "type": "private", "to": email, "content": "**" + senderusername + "** mentioned you in must read ! \nThe message says : " + " ".join(content[2:]) }) if content[1].lower() == "poll": if content[2].lower() == "create": print(",".join(content[4:])) idno = self.poll.create_poll(content[3], content[4:]) self.client.send_message({ "type": "stream", "subject": msg["subject"], "to": msg["display_recipient"], "content": "Poll Successfully Created and id is : **" + str(idno) + "**" }) elif content[2].lower() == "show": if content[3].lower() == "all": polldetails = self.poll.show_allpoll() self.client.send_message({ "type": "stream", "subject": msg["subject"], "to": msg["display_recipient"], "content": polldetails }) else: polldetails = self.poll.show_poll(content[3]) self.client.send_message({ "type": "stream", "subject": msg["subject"], "to": msg["display_recipient"], "content": "Poll ID: **" + polldetails["id"] + "**\n Question : **" + polldetails["pollname"] + "**\nOption : **" + polldetails["options"] + "**\n Votes : **" + polldetails["votes"] + "**" }) elif content[2].lower() == "vote": vote = self.poll.vote_poll(content[3], content[4]) self.client.send_message({ "type": "stream", "subject": msg["subject"], "to": msg["display_recipient"], "content": "Your Vote Has Been Recorded!" }) elif content[2].lower() == "delete": if content[3].lower() == "all": deleted = self.poll.delete_allpoll() self.client.send_message({ "type": "stream", "subject": msg["subject"], "to": msg["display_recipient"], "content": "all polls has been removed from database" }) else: deleted = self.poll.delete_poll(content[3]) self.client.send_message({ "type": "stream", "subject": msg["subject"], "to": msg["display_recipient"], "content": "The given poll has been removed from database" }) if content[1].lower() == 'motivate': quote_data = self.motivate.get_quote() self.client.send_message({ "type": "stream", "to": stream_name, "subject": stream_topic, "content": quote_data }) if content[1].lower() == "shorturl": short_url = self.shortenedurl.get_shorturl(content) self.client.send_message({ "type": "stream", "to": stream_name, "subject": stream_topic, "content": short_url }) if content[1].lower() == 'hackernews' or content[1].lower( ) == 'hn' or content[1].lower() == 'HN': news = self.hacknews.get_hackernews() self.client.send_message({ "type": "stream", "to": stream_name, "subject": stream_topic, "content": news }) if content[1].lower() == "cricnews": news = self.cricket.news() self.client.send_message({ "type": "stream", "subject": msg["subject"], "to": msg["display_recipient"], "content": news }) if content[1].lower() == "help" and len(content) == 2: message = self.help() self.client.send_message({ "type": "stream", "subject": msg["subject"], "to": msg["display_recipient"], "content": message }) if content[1].lower() == "help" and len(content) > 2: subkey = content[2] message = self.help_sub(subkey) self.client.send_message({ "type": "stream", "subject": msg["subject"], "to": msg["display_recipient"], "content": message }) if content[1].lower() == "twitter": #tweets = self.tw.get() #print(tweets) if len(content) > 2 and content[2] == "post": if self.tw.stream == msg["display_recipient"]: status = self.tw.post(" ".join(content[3:])) x = json.dumps(status._json) x = json.loads(x) message = "https://twitter.com/{}/status/{}".format( x["user"]["screen_name"], x["id_str"]) message = "Tweet Posted\n" + message self.client.send_message({ "type": "stream", "subject": msg["subject"], "to": msg["display_recipient"], "content": message }) else: message = "Use the stream **{}** to post a tweet".format( self.tw.stream) self.client.send_message({ "type": "private", "to": sender_email, "content": message }) if len(content) > 2 and content[2] == "post_image": if self.tw.stream == msg["display_recipient"]: status = self.tw.post_image(content[3], " ".join(content[4:])) if isinstance(status, str): message = status else: x = json.dumps(status._json) x = json.loads(x) message = "https://twitter.com/{}/status/{}".format( x["user"]["screen_name"], x["id_str"]) message = "Tweet Posted\n" + message self.client.send_message({ "type": "stream", "subject": msg["subject"], "to": msg["display_recipient"], "content": message }) else: message = "Use the stream **{}** to post a tweet".format( self.tw.stream) self.client.send_message({ "type": "private", "to": sender_email, "content": message }) if content[1] not in self.subkeys: ip = content[1:] ip = " ".join(ip) message = self.chatbot.get_response(ip).text self.client.send_message({ "type": "stream", "subject": msg["subject"], "to": msg["display_recipient"], "content": message }) if self.urls(" ".join(content)): summary = self.w.wiki(" ".join(content)) if summary: self.client.send_message({ "type": "stream", "subject": msg["subject"], "to": msg["display_recipient"], "content": summary }) elif "omega" in content and content[0] != "omega": self.client.send_message({ "type": "stream", "subject": msg["subject"], "to": msg["display_recipient"], "content": "Alas! Finally you called me :blush:" }) else: return